I can create model based dropdown list in Yii2 using the ArrayHelper::map(). But I am not sure about the process to add a new select option in the dropdown list. Bellow I have added my code-
$book_list = Books::find()
->where(['Status' => 1])
->orderBy('BookName')
->all();
$listBook=ArrayHelper::map($book_list,'BookName','BookName');
<?= $form->field($model, 'BookName')->dropDownList($listBook, [
'prompt' => 'Select'],
['label'=>'']
)?>
And it generating dropdown list like following-
<option value="">Select</option>
<option value="Biology">Biology</option>
<option value="Mathematics">Mathematics</option>
<option value="Physics">Physics</option>
I want to add a new option called "OTHER" at the end of the dropdown list. I am using order by BookName so "OTHER" will be out of the sorting. It will always display in bottom/top of the dropdown list.
<option value="">Select</option>
<option value="Biology">Biology</option>
<option value="Mathematics">Mathematics</option>
<option value="Physics">Physics</option>
<option value="Other">Other</option>
How can I achieve this?
Please try like this,
$listBook=ArrayHelper::map($book_list,'BookName','BookName');
$listBook['Other'] = 'Other';
Sorry for delay, Below is the correct answer.
$listBook=ArrayHelper::map($book_list,'BookName','BookName');
$listBookNew = array_merge($listBook, array('Other'=>'Other'));
<?= $form->field($model, 'BookName')->dropDownList($listBookNew, [
'prompt' => 'Select'],
['label'=>'']
)?>
Let me know if it works