CakePHP's form generator for checkboxes ... when passing the following into the name:
<?php echo $this->Form->checkbox('checkList[]', array( 'value'=>1,'id' => 'holiday'.$holidaysDays['id'], 'error' => false, 'placeholder' => false,'div'=>false,'label'=>false,'class' => 'approveHolidayCheckbox', 'data-off-text'=>'No', 'data-on-text' =>'Yes', 'hiddenField'=>true) ); ?>
outputs:
<input type="checkbox" name="data[HolidaysApproval][checkList[]]" value="1" id="holiday238" class="approveHolidayCheckbox" data-off-text="No" data-on-text="Yes">
I read here:http://network-13.com/thread/3647-Creating-checkbox-arrays-with-CakePHP that the solution is adding a full stop to the field name (as below), where multiple checkboxes are output on the page. Is this the 'right' way to do this?
Couldn't see this particular scenario anywhere in the documentation.
<?php echo $this->Form->checkbox('checkList.', array( 'value'=>1,'id' => 'holiday'.$holidaysDays['id'], 'error' => false, 'placeholder' => false,'div'=>false,'label'=>false,'class' => 'approveHolidayCheckbox', 'data-off-text'=>'No', 'data-on-text' =>'Yes', 'hiddenField'=>true) ); ?>
Yes this is the correct way of doing this. When CakePHP builds the field names it uses PHP's explode() method. So checklist. essentially does the following:-
$fieldname = explode('.', 'checklist.');
Which results in:-
Array
(
[0] => checkList
[1] =>
)
So you would get inputs with the name data[Model][checklist][].
You can similarly use this for hasMany like fields, e.g. $this->Form->field('Model..name'); which would give you inputs with the name data[Model][][name].
Take a look at the FormHelper and you should easily be able to see how it builds the field names.
Related
Here is the form helper I have used for checkbox
<?php
echo $this->Form->input('name',array('type'=>'checkbox','options'=>$options));
?>
and $options array is as follows:
[options] => Array
(
[58] => 58
[85] => 85
)
But I am getting only one check box with both values in it. How can I get check box for each values.
Use the multiple attribute.
echo $this->Form->input('Name',array(
'label' => __('Label',true),
'type' => 'select',
'multiple' => 'checkbox',
'options' => $options,
));
Another thing you have to check, and this is truly a general rule in cakephp when things do not run as expected. is:
"Are you properly closing the form? Do your inputs stay inside <form>...</form>? If you are not sure how to check simply use your preferred
DevTool and check the rendered HTML page.
This is almost the thing I forgot to check mostly and which always let me waste a lot of time!
If your are creating the $option variable in the view this will help you :
$options = array("key" => "value" , "key" => "value" , "key" => "value");
But if you are setting it the controller this will help you :
$this->set('options', array("key" => "value" , "key" => "value" , "key" => "value"));
key is the value in each option of the select input
value is the text of the option tags
I am some what new to CakePHP and wanted some assistance in setting up a form in a CakePHP View.
I have Array in the following form:
Array ( [1] => B002I0HJZO [2] => B002I0HJzz [3] => B002I0HJccccccccc )
I want a form with 3 radio buttons (in this case) that goes to a custom method called test
You can do that with the FormHelper class.
Example:
<?php
$options = array(
1 => 'B002I0HJZO',
2 => 'B002I0HJzz',
3 => 'B002I0HJccccccccc',
);
echo $this->Form->input('option_id', array('options' => $options, 'type' => 'radio'));
The key is to specify the "type". CakePHP usually defaults to a select element by default.
The example above doesn't use the "automagic" feature of CakePHP. If you retrieve the options in your controller using a find('list') and the array is passed to the view in the plural form of the field name without the "_id" suffix (e.g. if the field is "option_id", you should do $this->set('options', $this->Option->find('list'); assuming that "Option" is the model name), then you shouldn't need to specify the "options", just the "type"
To answer the second part of your question, to post to a different action (e.g. "test"), you need to specify the action when creating the form.
Example:
<?php
$this->Form->create('Product', array('action' => 'test'));
For more information, read the documentation
How do i use the inputDefaults to add a common class to all the input elements in my form. also pls give a brief description of the inputDefaults.
isn't it:
echo $this->Form->create('User', array(
'inputDefaults' => array(
'class' => 'someclass'
)
);
`
You should read the cookbook. theres a good example: http://book.cakephp.org/view/1639/options-inputDefaults
When you create a form you add inputdefaults key in options:
echo $this->Form->create('User', array(
'inputDefaults' => array(
'div' => array('class' => 'someclass')
)
);
After browsing the source file i didn't find anything either. So the only way is to use it explicitly for every call to the input function.
I've looked at loads of forums about validation errors not showing and tried various things but to no avail...
Basically, the validation is correctly recognising the fields do not have values when they should, however the error messages don't 'automagically' appear below the input boxes.
Model validation rule is shown below:
var $validate = array(
'description' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a description of the change'
)
);
echo pr($this->data); output is shown below:
Array
(
[Change] => Array
(
[0] => Array
(
[id] => 3237
[cn_id] => 5132
[req_id] => 25
[description] =>
)
[1] => Array
(
[id] => 3238
[cn_id] => 5132
[req_id] => 22
[description] =>
)
[2] => Array
(
[id] => 3239
[cn_id] => 5132
[req_id] => 4
[description] =>
)
)
)
echo pr($this->Change->invalidFields()); output is shown below:
Array
(
[0] => Array
(
[description] => Please enter a description of the change
)
[1] => Array
(
[description] => Please enter a description of the change
)
[2] => Array
(
[description] => Please enter a description of the change
)
[description] => Please enter a description of the change
)
So, it is generating the errors messages for display, but they don't actually display in the view, and I don't know why?
Excerpt from the 'view' code is show below:
<?php echo $form->input('Change.'.$i.'.description',
array('value' => $cn['Change'][$i]['description'],
'label' => $engReq['Req']['description'])); ?>
Does anybody have ideas why the error messages are not showing?
I experienced the same issue with a hasMany model (where the form had numerically indexed fields) and came up with a validation solution that worked for me.
Quick answer: Before trying to actually save the data, I validated the data separately like (notice 'validate'=>'only'):
if($this->ModelName->saveAll($this->data, array('validate' => 'only'))) {
// proceed to save...
}
Doing it this way gave me the model's validation error message in the form, right under the input field that failed the validation (the normal Cake way of showing the validation error).
Note: I could not use saveAll() to actually save my data (I'll explain why in a minute). If I could use saveAll() to actually save the data, I could have gotten the validation at the same time as I saved by using (notice 'validate' => 'first'):
if($this->ModelName->saveAll($this->data, array('validate' => 'first')))
However, I could not use saveAll() to actually save the data, due to the fact that I needed to use a transaction to save several models at once, where some of the models were not directly related to other models. saveAll() will only save the model on which it is called, plus models directly related to it. Since Cake does not currently support nested transactions, and saveAll() uses one transaction automatically, I had to use save() on my models and start and end my transaction manually. However, this caused me to loose the validation message in my form on the hasMany items, even if I saved by using "$this->ModelName->save($this->data, array('validate'=>'first')".
Further explanation: The issue does seem to be related to using numerically indexed fields in the form. For example:
$this->Form->input("ModelName.0.field_name");
It seems this indexing scheme is the proper way to handle hasMany items in the form, but the validation messages would not find their way to this form input. It is interesting to notice that my view did in fact have access to the validation error. This can be seen in the view by using (notice no numerical index in these lines):
if($this->Form->isFieldError("ModelName.field_name")) {
echo $this->Form->error("ModelName.field_name");
}
Putting these lines after the '$this->Form->input("ModelName.0.field_name")' inserted a the validation message into the page, just not in the same div as the input field (and thus it didn't look ideal).
I couldn't figure out a way to tell Cake to use that validation message in the '$this->Form->input("ModelName.0.field_name")'. So I resorted to the 'validate' => 'only' method described earlier, which is working well for me.
shouldnt it be
var $validate = array(
'description' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a description of the change'
)
)
);
?
Using CakePHP:
I have a many-to-one relationship, let's pretend it's many Leafs to Trees. Of course, I baked a form to add a Leaf to a Tree, and you can specify which Tree it is with a drop-down box ( tag) created by the form helper.
The only thing is, the SELECT box always defaults to Tree #1, but I would like it to default to the Tree it's being added to:
For example, calling example.com/leaf/add/5 would bring up the interface to add a new Leaf to Tree #5. The dropdown box for Leaf.tree_id would default to "Tree 5", instead of "Tree 1" that it currently defaults to.
What do I need to put in my Leaf controller and Leaf view/add.ctp to do this?
In CakePHP 1.3, use 'default'=>value to select the default value in a select input:
$this->Form->input('Leaf.id', array('type'=>'select', 'label'=>'Leaf', 'options'=>$leafs, 'default'=>'3'));
You should never use select(), or text(), or radio() etc.; it's terrible practice. You should use input():
$form->input('tree_id', array('options' => $trees));
Then in the controller:
$this->data['Leaf']['tree_id'] = $id;
$this->Form->input('Leaf.id', array(
'type'=>'select',
'label'=>'Leaf',
'options'=>$leafs,
'value'=>2
));
This will select default second index position value from list of option in $leafs.
the third parameter should be like array('selected' =>value)
Assuming you are using form helper to generate the form:
select(string $fieldName, array $options, mixed $selected, array $attributes, boolean $showEmpty)
Set the third parameter to set the selected option.
cakephp version >= 3.6
echo $this->Form->control('field_name', ['type' => 'select', 'options' => $departments, 'default' => 'your value']);
To make a text default in a select box use the $form->select() method. Here is how you do it.
$options = array('m'=>'Male','f'=>'Female','n'=>'neutral');
$form->select('Model.name',$options,'f');
The above code will select Female in the list box by default.
Keep baking...
FormHelper::select(string $fieldName, array $options,
array $attributes)
$attributes['value'] to set which value should be selected default
<?php echo $this->Form->select('status', $list, array(
'empty' => false,
'value' => 1)
); ?>
If you are using cakephp version 3.0 and above, then you can add default value in select input using empty attribute as given in below example.
echo $this->Form->input('category_id', ['options'=>$categories,'empty'=>'Choose']);
The best answer to this could be
Don't use selct for this job use input instead
like this
echo $this->Form->input('field_name', array(
'type' => 'select',
'options' => $options_arr,
'label' => 'label here',
'value' => $id, // default value
'escape' => false, // prevent HTML being automatically escaped
'error' => false,
'class' => 'form-control' // custom class you want to enter
));
Hope it helps.
As in CakePHP 4.2 the correct syntax for a select form element with a default value is quite simple:
echo $this->Form->select(
'fieldname',
['value1',
'value2',
'value3'],
['empty' => '(auswählen)','default'=>1]
);
If hopefully don't need to explain the default=1 means the second value and default=0 means the first value. ;)
Be very careful with select values as it can get a little tricky. The example above is without specific values for the select fields, so its values get numerated automatically. If you set a specific value for each select list entry, and you want a default one, set its specific value:
$sizes = ['s' => 'Small',
'm' => 'Medium',
'l' => 'Large'];
echo $this->Form->select('size', $sizes, ['default' => 'm']);
This example is from the official 4.x Strawberry Cookbook.
https://book.cakephp.org/4/en/views/helpers/form.html#options-for-control