cakephp: How to set checkbox to checked? - cakephp

I am using
$form->input('Model.name', array('multiple'=>'checkbox');
I am trying to base on model data to set certain checkboxes to checked.
How can i do that?

cmptrgeekken's solution works for a single checkbox. I'm assuming you're generating a multiple checkboxes, for a HABTM relation or something similar.
You need to pass a array with the values of the elements that are going to be selected to the method, like this:
$options = array(1 => 'ONE', 'TWO', 'THREE');
$selected = array(1, 3);
echo $form->input('Model.name', array('multiple' => 'checkbox', 'options' => $options, 'selected' => $selected));
is going to generate this:
<div class="input select">
<label for="ModelName">Name</label>
<input name="data[Model][name]" value="" type="hidden">
<div class="checkbox">
<input name="data[Model][name][]" checked="checked" value="1" id="ModelName1" type="checkbox">
<label for="ModelName1" class="selected">ONE</label>
</div>
<div class="checkbox">
<input name="data[Model][name][]" value="2" id="ModelName2" type="checkbox">
<label for="ModelName2">TWO</label>
</div>
<div class="checkbox">
<input name="data[Model][name][]" checked="checked" value="3" id="ModelName3" type="checkbox">
<label for="ModelName3" class="selected">THREE</label>
</div>
</div>
The first and third checkbox checked.
Just remember that you're actually working with a multiple select element that is just displayed as a bunch of checkboxes (Which is IMO better because of the usability).

I don't use CakePHP, but according to the docs, it appears as though you should be able to add the option 'checked'=>true:
$form->input('Model.name', array('type'=>'checkbox','checked'=>true));
since that's one of the options of the checkbox function.

$options = array(1 => 'ONE', 'TWO', 'THREE');
$selected = array(1, 3);
echo $form->input('Model.name',
array(
"name"=>$mnus['Aco']['id'],
"type"=>"select",
"multiple"=>"checkbox",
'options' => $options,
'selected' => $selected)
);
this is the correct way for multiple check box and checked option. I am using this in cake1.3 please recheck once on your code it must work.

echo $this->Form->input('Title', array('type'=>'checkbox', 'label'=>'Label', 'checked'=>'checked'));

The Marko solution still working in CakePHP 2.0+
-> https://stackoverflow.com/a/1962499/3197383
It just need to correct with the new syntax :
<?php
$options = array(1 => 'ONE', 'TWO', 'THREE');
$selected = array(1, 3);
echo $this->Form->input('ModelName',
array('multiple' => 'checkbox', 'options' => $options, 'selected' => $selected)
);
?>

Its Super Simple
$form->input('field_name', array('type'=>'checkbox','checked'=>true));
That's it.
Documentation: https://book.cakephp.org/3.0/en/views/helpers/form.html

Another way to have a checkbox checked with the "label" right next to it is.
$form->checkbox('Model.name', array('checked'=>'checked'))?> Label
Label can be what ever you want though. example: 21,000-3000, Tire, Human. I am sure you get the idea.

<?php
$subjects = array(1=>'Snow boarding',2=>'Surfing',3=>'Trekking',4=>'Swimming');
$selected_skills = array(0=>2,1=>4);
// For MutiSelect box with selected
$form->input('skills_list',array('label' => 'Skills','options' => $subjects,'class' =>'','multiple'=>true,'selected'=> $selected_skills));
//For Multiple checkbox with checked
$form->input('skills_list',array('label' => 'Skills','options' => $subjects,'class' =>'','multiple'=>'checkbox','selected'=> $selected_skills));
?>

Here is a small code snippet from one of my project-
$categories = $this->Site->Category->find('list', array('recursive' => -1));
$this->set(compact('categories'));
$this->Site->Category->bindModel(array('hasOne' => array('CategoriesSite')));
$selected = $this->Site->Category->find('list', array(
'fields' => array('id'),
'conditions' => array(
'CategoriesSite.site_id' => $this->data['Site']['id'],
),
'recursive' => 0,
));
$this->set(compact('selected'));
Main key is for selected is 'fields' => array('id')

$options = array("fixed","varry");
$selected = "0";
echo $form->input('Model.name', array('multiple' => 'checkbox', 'options' => $options, 'value' => $selected));
Use the value attribute to make checked default.

'likes_preferences' =>array(
'type'=>'select','label' => 'Main likes/preferences',
'options' => $this->Ethos->toOptionsArray('preferences'),
'multiple' => 'checkbox',
'div'=>array('class'=>'input select checkbox-group clearfix'),
'hiddenField' => false,
),
the above code for adding the data, you need to change the field 'likes_preferences' from array to comma separated string before saving into database.
$preferences = implode(',',$this->request->data['Member']['likes_preferences']);
$this->request->data['Member']['likes_preferences'] = $preferences;
EDIT MODE
$likes = explode(',',$this->request->data['Member']['likes_preferences']);
'likes_preferences' =>array(
'type'=>'select','label' => 'Main likes/preferences',
'options' => $this->Ethos->toOptionsArray('preferences'),
'multiple' => 'checkbox',
'div'=>array('class'=>'input select checkbox-group clearfix'),
'hiddenField' => false,
'selected' => $likes
),
you are done, again you must convert the array to string while updating the database in edit action.

You can also try this for input with single option
$this->Form->input('name', array('type' => 'checkbox', 'default' => 1, 'checked' => 'checked'));

Related

CakePHP2 - Default value for input - select with option multiple

I have Form input with multiple select options. I am unable to set default values. This is my code:
<?= $this->Form->input('PaymentMethods', array(
'type' => 'select',
'multiple' => true,
'label' => false,
'options' => array(
'cash'=>'cash',
'invoice'=>'invoice',
'ax'=>'ax',
'ca'=>'ca',
'vi'=>'vi',
'tp'=>'tp',
'dc'=>'dc'
),
'default'=>'ax'
)); ?>
How do I set default values for this input with PHP only?
This is working on my system. You can also set it from controller like this :
$this->request->data[$this->modelClass]['PaymentMethods'] = 'ax';
Please check these url also
CakePHP select default value in SELECT input
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
example :
$sizes = array('s' => 'Small', 'm' => 'Medium', 'l' => 'Large');
echo $this->Form->input(
'size',
array('options' => $sizes, 'default' => 'm')
);
Since this is multi-choice select, value given must be array. And the key shouldn't be default, I should've used value instead.
<?= $this->Form->input('PaymentMethods', array(
'type' => 'select',
'multiple' => true,
'label' => false,
'options' => $options,
'value'=> $array_of_data_fetched_from_database
)); ?>

Cakephp option tag attributes

In the view:
echo $this->Form->input('Ingredient');
The above populate multiple select list that HTML output as:
<select name="data[Ingredient][Ingredient][]" option="hh" multiple="multiple" id="IngredientIngredient">
<option value="1" selected="selected">Tomato</option>
<option value="2">Spaghetti </option>
<option value="3" selected="selected">Salt</option>
</select>
What I need to know is how to add attributes to the generated <option> tag?
Use the controller to pass selected values:
if ($this->request->is('post') {
// save form
} else {
$this->request->data['Incredient']['Incredient'] = $ids;
}
See here
To add additional attributes like classes you just need to make it a deeper array and you can pass those:
$options = array(
1 => 'One',
2 => array('name' => 'Two', 'value' => 2, 'class' => 'extra'),
3 => 'Three');
echo $this->Form->input('test', array('type' => 'select', 'options' => $options));
The result:
<div class="input select">
<label for="ModelTest">Test</label>
<select name="data[Model][test]" id="ModelTest">
<option value="1">One</option>
<option value="2" class="extra">Two</option>
<option value="3">Three</option>
</select>
</div>
See this
My Example custom tag option in select, by (CakePHP 2 + VueJs 2) is easy.
<?php
$options = array(
array(
'value' => false,
'v-for' => 'obj in data_options_input_id_vuejs',
'name' => '{{obj.text}}',
'v-bind:value' => 'obj.value',
)
);
echo $this->Form->input('input_id', array(
'type' => 'select',
'required' => true,
'class' => 'input-block-level',
'options' => $options,
'v-model:' => 'productos_stocks_padre_combo_select',
));
?>
Hi all, In my case, i want to add code="code-value" to my select option and this code is working for me.
If you want to add extra data to your option, try this code:
//In controller
$chapters = $this->Course->Chapter->find('all', array('fields' => array('name', 'code', 'id')));
// Call the noop function $this->noop() on every element of chapters
$chapters = Hash::map($chapters, "{n}.Chapter", array($this, 'noop'));
// Callback noop function
function noop($option) {
$option['value'] = $option['id'];
unset($option['id']);
return $option;
}
You can see document about Hash:map function here. Good luck.

Adding a default option "Please Select" in cakephp dropdown

I am new to cakephp. I need to add a default
<option value="0">--Please Select--</option>
in my following select field :
$attributes = array("empty"=>false,"Selected" => 'Select City',"id" => "location");
echo $form->select("gal_location_id", $gal_locations,null,$attributes);
I tried to add
$gal_locations[0] = "--Select City--";
$attributes = array("empty"=>false,"default" => 0,"id" => "location");
but the option coming at the bottom of the list. What is the proper way to add the default option ?
You're looking for the "empty" attribute:
$this->Form->input('gal_location_id', array(
'type' => 'select',
'options' => $gal_locations,
'empty' => 'Select City', // <-- Shows as the first item and has no value
'id' => 'location'
));
See the equivalent in CakePHP3 from this post
CakePHP3
With the following option you dont get a notification to choose a dropdown item.
So if you're just looking for a default value and force the user to pick another, just replace the assign a string to 'empty'.
echo $this->Form->input('db_field', [
'label' => 'My Drop Down',
'empty' => [$default => $default], //Your default options
'options' => $my_options //Your array /list'
]);
echo $this->Form->input('country_id',[
`enter code here`'options' =>$country,
'label' => false,
'class'=>'form-control select2',
'empty'=> 'Select...',
'value' => ''
]);

CakeDC Search Plugin With Dropdown

I'd like to add a select box for searching with the CakeDC Search Plugin. IE:
<select name="field">
<option value="email">Search By Email</option>
<option value="first_name">Search By First Name</option>
</select>
Currently what I have in my VIEW is:
echo $this->Form->create('User', array(
'url' => array_merge(array('action' => 'index'), $this->params['pass'])
));
echo $this->Form->input('email', array('div' => false, 'empty' => true));
echo $this->Form->input('first_name', array('div' => false, 'empty' => true));
This works just fine this way, but I'd like to avoid the multiple input boxes and simplify it with a select box. I could hard it (take the value from the select box and combine it with the value from the input box), but there has to be another way to do it...
Here is my User Module:
public $filterArgs = array(
'email' => array('type' => 'like'),
'first_name' => array('type' => 'like')
);
And this is my Controller:
public function index() {
$this->Prg->commonProcess();
$this->paginate['conditions'] = $this->User->parseCriteria($this->passedArgs);
$this->set('users', $this->paginate());
}
i think you are looking for
echo $this->Form->input('search', array('div' => false, 'empty' => true));
and
public $filterArgs = array(
'search' => array('type' => 'like', 'field'=>array('email', 'first_name')),
);
and
public $presetVars = true;
but you would lose the "AND" of the two inputs in favor of an OR (this is less powerful).
if thats ok for you, this would be the way.

CakePHP creating radio buttons

How can I create two radio buttons with one being preselected based on the value of $foo? The snippet below creates them fine but does not select either of the two buttons.
$options = array('standard' => ' Standard','pro' => ' Pro');
$attributes = array(
'legend' => false,
'value' => false,
'checked'=> ($foo == "pro") ? FALSE : TRUE,
);
echo $this->Form->radio('type',$options, $attributes);
It's simple.. use the default value to $foo:
$options = array(
'standard' => 'Standard',
'pro' => 'Pro'
);
$attributes = array(
'legend' => false,
'value' => $foo
);
echo $this->Form->radio('type', $options, $attributes);
As you can see on the documentation:
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::radio
you should preselect the value for any form field from the controller
#see http://www.dereuromark.de/2010/06/23/working-with-forms/ "Default Values"
This is the way to go
$attributes = array();
$options = array('standard' => 'Standard', 'pro' => 'Pro');
if($foo === 'pro') {
$attributes['default'] = 'pro';
}
echo $this->Form->radio('type', $options, $attributes);
A better Solution is to set the defaults in the controller as Mark has pointed. That way you can set defaults at the end of your controller's action like...
Let's assume your Model is Member with membership_type field
$this->data['Member']['membership_type '] = 'pro';
For CakePHP 3.x, the following syntax should work.
$options = array('Y'=>'Yes','N'=>'No');
$attributes = array('div' => 'input', 'type' => 'radio', 'options' => $options, 'default' => 'Y');
echo $this->Form->input('add to business directory',$attributes);
HTH

Resources