Zend Form Radio Default Checked - php

I have the next radio button group:
$enabled = $this->createElement('radio', 'enabled')
->setLabel('Enabled')
->setMultiOptions(array('1'=>'yes', '0'=>'no'))
->setValue($rank_values['enabled'])
->setAttrib('id', 'enabled')
->setAttrib('class', $action . '_enabled')
->setSeparator('');
How can I set a checked radio? Now, when I open my script, there are not selected radio. I want to select 'yes'. How?
Thank you.

it is much more easier :)
$enabled = $this->createElement('radio', 'enabled')
->setLabel('Enabled')
->setMultiOptions(array('1'=>'yes', '0'=>'no'))
->setValue($rank_values['enabled'])
->setAttrib('id', 'enabled')
->setAttrib('class', $action . '_enabled')
->setSeparator('')
->setValue("1");

In case somebody wonders, I'm using the array notation to declare all my elements in my forms and in zend framework 2 to have a default option selected in a radio button you have to add the attribute value and make it have the key of the value_options you want to be selected by default:
// Inside your constructor or init method for your form //
$this->add(
[
'type' => 'Radio',
'name' => 'some_radio',
'options' => [
'value_options' => [
'opt1' => 'Radio option 1',
'opt2' => 'Radio option 2'
]
],
'attributes' => [
'value' => 'opt1' // This set the opt 1 as selected when form is rendered
]
]
);
I found some examples a little confusing because they were using numeric keys in the value options (0, 1) so when I saw 'value' => 1 it wasn't obvious for me that this was the key in the value_options array. Hope this helps someone.

Use this:
->setAttrib("checked","checked")
So that your complete code looks like this:
$enabled = $this->createElement('radio', 'enabled')
->setLabel('Enabled')
->setMultiOptions(array('0'=>'no', '1'=>'yes'))
->setAttrib("checked","checked")
->setValue($rank_values['enabled'])
->setAttrib('id', 'enabled')
->setAttrib('class', $action . '_enabled')
->setSeparator('');
[EDIT] Using setValue:
You can alternatively use this:
->setValue('1')
This will check the option represented by value 1 which is yes.

According to the manual, you would do it this way if you were to use array notation: link to manual
$this->add(
[
'name' => 'someRadioMethod',
'type' => 'radio',
'options' => [
'label' => 'Some descriptive label',
'value_options' => [
[
'value' => '1',
'label' => 'Label for 1',
'selected' => true,
],
[
'value' => '2',
'label' => 'Label for 2',
'selected' => false,
]
],
],
]
);

I found that if you have a filter set then ->setvalue('X') does not work.
I removed ->addFilter('StringToLower')
and added ->setSeparator('')->setValue('N');
Worked a treat

Yeah. I have resolved it using jQuery:
jQuery(document).ready(function(){
var $radios = $('input:radio[name=enabled]');
if($radios.is(':checked') === false) {
$radios.filter('[value=1]').attr('checked', true);
}
});

Related

Using radioList method with ActiveField in Yii2 to provide different options per radio box

I'm using the radioList method within the ActiveField widget and I'm trying to work out how to set different options for different radio boxes within the same list.
I have this...
$form->field($model, 'some_question')->inline()->radioList(
[
1 => Yii::t('general', 'Yes'),
0 => Yii::t('general', 'No')
],
['itemOptions' => ['value' => 1, 'data-foo' => 'bar']]
)->label(false);
But whatever I set in itemOptions gets set on all radio buttons - is there a way to set different values for each one?
Use callable item for this.
$form->field($model, 'some_question')->inline()->radioList(
[
1 => Yii::t('general', 'Yes'),
0 => Yii::t('general', 'No')
],
['item' => function ($index, $label, $name, $checked, $value) {
switch ($value) {
// different options per value
case 1:
$options = [
'data-foo' => 'bar'
];
break;
case 0:
$options = [
'data-next' => 'smthng'
];
}
return \yii\bootstrap\Html::radio($name, $checked, array_merge($options, [
'value' => $value,
'label' => \yii\bootstrap\Html::encode($label),
]));
}]
)->label(false);

