beginner
beginner

Reputation: 2032

YII2 Insert something in array made by arrayhelper::map()

How to insert or push something to an existing array?

I have this code...

$brgys=ArrayHelper::map(LibBrgy::find()
->where(['city_code'=>$model->city_code])
->all(),'brgy_code','brgy_name'); 

the result is..

array(4) {
[166816001]=> string(7) "BAGYANG" 
[166816002]=> string(5) "BARAS" 
[166816003]=> string(8) "BITAUGAN" 
[166816004]=> string(7) "BOLHOON" 
}

How do I add an empty value to make it like the following...

array(4) {
[166816001]=> string(7) "BAGYANG" 
[166816002]=> string(5) "BARAS" 
[166816003]=> string(8) "BITAUGAN" 
[166816004]=> string(7) "BOLHOON"
['']=>""
}

so that in the html form I would have this..

<select id="tblspbub-brgy_code" class="form-control" name="TblSpBub[brgy_code]">
<option value="166816001">BAGYANG</option>
<option value="166816002">BARAS</option>
<option value="166816003">BITAUGAN</option>
<option value="166816004">BOLHOON</option>
<option value=""></option>
</select>

Upvotes: 0

Views: 2038

Answers (1)

arogachev
arogachev

Reputation: 33538

No need to modify array to achieve this.

Drop-down list has special option for this called prompt.

<?= $form->field($model, 'code')->dropDownList($items, ['prompt' => '']) ?>

It will render additional option with empty value in select with given name.

You can read more about here.

Upvotes: 1

Related Questions