Yii2 ChartJs throws A non-numeric value encountered error at page - charts

I have installed a 2amigos/yii2-chartjs-widget to my yii2 project via composer and after installing it I am trying to tun the example as shown in the documentation.
<?php
ChartJs::widget([
'type' => 'pie',
'id' => 'structurePie',
'options' => [
'height' => 200,
'width' => 400,
],
'data' => [
'radius' => "90%",
'labels' => ['Label 1', 'Label 2', 'Label 3'], // Your labels
'datasets' => [
[
'data' => ['35.6', '17.5', '46.9'], // Your dataset
'label' => '',
'backgroundColor' => [
'#ADC3FF',
'#FF9A9A',
'rgba(190, 124, 145, 0.8)'
],
'borderColor' => [
'#fff',
'#fff',
'#fff'
],
'borderWidth' => 1,
'hoverBorderColor'=>["#999","#999","#999"],
]
]
],
'clientOptions' => [
'legend' => [
'display' => false,
'position' => 'bottom',
'labels' => [
'fontSize' => 14,
'fontColor' => "#425062",
]
],
'tooltips' => [
'enabled' => true,
'intersect' => true
],
'hover' => [
'mode' => false
],
'maintainAspectRatio' => false,
],
'plugins' =>
new \yii\web\JsExpression('
[{
afterDatasetsDraw: function(chart, easing) {
var ctx = chart.ctx;
chart.data.datasets.forEach(function (dataset, i) {
var meta = chart.getDatasetMeta(i);
if (!meta.hidden) {
meta.data.forEach(function(element, index) {
// Draw the text in black, with the specified font
ctx.fillStyle = rgb(0, 0, 0);
var fontSize = 16;
var fontStyle = normal;
var fontFamily = Helvetica;
ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
// Just naively convert to string for now
var dataString = dataset.data[index].toString()+'%';
// Make sure alignment settings are correct
ctx.textAlign = center;
ctx.textBaseline = middle;
var padding = 5;
var position = element.tooltipPosition();
ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
});
}
});
}
}]')
])
?>
But when I refresh my page I am getting this error
A non-numeric value encountered
The error occurs at var dataString = dataset.data[index].toString()+'%';
I have been trying to solve this issue but I couldn't find anything
Any help would be highly appreciated.

Its because you are not escaping the quotes correctly you need to escape the single quotes in the statement
var dataString = dataset.data[index].toString()+' % ';
because your outer quotes in the new yii\db\Expression() are using single quotes to wrap the whole javascript, so change the line to
var dataString = dataset.data[index].toString()+\' % \';

Related

Disable field in TCA when editing a record

Is it possible to disable a field in the TCA config, only when editing a record?
TCA config for new record:
'title' => [
'exclude' => true,
'label' => 'Title',
'config' => [
'type' => 'input',
'size' => 30,
'eval' => 'trim,required'
],
],
TCA config for existing records:
'title' => [
'exclude' => true,
'label' => 'Title',
'config' => [
'type' => 'input',
'size' => 30,
'eval' => 'trim,required'
'readOnly' => true,
],
],
I'm not aware of a built in solution for different TCA settings for new and existing records.
Since the final TCA is cached there is also no way to manipulate it with some PHP on runtime.
It is possible to add Javascript in the backend. With this Javascript your are able, to disable fields on the fly. But be aware, that this is just a hacky workaround which can easily be overcome!
Add Javascript in ext_localconf.php:
if (TYPO3_MODE === 'BE') {
$renderer = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Page\PageRenderer::class);
$renderer->addJsFile(
'EXT:myext/Resources/Public/JavaScript/Backend.js'
);
}
In Backend.js you can do something like this:
require(["jquery"], function ($) {
const queryString = decodeURI(window.location.search),
urlParams = new URLSearchParams(queryString);
if (urlParams.has('route') && urlParams.get('route') == '/record/edit') {
// check, that you just do changes, if you edit records of the desired model
if (queryString.indexOf('edit[tx_myextension_domain_model_model][')) {
let idPosStart = queryString.indexOf('edit[tx_myextension_domain_model_model][') + 40,
idPosEnd = queryString.indexOf(']=', idPosStart),
idLength = idPosEnd - idPosStart,
idEl = queryString.substr(idPosStart, idLength),
elVal = urlParams.get('edit[tx_myextension_domain_model_model][' + idEl + ']');
if (elVal == 'edit') {
// Delay everything a little bit, otherwise html is not fully loaded and can't be addressed
setTimeout(function () {
// disable desired fields, eg field "title"
let titleField = $('[data-field="title"]').parents('.form-section');
titleField.find('input').prop('disabled', true);
titleField.find('button.close').remove();
}, 800);
}
}
}
}

when selecting an option, show data from the database - Woocommerce custom fields (checkout)

I have the following code to generate a select and bring the values inside the options:
add_action('woocommerce_after_order_notes', 'cliente_woocommerce');
function cliente_woocommerce($checkout)
{
global $wpdb;
/// in tab_clientes have id, nome, cpf, cnpj, ie, email, data_since columns
$results = $wpdb->get_results("SELECT * FROM tab_clientes");
$options = ['' => __('Selecione o cliente')];
foreach ($results as $result) {
$options[$result->nome] = $result->razao_social;
}
echo '<div id="cliente_woocommerce"><h2>' . __('Cliente') . '</h2>';
woocommerce_form_field(
'cliente',
[
'type' => 'select',
'class' => ['cliente form-row-wide'],
'label' => __('Campo de Teste (Cliente)'),
'options' => $options,
],
$checkout->get_value('cliente')
);
woocommerce_form_field(
'nome',
[
'type' => 'text',
'class' => ['nome form-row-wide'],
'label' => __('Razão Social'),
'default' => '',
],
$checkout->get_value('nome')
);
woocommerce_form_field(
'cnpj',
[
'type' => 'text',
'class' => ['cnpj form-row-wide'],
'label' => __('CNPJ'),
'default' => '',
],
$checkout->get_value('cnpj')
);
echo '</div>';
}
with the following script:
$(document).ready(function()
{
$('#cliente').change(function() {
$('#nome').val( $( this ).val() );
});
$('#nome').change(function() {
$('#cnpj').val( $( this ).val() );
});
});
When I select the client, the #nome field (razão social - in the table = razao_social) appears with the correct value, but the value repeats within CNPJ field.
what am I doing wrong?

custom attribute displaying but is not saving in magento 2 admin customer creation form

i have created new customer attribute in my magento 2 environment
field is added the data in that filed is not saving.i am getting error as something went wrong while saving data.there is no good tutorials i could find to add new attribute.please help with this.
i have followed this code
https://magento.stackexchange.com/questions/128178/magento-2-add-custom-attribute-in-customer-registration-form
Customer Registration Custom attribute value create in admin and save
1. Text Field
2. Drop Down Field
3. Date Field
Using UpgradeSchema.php
<?php
namespace {CompanyName}\{ModuleName}\Setup;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetup;
/* irrelevant */
#use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
/* irrelevant */
#use Magento\Framework\Setup\SchemaSetupInterface;
/* add this */
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class UpgradeData implements UpgradeDataInterface
{
private $customerSetupFactory;
public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory)
{
$this->customerSetupFactory = $customerSetupFactory;
}
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
if (version_compare($context->getVersion(), '1.0.1', '<'))
{
// For Text field
$customerSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'attribute_title',
[
'type' => 'text',
'input' => 'text',
'label' => 'Attribute Title',
'required' => false,
'visible' => true,
'user_defined' => false,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
]
);
$attribute_title = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'attribute_title')
->addData(
['used_in_forms' => ['adminhtml_customer']
]);
$attribute_title->save();
//Add field Drop Down for Yes/No
$customerSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'is_attribute',
[
'type' => 'int',
'input' => 'select',
'label' => 'Is Attribute',
'frontend' => '',
'default' => '1',
'class' => '',
'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
'backend' => 'Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend',
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
'required' => false,
'visible' => true,
'user_defined' => false,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
]
);
$is_attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'is_attribute')
->addData(
['used_in_forms' => ['adminhtml_customer']
]);
$is_attribute->save();
// For Date And Time field
$customerSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'custom_date',
[
'label' => 'Custom Date',
'type' => 'datetime',
'input' => 'date',
'frontend' => 'Magento\Eav\Model\Entity\Attribute\Frontend\Datetime',
'backend' => 'Magento\Eav\Model\Entity\Attribute\Backend\Datetime',
'validate_rules' => '{"input_validation":"date"}',
'user_defined' => false,
'required' => false,
'visible' => true,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
]
);
$custom_date = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'custom_date')
->addData(
['used_in_forms' => ['adminhtml_customer']
]);
// more used_in_forms ['adminhtml_checkout','adminhtml_customer','adminhtml_customer_address','customer_account_edit','customer_address_edit','customer_register_address']
$commenced_business->save();
}
}
}
Data save will not happen by itself you need to set data into attribute.
If its part of customer Interface
For example
$attribute = $customer->getCustomAttribute('client_dn');
if ($attribute)
{
$customer->setValue("hi");
}
if you are saving using customer object
$customer->setData('client_dn', 'Hi');