How can I make typeahead show database information in yii2?

I want to make search in my project. I use typeahead but it's not working. This is my code:
<?php
echo '<label class="control-label">Select Repository</label>';
$template = '<div><p class="repo-language">{{no_telepon}}</p>' .
'<p class="repo-name">{{nama}}</p>' .
'<p class="repo-description">{{email}}</p></div>';
echo Typeahead::widget([
'name' => 'twitter_oss',
'options' => ['placeholder' => 'Filter as you type ...'],
'dataset' => [
[
'prefetch' => Penerima::find()->all(),
'datumTokenizer' => "Bloodhound.tokenizers.obj.whitespace('value')",
'display' => 'value',
'templates' => [
'notFound' => '<div class="text-danger" style="padding:0 8px">Unable to find repositories for selected query.</div>',
'suggestion' => new JsExpression("Handlebars.compile('{$template}')")
]
]
]
]);
?>
This question was asked long time a go.
I also faced the same problem, but i could figure-out this.
for future reference i add this post.
in your controller
$result = SampleModel::find()
->select('Attribute_name')
->where('name LIKE "%' . $searchParameter .'%"')
->asArray()
->all();
return Json::encode($result);
here you need to get the database value as "associative array", you can get that from using "asArray()".
then as you see return value as Json encode.
in your "View"
<?php
echo Typeahead::widget([
'name' => 'sampleName',
'options' => ['placeholder' => 'Filtering data ...'],
'scrollable' => true,
'pluginOptions' => ['highlight'=>true],
'dataset' => [
[
'remote' => [
'url' => Yii::$app->urlManager->createUrl(['sample/action']) .
'?searchParameter=%QUERY',
'wildcard' => '%QUERY'
],
'datumTokenizer' => "Bloodhound.tokenizers.obj.whitespace('Atribute_name')",
'display' => 'Atribute_name',
'limit' => 10,
],
],
'pluginEvents' => [
'typeahead:select' => 'function(e, s) {
EnableUserDetailsTypeAhead(s);
}',
]
]);
?>
here few things to be consider.
calling to the controller action. you can do that.
Yii::$app->urlManager->createUrl(['sample/action']) .
'?searchParameter=%QUERY',
'wildcard' => '%QUERY'
],
the below lines inside data set must be provide.
'datumTokenizer' => "Bloodhound.tokenizers.obj.whitespace('Atribute_name')",
'display' => 'Atribute_name',
you will get the expected data.
this sample code i have tested and this is working
From the docs:
prefetch: array, configuration for the prefetch options object. Refer documentation for the options you can set for this parameter. The return data must be Json encoded and converted to an associative array of the format [['value' => 'data1'], ['value' => 'data2'],...], where value is the fixed key set in display
You are passing an array of objects instead of an array of key value pairs. You can use asArray to create a list of objects. You will need to change display to the name of the field containing the data:
'prefetch' => Penerima::find()->select('title')->asArray()->all(),

PHP Help for Echoing Variables

