I want to show selected value in Yii2 dropdown,
$_GET Value:
$id = $_GET["cid"];
Drop down code
$form->field($model, 'userid')
->dropDownList(
[User::getUser()],
//[ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name')],
['prompt'=>'Select a user','id'=>'user_dropdown'],
['options' =>
[
$id => ['selected' => true]
]
]
)->label('');
but this method is not working!
Try this.
$model->userid=$id;
$form->field($model, 'userid')
->dropDownList(...)
->label('');
Basically, you affect the options (your <option> elements) by using the value attribute's actual value as the array key in the dropDownList options array.
So in this case I have an array of states and the value attributes have the state abbreviation, for example value="FL". I'm getting my selected state from the Address table, which stores the abbreviation, so all I have to do is use that as my array key in the options array:
echo $form->field($model, 'state')->dropDownList($listData, ['prompt'=>'Select...', 'options'=>[$address->state=>["Selected"=>true]]]);
The documentation spells it out: http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#dropDownList()-detail
i hope this will help you
$form->field($model, 'userid')
->dropDownList(
[User::getUser()],
//[ArrayHelper::map(User::find()->where('id' => $id)->all(), 'id', 'name')],
['prompt'=>'Select a user','id'=>'user_dropdown'],
['options' =>
[
$id => ['selected' => true]
]
]
)->label('');
$model->userid = $_GET['cid'];
$form->field($model, 'userid')
->dropDownList(
$items, //Flat array('id'=>'val')
['prompt'=>''] //options
)->label('');
<?php
$selectValue = $_GET['tid']
echo $form->field($model, 'tag_id')
->dropdownList(
ArrayHelper::map(Tag::find()->where(['visibility'=>'1'])->orderBy('value ASC')->all(), 'tag_id', 'value'),
['options' => [$selectValue => ['Selected'=>'selected']]],
['prompt' => '-- Select Tag --'])
->label(false);
?>
This code will Auto Select the selected value received as input.
Where $selectValue will be numeric value received from GET method.
Final output : <option value="14" selected="selected">NONE</option>
Ok, if you are using ActiveForm then value of your model field will be used as the selected value. With Html helper dropDownList function accepts another parameter selection doc. Example:
$id = $_GET["cid"];
\yii\helpers\Html::dropDownList('userid', $id, [ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name'), [......])
This is my S.O.L.I.D approach.
Controller
$model = new User();
$model->userid = $id; #this line does the magick. Make sure the $id has a value, so do the if else here.
return $this->return('view', compact('model'))
But, if you prefer the setter method. Do this...
# Model
class User extends ActiveRecord
{
public function setUserId(int $userId): void
{
$this->userid = $userId;
}
}
# Controller
$model = new User();
$model->setUserId($userId);
View (view is as-is)
$form->field($model, 'userid')
->dropDownList(...)
->label('');
Use this code below:
$category = \backend\models\ProductCategory::find()->WHERE(['deleted'=>'N'])->all();
$listData = ArrayHelper::map($category,'product_category_id','category_name');
echo $form->field($model, 'product_category_id')->dropDownList($listData,['prompt'=>'Select']);
All of the options I've added are unrequired.
What is written in the 'value' index is what dropdown item will be selected as default.
Prompt just displays a first option that doesn't have a value associated with it.
echo $form->field($model, 'model_attribute_name')
->dropDownList($associativeArrayValueToText,
[
'value'=> $valueIWantSelected,
'prompt' => 'What I want as a placeholder for first option',
'class' => 'classname'
]);
You'll find the function that assigns this in the following file:
vendor/yiisoft/yii2/helpers/BaseHtml.php
public static function renderSelectOptions($selection, $items, &$tagOptions = [])
Also from the function you can see that you can add an optgroup to your dropdown, you just need to supply a multidimensional array in where I've put $associativeArrayValueToText. This just means that you can split your options by introducing group headings to the dropdown.
Related
I am using a Select2 widget for Yii2. It shows a list with the ids of the users.
I need to show two fields defined in my model called Users: first_name_user and last_name_user. Like this:
Daniel Gates
John Connor
John Doe
Maria Key
But I don't know how use map() to show more than one field.
<?= $form
->field($model, 'id_user')
->widget(\common\widgets\Select2::classname(), [
'items' => \yii\helpers\ArrayHelper::map(\app\models\Users::find()->orderBy('name_user')->all(), 'id_user', 'name_user')
])
?>
Model
Add use app\models\Users; and use yii\helpers\ArrayHelper; at top.
public function userList()
{
$userList = [];
$users = Users::find()->orderBy('first_name_user')->all();
$userList = ArrayHelper::map($users, 'id_user', function ($user) {
return $user->first_name_user.' '.$user->last_name_user;
});
return $userList;
}
_form
<?= $form->field($model, 'id_user')->widget(Select2::className(), [
'data' => $model->userList(),
'options' => ['placeholder' => 'Select User'],
]) ?>
You need to use data option instead of items for Select2.
You need to modify your query to show the concatenated first_name_user and last_name_user as an alias and then return it along with the id column to be used in Select2 by ArrayHelper::map().
It's better to add a function to the model you are using to populate the form and return the results from there to the ArrayHelper::map().
Your query should look like
function userList(){
return \app\models\Users::find()
->select([new \yii\db\Expression('[[id_user]],CONCAT([[first_name_user]]," ",[[last_name_user]]) as full_user_name')])
->orderBy('name_user')
->all();
}
Your form field should look like below
<?=
$form->field($model, 'id_user')->widget(Select2::className(), [
'data' => \yii\helpers\ArrayHelper::map($model->userList(), 'id_user', 'full_user_name'),
'options' => [
'placeholder' => 'Select User',
'id' => 'id_user'
],
'theme' => Select2::THEME_DEFAULT,
'pluginOptions' => [
'allowClear' => true
],
]);
?>
I have a _form.php file with this field:
<?=
$form->field($model, 'price')
->textInput([
'class' => 'form-control',
'type' => 'number'
])
?>
The price has this format 1234.50. I would like to have the format es-AR, like this: 1234,50.
In the GridView of index.php I use this code and it works great so I would like to do the same in the _form but it is not working.
[
'attribute' => 'price',
'value' => function($myModel) {
$myFormat = new NumberFormatter("es-AR", NumberFormatter::CURRENCY);
return $myFormat->formatCurrency($myModel->price, "ARS");
},
]
There are 2 ways to do that:
Add extra class to the price field and use javascript to convert to format you want (remember to return it back on submit)
Create priceFormat() and use it on AfterFind event and remember to use priceUnFormat() to return to decimal on BeforeSave
Use:
$form->field($model, 'attr', ['inputOptions' => ['value' => Yii::$app->formatter->asDecimal($model->attr)]])
I want to get value of field in controller.
could you please help me?
here is my form code:
<?php
$form = ActiveForm::begin([
'id' => 'request-form',
'action' => 'site/request_page',
'method' => 'post',
'fieldConfig' => ['autoPlaceholder' => false]
]);
?>
<?= $form->field($model, 'workroom_id')->label(FALSE) ?>
and this is my controller code:
public function actionRequest_page() {
echo Yii::$app->request->post('workroom_id');
die();
}
But I got nothing in result.
write workroom_id in safe rule like this-
public function rules()
{
return [
[['workroom_id'],'safe']
];
}
Use bellow code -
echo Yii::$app->request->post('MODEL_NAME')['workroom_id'];
You should expand your action form-attribute. By using Url::to() for instance. As in echo \yii\helpers\Url::to(['site/request_page']);
And access your post data differently. Try var_dump(Yii::$app->request->post()); to see what your form data looks like. The other answer shows how to access it correctly.
The docs have an excellent starting place for working with forms.
Yii2 active form
<?= $form->field($model, 'pid')->dropDownList([1=>1,2=>2])->hint('上级分类') ?>
I want to disable the option item 2=>2.
Is there a way to do it?
You can add attributes for all items in the dropdownlist with the 'options' key. Let's say you want to disable the second item.
<?= $form->field($model, 'pid')->dropDownList([1 => 1, 2 => 2], ['options' => [2 => ['disabled' => true]]])->hint('上级分类') ?>
In the docs:
http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#activeDropDownList()-detail
This would work definitely:
<?= $form->field($model, 'pid')->dropDownList([1=>1,2=>2], ['options'=>['2'=>['disabled'=>true]]]) ?>
ActiveField dropDownlist() explicitly calls BaseHtml activeDropDownList():
From the docs to ActiveField dropDownList():
The tag options in terms of name-value pairs.
For the list of available options please refer to the $options
parameter of yii\helpers\Html::activeDropDownList().
And from the docs to BaseHtml activeDropDownList():
options: array, the attributes for the select option tags. The array
keys must be valid option values, and the array values are the extra
attributes for the corresponding option tags. For example,
[
'value1' => ['disabled' => true],
'value2' => ['label' => 'value 2'],
];
So pass these options:
[
2 => ['disabled' => true],
],
as second parameter to dropDownList().
Try this:
$disableDataArr['1'] = ['disabled' => true];
dropDownList( $dataArr, ['options'=> $disableDataArr ])
I have created new Yii2 basic project and want to dig in.
There is a Username field on login page:
I want to change label 'Username' to a custom one, e.g. 'My superb label'.
I have read the manual:
http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html
After investigating a little I've got the next result:
I have changed only template and it has changed the layout:
<?= $form->field($model, 'username', [
"template" => "<label> My superb label </label>\n{input}\n{hint}\n{error}"
])?>
How to change the text of the label in a correct way?
What is best practice?
<?= $form->field($model, 'username')->textInput()->label('My superb label') ?>
http://www.yiiframework.com/doc-2.0/yii-bootstrap-activefield.html#label()-detail
there is an another cool way.
<?= $form->field($model, 'username')->textInput(['class'=>'field-class'])->label('Your Label',['class'=>'label-class']) ?>
Okay, just override attributeLabels in LoginForm.php:
/**
* Returns the attribute labels.
*
* See Model class for more details
*
* #return array attribute labels (name => label).
*/
public function attributeLabels()
{
return [
'username' => 'Логин',
'password' => 'Пароль',
];
}
You can also add such function to model:
public function attributeLabels()
{
return [
'username' => 'My Login',
'password' => 'My Pasword',
'rememberMe' => 'Remember Me, please',
];
}
just change the lable from modles like this
'symptomsBefore' => Yii::t('app', 'Has The Patient Suffered from the same or similar symptoms before'),