I have following code:
<?php
$select_options = array();
foreach($delivery_options as $option)
{
$select_options[$option->getDeviceId()] = $option->getDeviceName();
echo $select_options[$option->getDeviceId()];
}
echo $this->Form->input('default_device', array(
'type' => 'select',
'options' => $select_options,
'value' => $default_device,
'label' => '',
));
?>
In foreach loop every echo returns this:
abc'abc
In html source code it looks like this abc'abc
and then in select input: abc'abc
In html source code: abc'abc
It means that & char from abc'abc was converted to it's html encoding - & - but how did it happen?
I also tried htmlentities() and htmlspecialchars() but this still doesnt help...
The select input type allows for a special $option attribute called
'escape' which accepts a bool and determines whether to HTML entity
encode the contents of the select options. Defaults to true.
Try setting it to false.
echo $this->Form->input('default_device', array(
'type' => 'select',
'options' => $select_options,
'escape' => false, // like so
'value' => $default_device,
'label' => '',
));
Related
I have the following perl code in where I have a perl structure as follows:
`
use Data::Dumper;
my %data = (
'status' => 200,
'message' => '',
'response' => {
'name' => 'John Smith',
'id' => '1abc579',
'ibge' => '3304557',
'uf' => 'XY',
'status' => bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' )
}
);
my $resp = $data{'status'};
print "Response is $resp \n";
print Dumper(%data->{'response'});
Getting the status field works, however If I try something like this:
my $resp = $data{'response'}
I get Response is HASH(0x8b6640)
So I'm wondering if there's a way I can extract all the data of the 'response' field on the same way I can do it for 'status' without getting that HASH...
I've tried all sort of combinations when accessing the data, however I'm still getting the HASH back when I try to get the content of 'response'
$data{'response'} is the correct way to access that field on a hash called %data. It's returning a hash reference, which prints out by default in the (relatively unhelpful) HASH(0x8b6640) syntax you've seen. But if you pass that reference to Dumper, it'll show you everything.
print Dumper($data{'response'});
to actually access those subfields, you need to dereference, which is done with an indirection -> operation.
print $data{'response'}->{'name'}
The first access doesn't need the -> because you're accessing a field on a hash variable (i.e. a variable with the % sigil). The second one does because you're dereferencing a reference, which, at least in spirit, has the $ sigil like other scalars.
Thanks for your posts. I fixed the code as follows:
use Data::Dumper;
my %data = (
'status' => 200,
'message' => '',
'response' => {
'name' => 'John Smith',
'id' => '1abc579',
'ibge' => '3304557',
'uf' => 'XY',
'status' => bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' )
}
);
my $resp = $data{'response'};
print Dumper($resp);
Now it works like a charm, and I'm able to get the data I want.
please help me out with this..I've tried too many different things...
I'm trying to populate a woocommerce select field with data from the database.
// Add fields & settings to the custom product tab
$SQL = "SELECT DISTINCT table_name FROM wp_lbc_prices";
$array = $wpdb->get_results( $SQL, ARRAY_A);
add_action( 'woocommerce_product_data_panels',
'wcpt_roller_blind_options_product_tab_content' );
function wcpt_roller_blind_options_product_tab_content() {
?><div id='roller_blind_options' class='panel woocommerce_options_panel'><?php
?><div class='options_group'><?php
woocommerce_wp_select( array(
'id' => 'roller_blind_tables',
'label' => __( 'Price Tables', 'wcpt' ),
'placeholder' => '',
'desc_tip' => 'true',
'description' => __( 'Select Associated Price Table.', 'wcpt' ),
'options' => $array
));
?></div>
</div><?php
Certainly, the query to the DB works and a result is being returned... but I'm not sure how to make an acceptable array (I'm used to asp.net which seems to make this more simple!). The data I am returning does not need an ID so the value and text of the dropdown can be the same.
You need first to be sure of table_name or replace it by the correct column slug to be queried from your database table wp_lbc_prices.
You need to replace the WPDB method get_results() by get_col()which query a single column and gives an array natively.
Prepare the array to copying the values to the keys using array_combine()
I have completed your code with the hooked function that adds a custom product tab.
Your revisited code will be:
add_filter( 'woocommerce_product_data_tabs', 'add_roller_blind_product_data_tab' );
function add_roller_blind_product_data_tab( $tabs ) {
$tabs['roller_blind'] = array(
'label' => __( 'Roller blind', 'wcpt' ),
'target' => 'roller_blind_options', // <== to be used in the <div> class of the content
//'class' => array('show_if_simple'), // or 'hide_if_simple' or 'show_if_variable'…
);
return $tabs;
}
add_action( 'woocommerce_product_data_panels', 'display_roller_blind_product_data_tab_content' );
function display_roller_blind_product_data_tab_content() {
global $wpdb;
echo '<div id="roller_blind_options" class="panel woocommerce_options_panel">
<div class="options_group">';
$sql_query = $wpdb->get_col( "SELECT DISTINCT table_name FROM {$wpdb->prefix}wp_lbc_prices" );
$options = sizeof($sql_query) > 0 ? array_combine( $sql_query, $sql_query ) : array();
woocommerce_wp_select( array(
'id' => 'roller_blind_tables',
'label' => __( 'Price Tables', 'wcpt' ),
'placeholder' => '',
'desc_tip' => 'true',
'description' => __( 'Select Associated Price Table.', 'wcpt' ),
'options' => $options
));
echo '</div></div>';
}
It should better work now. But as this is a custom database table is not testable.
get_results function return an array with indexes so the values can be like array of objects like this array([0]=>object,[1]=>object) can you please share what you are getting in $array variable ?
I'm trying to load the list of network interface configuration files on Linux into the hash of hashes and further encode them into JSON. This is the code that I'm using:
#!/usr/bin/env perl
use strict;
use diagnostics;
use JSON;
use Data::Dumper qw(Dumper);
opendir (DIR, "/etc/sysconfig/network-scripts/");
my #configs =grep(/^ifcfg-*/, readdir(DIR));
my $output = "metadata/json_no_comment";
my %configuration;
my $key;
my $value;
my %temp_hash;
foreach my $input ( #configs) {
$input= "/var/tmp/rhel6.8/" . $input;
open (my $JH, '<', $input) or die "Cannot open the input file $!\n";
while (<$JH>) {
s/#.*$//g;
next if /^\s*#/;
next if /^$/;
for my $field (split ) {
($key, $value) = split /\s*=\s*/, $field;
$temp_hash{$key} = $value;
}
$configuration{$input} = \%temp_hash;
}
close $JH;
}
print "-----------------------\n";
print Dumper \%configuration;
print "-----------------------\n";
my $json = encode_json \%configuration;
open (my $JNH, '>', $output) or die "Cannot open the output file $!\n";
print $JNH $json;
close $JNH;
The data structure, that I'm getting is following:
$VAR1 = {
'/etc/sysconfig/network-scripts/ifcfg-lo' => {
'BOOTPROTO' => 'dhcp',
'NAME' => 'loopback',
'TYPE' => 'Ethernet',
'IPV6INIT' => 'yes',
'HWADDR' => '"52:54:00:65:e7:8c"',
'DEVICE' => 'lo',
'NETBOOT' => 'yes',
'NETMASK' => '255.0.0.0',
'BROADCAST' => '127.255.255.255',
'IPADDR' => '127.0.0.1',
'NETWORK' => '127.0.0.0',
'ONBOOT' => 'yes'
},
'/etc/sysconfig/network-scripts/ifcfg-eth0' => $VAR1->{'/etc/sysconfig/network-scripts/ifcfg-lo'}
};
The data structure, I'm looking for is the following:
$VAR1 = {
'/etc/sysconfig/network-scripts/ifcfg-lo' => {
'BOOTPROTO' => 'dhcp',
'NAME' => 'loopback',
'TYPE' => 'Ethernet',
'IPV6INIT' => 'yes',
'HWADDR' => '"52:54:00:65:e7:8c"',
'DEVICE' => 'lo',
'NETBOOT' => 'yes',
'NETMASK' => '255.0.0.0',
'BROADCAST' => '127.255.255.255',
'IPADDR' => '127.0.0.1',
'NETWORK' => '127.0.0.0',
'ONBOOT' => 'yes'
},
'/etc/sysconfig/network-scripts/ifcfg-eth0' => {
'BOOTPROTO' => 'dhcp',
'NAME' => '"eth0"',
'TYPE' => 'Ethernet',
'IPV6INIT' => 'yes',
'HWADDR' => '"52:54:00:65:e7:8c"',
'NETBOOT' => 'yes',
'ONBOOT' => 'yes'
}
};
Any idea what am I doing wrong? Why the first nested hash is created correctly and the second one is not? I suspect, that it has something to do with reading the files line by line, but I have to do it, because I need to filter out the commented lines before JSON conversion.
Thanks for any help.
Edit: I have modified the script as suggested by Borodin and it works. Thanks!
The problem is that $configuration{$input} always refers to the same hash %temp_hash because you have declared it at file level. You need to created a new hash for each config file by declaring %temp_hash inside the for loop
Also note that next if /^\s*#/ can have no effect because you just deleted any hashes in the line. Your sanitisation should look like
s/#.*//;
next unless /\S/;
I have following data :
Array
(
[category] => Array
(
[0] => d
[1] => 100
[2] => 100
[3] => 100
)
[volume] => Array
(
[0] => 100
[1] => 100
[2] => 100
)
[urgency] => Array
(
[0] => 100
[1] => 100
[2] => 100
)
[importance] => Array
(
[0] => 100
[1] => 100
[2] => 100
)
)
And I created DynamicModel for it with rules "each value should be integer" (added in 2.0.4).
$view_model = DynamicModel::validateData(compact('category', 'volume', 'urgency', 'importance'), [
[['category', 'volume', 'urgency', 'importance'], 'each', 'rule' => ['integer']],
]);
In view I have:
<?= $form->field($model, 'category[0]')->textInput() ?>
<?= $form->field($model, 'category[1]')->textInput() ?>
<?= $form->field($model, 'category[2]')->textInput() ?>
...
<?= $form->field($model, 'importance[2]')->textInput() ?>
Problem is, when I submit form with "d" in first input, I have errors on each "category" input:
What I do wrong?
You can use Each validator
Info: This validator has been available since version 2.0.4.
[
// checks if every category ID is an integer
['categoryIDs', 'each', 'rule' => ['integer']],
]
This validator only works with an array attribute. It validates if every element of the array can be successfully validated by a specified validation rule. In the above example, the categoryIDs attribute must take an array value and each array element will be validated by the integer validation rule.
rule: an array specifying a validation rule. The first element in the array specifies the class name or the alias of the validator. The rest of the name-value pairs in the array are used to configure the validator object.
allowMessageFromRule: whether to use the error message returned by the embedded validation rule. Defaults to true. If false, it will use message as the error message.
Note: If the attribute value is not an array, it is considered validation fails and the message will be returned as the error message.
This answer is applicable to ajax request scenarios
In your controller
use yii\base\Model;
use yii\widgets\ActiveForm;
use yii\web\Response;
public function actionCreate()
{
$models = [
'model1' => new Category,
'model2' => new Category,
];
if (Yii::$app->request->isAjax && Model::loadMultiple($models, Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
$validate = [];
$validate = array_merge(ActiveForm::validateMultiple($models), $validate);
// If you need to validate another models, put below.
// $validate = array_merge(ActiveForm::validate($anotherModel), $validate);
return $validate;
}
if (Model::loadMultiple($models, Yii::$app->request->post())) {
foreach($models as $key => $model) {
$model->save();
}
}
return $this->render('create', [
'models' => $models,
]);
}
In your view
<?php
$form = ActiveForm::begin([
'enableClientValidation' => false,
'enableAjaxValidation' => true,
]);
?>
<?= $form->field($models['model1'], '[model1]name')->textInput(); ?>
<?= $form->field($models['model2'], '[model2]name')->textInput(); ?>
<?= Html::submitButton('Create') ?>
<?php ActiveForm::end(); ?>
Here is the sample code from Yii2 checkboxList, I want to add custom class for each Item in checkboxList but I don't know how and where can I add that!
Could you please help me please ..
$list = [0 => 'PHP', 1 => 'MySQL', 2 => 'Javascript'];
$list2 = [0,2];
echo Html::checkboxList('CuisineId',$list2,$list,array('class' => 'test' ));
Thanks in advance.
If you want to add the same class, you should use itemOptions :
echo Html::checkboxList('CuisineId', $list2, $list, ['itemOptions'=>['class' => 'test']]);
Or if you want a custom class for each item, you should use item callback :
echo Html::checkboxList('CuisineId', $list2, $list, ['item'=>function ($index, $label, $name, $checked, $value){
return Html::checkbox($name, $checked, [
'value' => $value,
'label' => $label,
'class' => 'any class',
]);
}]);
Read more : http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#checkboxList()-detail
EDIT : add example
Just in case you only need to change the label options:
<?= Html::checkboxList('CuisineId', $list, $items, [
'itemOptions' => [
'labelOptions' => [
'style' => 'font-weight: normal',
'class' => 'some-custom-class',
],
],
]) ?>
Note: Everything you put inside itemOptions will be passed to Html::checkbox() as its own options when creating each checkbox. It means you can pass class, style, label, labelOptions, etc.