2

This is my code.

$activities = ArrayHelper::map(LibActivity ::find()->all(), 'id', 'activity_name');

it generates the following.

    <select id="tblncddpvlcccbis-activity_id" class="form-control" name="TblNcddpVlccCbis[activity_id]">
    <option value="">---Select Type of Activity---</option>
    <option value="1">Social Mobilization</option>
    <option value="2">Project Identification/Selection</option>
    <option value="3">Project Approval</option>
    </select>

What I want is to concatenate the third parameter so that the option would be the id-activity_name like this:

$activities = ArrayHelper::map(LibActivity ::find()->all(), 'id', 'id'.'-'.'activity_name');

<select id="tblncddpvlcccbis-activity_id" class="form-control" name="TblNcddpVlccCbis[activity_id]">
<option value="">---Select Type of Activity---</option>
<option value="1">1-Social Mobilization</option>
<option value="2">2-Project Identification/Selection</option>
<option value="3">3-Project Approval</option>
</select>
Insane Skull
  • 9,220
  • 9
  • 44
  • 63
beginner
  • 2,024
  • 5
  • 43
  • 76
  • 1
    Please check this link with good example of yii2 [StackOverflow answer](https://stackoverflow.com/questions/27768540/yii2drop-down-list-for-multiple-values-concat-in-one-line/27769661#27769661) – Santosh Ram Kunjir Oct 24 '16 at 10:18

2 Answers2

4

I don't know if this is the standard way in YII or not but you can try it like this:

$libs = LibActivity ::find()->all();
foreach($libs as &$lib){
    $lib->activity_name = $lib->id.'-'.$lib->activity_name;
}

$activities = ArrayHelper::map($libs, 'id', 'activity_name');
// Todo With activities
Touqeer Shafi
  • 5,084
  • 3
  • 28
  • 45
3

PHP has array_walk function that allows to apply a function to every item in the array.

So, here's how you do it:

$activities = ArrayHelper::map(LibActivity::find()->all(), 'id', 'activity_name');
array_walk($activities, function(&$value, $key){
    $value = $key.' '.$value;
});

In this case we pass an anonymous function that does exactly what you need. I think it's better to apply these changes to the resulting array, not to the original result set.

You can also optimize your original query. Assuming id and activity_name are actual table fields, you can do this:

LibActivity::find()->select(['id', 'activity_name'])->asArray()->all()

This way you'll only get the necessary fields and also avoid creating objects where you don't need them.

Beowulfenator
  • 2,262
  • 16
  • 26