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>
Related
Im have ActiveRecord model and view for update form of this model. Also I have getter and setter in model class that looks like this
public function setTopvisorGoogleRegion($value)
{
$this->myvalue = $value;
return(true);
}
public function getTopvisorGoogleRegion()
{
return([1 => '123']); //I return this array for show you essence of the problem
}
Following logic in this code $model->topvisorgoogleregion must return [1 => '123']
In view I have next code
<?php echo($form->field($model, topvisorgoogleregion)->textInput());?>
<?php echo $form->field($model, 'topvisorgoogleregion')->widget(Select2::classname(), [
'data' => [1 => '123', 2 => '456'],
'options' => [
'id'=>'projectCtrl',
'placeholder' => 'Select option',
'multiple' => true
],
'pluginOptions' => [
'allowClear' => true,
'tags' => true,
],
]);
?>
When I open form I want to see option 1 => '123' already selected in Select2. Its logically because when already existing record is updating, ActiveRecord get data that already stored in model (in this case using getter) and fill fields in view with this data (In first field that using textInput I see text 'Array' because getter in model returns array). But Select2 is empty when I open update page. Whats going wrong?
If I delete first field (textInput) nothing changes
I find the solution - in getter I need provide ActiveQuery object, not array. I dont know why and how it works, but it works
Please help... I am trying to set default value for this: I know it is based on Kartik select on yii2. I didn't use it before. Here is my source code I would need to set default value based on $_GET parameters. But problem is I can't set any. The source is this...
<?php
echo $form->field($profile, 'country_id')->widget(Select2::classname(), [
'language' => Yii::$app->language,
'data' => ArrayHelper::map($countries, 'id', 'title_' . mb_substr(Yii::$app->language, 0, 2)),
'theme' => Select2::THEME_BOOTSTRAP,
'options' => [
'id' => 'country-select',
'placeholder' => Yii::t('frontend', 'Select a country')],
'pluginOptions' => [
'allowClear' => true,
],
])->label($Country, ['class' => 'label-class'])
?>
Where Should I set it in this case. Sorry, I just saw this plugin at first time...
if you wanna set the default value, you should use the model like the following code;
$profile->country_id = isset($profile->country_id) ? $profile->country_id : 1 // like that
also you can use in afterFind function on the model.
check this Yii2: How to set default attribute values in ActiveRecord? and this https://www.yiiframework.com/doc/guide/2.0/en/tutorial-core-validators#default
Using Yii2, I'm trying to create a detailView. I want to hide empty rows, and therefore I use the kartik-v detailview. However, I also want to hide attributes if they conform to a certain condition. So I stumbled across this SO question, which captures the intention of my question. It does not, however, answer it satisfactory. (This question asks roughly the same thing). An example
<?= DetailView::widget([
'hideIfEmpty' => true, //available in kartik's detailview
'model' => $model,
'attributes' => [
'id',
'name', //cant be null, always shown
'description:ntext', //can be null, so hidden thanks to kartiks detailview
isAdmin() ? "password" :"", //an example, of course
"hypotheticalOtherField",
isAdmin() ? [
'attribute'=>'client',
'format'=>'raw',
'value'=>function($object) {
return Html::button("MyButton".$object->client);
}
] : ""
]
]) ?>
As you can see, I want to show some fields based on (in this example) whether or not the user is admin. Sadly, inserting emtpy strings, empty arrays, or null values into the attributes array if the condition isn't met, produces an error (IE The attribute must be specified in the format of "attribute", "attribute:format" or "attribute:format:label" when inserting empty strings)
I suppose I could create the attributes array like this:
$attrs = ['id','name','description:ntext'];
if (isAdmin()) array_push($attrs, "password");
array_push($attrs, "hypotheticalOtherField");
if (isAdmin()) array_push($attrs, [
'attribute'=>'client',
'format'=>'raw',
'value'=>function($object) {
return Html::button("MyButton".$object->client);
}
]);
echo DetailView::widget([
'hideIfEmpty' => true, //available in kartik's detailview
'model' => $model,
'attributes' => $attrs
]);
but then the overview with the standard Yii2 code layout is severely undermined.
So is there some way to conditionally insert values into an array, so I can keep coding Yii-style: estetic, organized, and uncluttered? Or maybe a values from which Yii2 knows it should be skipped when creating the View
You can use visible to DetailView
<?= DetailView::widget([
'hideIfEmpty' => true, //available in kartik's detailview
'model' => $model,
'attributes' => [
'id',
'name', //cant be null, always shown
'description:ntext', //can be null, so hidden thanks to kartiks detailview
[
'visible' => (isAdmin() ? true : false),
'value' => $model->password,
'label' => 'test'
],
]) ?>
Add whatever condition you want to add!!! in visible
If you try with an array append shorthand and the look of the code is more yii2 stylish
The attribute based on array is a correct (good) practice.
$attrs[] = ['id','name','description:ntext'];
if (isAdmin()) {
$attrs[] = ['password'];
}
$attrs[] = ['hypotheticalOtherField']
if (isAdmin()) {
$attrs[] = [
'attribute'=>'client',
'format'=>'raw',
'value'=>function($object) {
return Html::button("MyButton".$object->client);
}
}
echo DetailView::widget([
'hideIfEmpty' => true, //available in kartik's detailview
'model' => $model,
'attributes' => $attrs
]);
I have created a check-box input as type Boolean for storing values as dishcharged - checked or unchecked. Checked will store 1 and unchecked will store 0.
Now I want to show the label as Yes or No for value 1 and 0 in grid-view and view. How can achieve that.
my _form.php code is like
$form->field($model, 'discharged')->checkBox(['label' => 'Discharged',
'uncheck' => '0', 'checked' => '1'])
I have tried like
[
'attribute'=>'discharged',
'value'=> ['checked'=>'Yes','unchecked=>'no']
],
but doesn't look like the correct syntax.
Thanks.
As arogachev said, you should use boolean formatter :
'discharged:boolean',
http://www.yiiframework.com/doc-2.0/guide-output-formatter.html
http://www.yiiframework.com/doc-2.0/yii-i18n-formatter.html#asBoolean()-detail
Or you could add a getDischargedLabel() function in your model :
public function getDischargedLabel()
{
return $this->discharged ? 'Yes' : 'No';
}
And in your gridview :
[
'attribute'=>'discharged',
'value'=> 'dischargedLabel',
],
First option:
[
'attribute' => 'discharged',
'format' => 'boolean',
],
or shortcut:
'discharged:boolean',
This does not require additional methods in your model and writing text labels (it will be set automatically depending on language in your config).
See more details here.
Second option:
Instead of writing additional method in model you can just pass closure to value.
You can check details here.
[
'attribute' => 'discharged',
'value' => function ($model) {
return $model->discharged ? 'Yes' : 'No';
},
],
If you consistently display booleans the same way in your app, you can also define a global boolean formatter:
$config = [
'formatter' => [
'class' => 'yii\i18n\Formatter',
'booleanFormat' => ['<span class="glyphicon glyphicon-remove"></span> no', '<span class="glyphicon glyphicon-ok"></span> Yes'],
],
];
Then add your column:
'discharged:boolean',
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