CakePHP select default value in SELECT input - php

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

Related

yii1 gridview dropdownlist set value as default value

Is that possible to make gridview dropdownlist set value as default value? For example my working status has 2 type which is active and no active. Possible set active as default value?
the code as below:
array(
'name'=>'employee_wstatus',
'type' => 'raw',
'filter'=>array('1'=>'Active', '0'=>'No Active'),
'value' => 'EmployeeM::model()->getWorkstatus($data->employee_wstatus);',
'htmlOptions'=> array('width'=>'10%'),
),
If you look at the implementation of Yii filter method, you will see, that it always adds empty option when it gets an array on input.
To remove blank value from your dropdown filter you have to define selectbox manually:
'filter' => CHtml::activeDropDownList(
EmployeeM::model(),
'employee_wstatus',
array('1' => 'Active', '0' => 'No Active')
),

How to add default value selected in dropdownlist with enum?

I am new to yii2 and trying to get around. I have a dropdownlist whose values in the database are enum. So when the crud was created the dropdownlist had the enum values.
But I want to keep one value selected as default in the drop down list.
My form code is below:
<?= $form->field($model, 'priotiy_level')->dropDownList([ 'low' => 'Low', 'medium' => 'Medium', 'high' => 'High', ], ['prompt' => 'Select Priority Level']) ?>
Instead of the prompt, I want to have medium as a selected value. Can someone please help me with this?
Thank you.
After initialization of the $model instance in your controller set the attribute and then pass $model to view.
$model->priority_level = 'medium';
As #Bizley said, you need to set the value of the attribute in your Controller. In Yii2, you can do that with in one line:
public function actionSomething {
$model = new MyClass(['priotiy_level' => 'medium']);
// code
return $this->render('something', [
'model' => $model
]);
}
Additionally to previous answers you can also use default validator:
class SomeActiveRecord extends ActiveRecord {
// ...
function rules(){
return [
['priotiy_level', 'default', 'value' => 'medium']
// set "username" and "email" as null if they are empty
[['username', 'email'], 'default'],
// set "level" to be 1 if it is empty
['level', 'default', 'value' => 1],
];
}
}
More details see here: Handling Empty Inputs.
This code sets default value for the all actions/forms. If you need different default values on different forms, can be used also scenarios of validation.
Give class to your dropdownList :
Ex.
<?= $form->field($model, 'priotiy_level')->dropDownList([ 'low' => 'Low', 'medium' => 'Medium', 'high' => 'High', ], ['class' => 'priority_list','prompt' => 'Select Priority Level']) ?>
Give Default value using Java Script or Jquery
Ex.
<script>
$(".priority_list").val('medium'); // assing value using jquery
</script>
You can also use ID:
Ex.
<script>
var temp=document.getElementById('project-industry_id');
temp.value='medium';
</script>

CakePHP multiple checkbox array HTML the right way

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.

Why is CakePHP Form helper grouping my form radio options?

echo $this->Form->create('AmazonMatches', array('action' => 'selectMatches'));
echo $this->Form->input('option_id', array('options' => $allAmazonMatches, 'type' => 'radio'));
echo $this->Form->end(__('Submit', true));
Now I see a box around my radio buttons with a large red text saying "Option Id".
How can i get rid of it? Sorry I am a total Cake noob.
You need to set the 'legend' option to false if you don't want to show it, or to a string if you want to customize the message:
echo $this->Form->input('option_id', array(
'options' => $allAmazonMatches,
'type' => 'radio',
'legend' => false
));
$this->Form->input
Creates one input field with the id provided. You'll have to create multiple inputs inorder to make your checkboxes work separately.
There could be better methods, but doing it something likethis will work.
foreach($allAmazonMatches as $amazonMatch)
{
$this->Form->input...
}

CakePHP Radio Buttons

I am using CakePHP to create a simple blog for myself. I want to have a rating system attached to each post.
I have loaded the ratings which look like this:
Controller
$this->set('ratings', $this->Ratings->find('all'));
I want to generate radio buttons on the view with the ratings. The ratings have the fields value and label. I could use a foreach and loop around the ratings but I am wondering if the radio button helper in the form class can take a model object and generate the radio buttons?
I hope you understand what I mean.
You can pass an options attribute to the form helper.
<?=$this->Form->input('rating', array('type' => 'radio', 'options' => range(1, 10)))?>
$options = array(
'0' => 'Male',
'1' => 'FeMale'
);
$attributes = array(
'legend' => false,
'value' => 0
);
echo $this->Form->radio('type', $options, $attributes);

Categories