I'm a beginner in writing PHP, but working on developing themes in WordPress.
I have no idea how to echo my style option within my front-page.php.
My meta.php:
$meta_style = array();
$meta_style['meta_style'] = array(
'dash_icon' => 'list-view',
'title' => __('Section Settings', 'fluent'),
'description' => __('These are general section settings.','fluent'),
'context' => 'normal',
'priority' => 'high',
'option_name' => 'meta_style',
'caps' => array(),
'fields' => array(
'style' => array(
//...
'type' => 'select',
'options' => array(//option value = option label
'value' => 'white',
'value2' => 'black'
),
'multiple' => false,//allow multiple values to be selected - default false
'placeholder' => 'white'//placeholder text for the element
),
),
);
My front-page.php (it's wrapped in a BUTTON just a see if the variable echoes):
<button>
<? if($meta = get_post_meta($post->ID)){ if($meta['style'] == true){ echo $meta['value']; } } ?>
</button>
Can anyone provide an additional examples on how to echo other types, such as 'type' => 'text'?
I dont know exactly what you want, but you should:
1 - See if you're echoing the right information
2 - Use var_dump()
In your first code example you have a variable $meta_style which is a map. It has one key, 'meta_style' that leads to a next map. Inside that inner map you have the keys 'dash_icon' and so on. So for example this should echo the string 'normal':
echo $meta_style['meta_style']['context'];
However, in your second example, you have a variable $meta which is also a map, having keys 'style' and 'value'. You could echo those with:
echo $meta['style'];
echo $meta['value'];
Based on your example, I have no idea what these should do or how they should be related, or what their meaning should be.

Overwriting zend form checkbox

I have a problem with the zend form checkbox.
$this->addElement('checkbox', 'languages', array(
'label' => 'Languages',
'class' => 'check_1',
'name' => 'checkset',
'checkedValue' => '1',
'uncheckedValue'=> '0'
));
I made this checkbox and overwritten the checkedValue and uncheckedValue but when I debug it, it has totally different values:
$values = $form_duplicate->getValues();
var_dump($values);
This is the result:
["languages"]=> string(1) "0"
I can't understand where is the problem. I looked up on the zend documentation page and this is how it must be.
I'm not sure I understand your problem, but you can use the setCheckedValue and setUncheckedValue methods to change defaults values like this:
$langages = new Zend_Form_Element_Checkbox('languages', array(
'label' => 'Languages',
'class' => 'check_1',
'name' => 'checkset'
));
$langages->setCheckedValue('value_check');
$langages->setUncheckedValue('value_uncheck');
$this->addElement($langages);
And to recover your values:
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
// isValid($formData) filled the form with the datas returned
if ($form_duplicate->isValid($formData)) {
// treatment
}
$values = $form_duplicate->getValues();
var_dump($values);
}

customize sort up/down Yii CGridView button

so, I want to make a new button in my CGridView. This is up & down arrow buttons which is will be used for sorting my articles. I've read a lot of how to make this kind of buttons. I already read the wiki of how to use this CGridView button also in this link.
And now I have this in my view :
array(
'header' => 'Action',
'class' => 'CButtonColumn',
'template' => '{moveup}{movedown}{view}{delete}',
'htmlOptions' => array('style' => 'width: 68px'),
'buttons' => array
(
'moveup' => array
(
'label' => 'Move Up',
'imageUrl' => Yii::app()->request->baseUrl . '/images/move_up.png',
'url' => 'Yii::app()->createUrl("KB/moveup", array("id"=>$data->KBID))',
'visible' => '$data->KBORDER == KB::model()->getMax()',
),
'movedown' => array
(
'label' => 'Move Down',
'imageUrl' => Yii::app()->request->baseUrl . '/images/move_down.png',
'url' => 'Yii::app()->createUrl("KB/movedown", array("id"=>$data->KBID))',
'visible' => '$data->KBORDER == KB::model()->getMin()',
),
),
),
and this one in my model :
public function getMax(){
$sql = 'SELECT MAX(KBORDER) FROM KB';
$max = Yii::app()->db->createCommand($sql);
$max->queryAll();
return $max;
}
public function getMin(){
$sql = 'SELECT MIN(KBORDER) FROM KB';
$min = Yii::app()->db->createCommand($sql);
$min->queryAll();
return $min;
}
All that codes running just fine. except for the visibility. I want to make the up button become invisible when it has the highest value of KBORDER or when it position is in the 1st place. And for the down button, it supposed to be invisible too when it has the lowest value of KBORDER or when it position is in the last place. but, when I put that code in my 'visible', all the buttons are invicible.
so my question is, how to make my request happen?
thanks in advance
First off, queryAll returns an array. Documentation. So you should probably use queryScalar, and you should return the result from the function, not the command object.
return $max->queryScalar();
You could also use a statistical query in Yii.
Secondly, you want to SHOW the button when it is not in the top or bottom respectivily, so you should negate the =
'visible' => '$data->KBORDER != KB::model()->getMax()',
and
'visible' => '$data->KBORDER != KB::model()->getMin()',

Categories