drupal 7 date_popup module (update minDate onSelect event)

I'm using drupal 7 module date (date_popup). I have 2 datepickers. I need to update minDate on the second datepicker on "onSelect" event by click on the first one. It works but only for the second click. If I click on the first datepicker and select date nothing happens and minDate is not updated. When I select the second time it works well. Why doesn't it work from my first click?
Here is my datepicker init php code for my module.
<?php
$form['leave'] = array(
'#type' => 'date_popup', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
'#title' => t('Leave'),
'#default_value' => date('Y-m-d'),
'#date_format' => $format,
'#required' => TRUE, // Added
'#date_label_position' => 'within', // See other available attributes and what they do in date_api_elements.inc
'#date_increment' => 15, // Optional, used by the date_select and date_popup elements to increment minutes and seconds.
'#date_year_range' => '-3:+3', // Optional, used to set the year range (back 3 years and forward 3 years is the default).
'#datepicker_options' => array(
'changeMonth' => false,
'changeYear' => false,
'altField' => '#edit-leave-alt',
'showOtherMonths' =>true,
'selectOtherMonths' =>false,
'altFormat' => 'D, M d, yy',
'minDate' => 0,
), // Optional, as of 7.x-2.6+, used to pass in additional parameters from the jQuery Datepicker widget.
'#attributes' => array('readonly' => 'readonly')
);
$form['leave'] = array(
'#type' => 'date_popup', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
'#title' => t('Leave'),
'#default_value' => date('Y-m-d'),
'#date_format' => $format,
'#required' => TRUE, // Added
'#date_label_position' => 'within', // See other available attributes and what they do in date_api_elements.inc
'#date_increment' => 15, // Optional, used by the date_select and date_popup elements to increment minutes and seconds.
'#date_year_range' => '-3:+3', // Optional, used to set the year range (back 3 years and forward 3 years is the default).
'#datepicker_options' => array(
'changeMonth' => false,
'changeYear' => false,
'altField' => '#edit-leave-alt',
'showOtherMonths' =>true,
'selectOtherMonths' =>false,
'altFormat' => 'D, M d, yy',
'minDate' => 0,
), // Optional, as of 7.x-2.6+, used to pass in additional parameters from the jQuery Datepicker widget.
'#attributes' => array('readonly' => 'readonly')
);
?>
Here is my js code
(function($) {
Drupal.behaviors.ifly_search = {
attach: function (context, settings) {
$("#edit-leave-datepicker-popup-0").datepicker({
onSelect: function(date,param) {
var data = new Date(param.currentYear, param.currentMonth, param.currentDay);
$("#edit-return-datepicker-popup-0").datepicker("option", "minDate", data).val(date);
},
});
}
};
})(jQuery);
Just to flesh out my comment. Try this instead:
(function($) {
Drupal.behaviors.ifly_search = {
attach: function (context, settings) {
$("#edit-return-datepicker-popup-0").datepicker({minDate: new Date()});
$("#edit-leave-datepicker-popup-0").datepicker({
onSelect: function(date,param) {
var data = new Date(param.selectedYear, param.selectedMonth, param.selectedDay);
$("#edit-return-datepicker-popup-0").datepicker("option", "minDate", data).val(date);
},
});
}
};
})(jQuery);
Skarist, thank you a lot!
Here is the working code:
Drupal.behaviors.ifly_search = {
attach: function (context, settings) {
$("#edit-leave-datepicker-popup-0").datepicker({
onSelect: function(date,param) {
var data = new Date(param.selectedYear, param.selectedMonth, param.selectedDay);
$("#edit-return-datepicker-popup-0").datepicker({minDate: data}).val(date);
$("#edit-return-datepicker-popup-0").datepicker("option", "minDate", data).val(date);
},
});
}
};

