I have two tables: depart and translate. In "depart" I keep departments with title_id, which is in second table "translate" and keeps title of dep in different languages.
Now I need to make a dropdown list of departments, but it shows 'title_id's in that list, but I need to take a dep.name from second table and put it in list ordered by department table. I have this at the moment:
<?= $form->field($model, 'departId')->dropDownList(ArrayHelper::map($depart, 'id', 'title_id'), ['prompt' => 'Choose department',] ); ?>
You have to run first a query to get data for the dropdown, something similar as that, assumed that the field of the translated text in translate is text:
$depart = (new \yii\db\Query())
->select('d.id, t.text')
->from(['d' => 'depart', 't' => 'translate'])
->where('d.title_id = t.id')
->orderBy('t.text')
->all();
Other possibility to get the same data with ActiveRecord, assumed that the association from the model Depart to Translate is defined in model Depart.
$depart = Depart::find()
->join('translate')
->select('depart.id, translate.text')
->orderBy(translate.text)
->asArray()
->all();
In model Depart:
/**
* #return \yii\db\ActiveQuery
*/
public function getTranslate()
{
return $this->hasOne(Translate::class, ['id' => 'title_id']);
}
Than you can use your form field with text insted of title_id:
<?= $form->field($model, 'departId')->dropDownList(ArrayHelper::map($depart, 'id', 'text'), ['prompt' => 'Choose department',] ); ?>
I have fields like below
<?= $form->field($model, 'phone')
->textInput(['type' => 'number', 'maxlength' => 13])
->label('Phone')
?>
why the 'maxlength' is not work? and how to make it work?
thank you before
It will not work because you are using type=>number for your input field, you have to change it to type=>text.
<?= $form->field($model, 'phone')
->textInput(['type' => 'text', 'maxlength' => 13])
->label('Phone')
?>
Looking at your input it seems like you are doing it because you do not want the user to enter any other thing than numbers for the Phone field, Yii2 provides you a very nice way to accomplish this i.e yii\widgets\MaskedInput, you can format your input using the mask option to tell it how many digits to allow and in which sequence see the demos HERE
<?= $form->field($model, 'phone')->widget(\yii\widgets\MaskedInput::className(), [
'mask' => '999-999-9999',
]) ?>
apart from the solutions above, you can also have the option of validating this inside your model by using the custom validation option.
Your rule for phone inside your model should look like
[['phone'],'PhoneLimit']
public function PhoneLimit($attribute)
{
if (!preg_match('/^[0-9]{13}$/', $this->$attribute)) {
$this->addError($attribute, 'Please provide digits only no more than 13.');
}
}
try for type number -> 'type'=>'number', 'min' => 1, 'max' => 999
I have linked tables and when I create dropdown list like this
<?= $form->field($model, 'player_id')->dropDownList(
ArrayHelper::map(Player::find()->all(), 'id', 'category_id'),
['prompt' => 'Select'])
?>
it works.
I need to have in my list category name and not category id (the table category consists of id and name and category_id from my current table is linked to category.id)
How can I make that?
Assuming your relationship is called getCategory, you just add the corresponding joinWith and use the name attribute:
$form->field($model, 'player_id')->dropDownList(
ArrayHelper::map(Player::find()->joinWith('category')->all(), 'id', 'name'),
['prompt' => 'Select'])
Update with your request: Your getNameAndLastname should include your category data:
public function getNameAndLastname() {
$cat = $this->getCategory()->one();
return $this->lastname.' '.$this->firstname.' - Cat: '.$cat->name;
}
And now:
$form->field($model, 'player_id')->dropDownList(
ArrayHelper::map(Player::find()->joinWith('category')->all(), 'id', 'nameAndLastname'),
['prompt' => 'Select'])
i have a problem with the checkbox field that does not save me the data in the database . In the database I have the ' conditions ' field ( chekbox field ) as boolean . when sending the form I do not save as checked ( 1 ) .
my model
Rules
return[
'condizioniRequired' => ['conditions','required'],
'condizioniType' => ['conditions','boolean'],];
My view
<?= $form->field($model, 'conditions')->checkbox(array('label'=>'Offerted')); ?>
all other fields are saved.
You have to do like this :
<?= $form->field($model, 'conditions')->checkBox(['uncheck' => '0', 'checked' => '1'])->label('label'=>'Offerted') ?>
I hope this will help!!.
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.