What are the correct parameters for Magento Product Attribute creation in Perl

I've got several calls working already, but for the life of me I can't figure out how to make product_attribute.create work. I'm always getting a 102 Invalid request parameters or 623 Wrong Method Signature.
making the call like this my $res = $self->_useragent->call( call => $self->_session, #{$payload} ); (note: useragent is a XML::RPC object.
This Dumper $payload;
$VAR1 = [
'product_attribute.create',
[
'test',
{
'frontend_label' => [
{
'label' => 'Test ME',
'store_id' => 0
}
],
'scope' => 'store',
'frontend_input' => 'text'
}
]
];
I've read the API Documentation but figuring out what the call should look like in Perl is tricky.
I'm not familiar with the XML-RPC library you're using in perl, but he error you're seeing is a Magento API exception, configured in
<!--File: app/code/core/Mage/Catalog/etc/api.xml -->
<!-- ... -->
<invalid_parameters>
<code>102</code>
<message>Invalid request parameters.</message>
</invalid_parameters>
<!-- ... -->
Using the exception's name, you can find the place Magento threw it
#File: app/code/core/Mage/Catalog/Model/Product/Attribute/Api.php
//...
if (empty($data['attribute_code']) || !is_array($data['frontend_label'])) {
$this->_fault('invalid_parameters');
}
//...
So, my guess is your call is correct, you're just missing an attribute_code.
After some digging through Magento's code, I copied this from the test suite and it converted to perl, it appears to work. maybe all attributes are required.
$VAR1 = [
'product_attribute.create',
[
{
'default_value' => '1',
'is_configurable' => 0,
'used_in_product_listing' => 0,
'is_visible_on_front' => 0,
'apply_to' => [
'simple'
],
'is_comparable' => 0,
'is_used_for_promo_rules' => 0,
'is_required' => 0,
'scope' => 'store',
'is_unique' => 0,
'frontend_input' => 'text',
'is_searchable' => 0,
'attribute_code' => 'unique_code',
'is_visible_in_advanced_search' => 0,
'frontend_label' => [
{
'label' => 'some label',
'store_id' => '0'
}
]
}
]
];
Further experimentation somewhat based on Alan Storm's Answer, suggest that the following fields are required, as I was not able to successfully create a request without all of these fields at minimum being defined.
$VAR1 = [
'product_attribute.create',
[
{
'frontend_input' => 'text',
'attribute_code' => 'test1374438470',
'frontend_label' => [
{
'store_id' => 0,
'label' => 'Test ME'
}
]
}
]
];