Add multiple Select2 Widget inside gridview column (Not as filter Column) in YII2

371 Views Asked by At

Hello I am trying to add a select2 widget inside gridview columns for each driver in Yii2. The grid is for driver model. One driver may have multiple zones. As in picture below:

enter image description here

Here is the grid:

enter image description here

I have created a relation in Driver Model:

public function getZones()
{
    return $this->hasMany(Zone::className(), ['id' => 'zone_id'])
        ->viaTable('driver_zone_mapping', ['driver_id' => 'id']);
}

and here is Select2 Grid Column code:

 [
            'label' => 'Zones',
            'format' => 'raw',
            'value' => function ($model) {
                return Select2::widget([
                    'model' => $model,
                    'attribute' => 'zones',
                    'value' => $model->zones,
                    'data' => ArrayHelper::map(Zone::find()->asArray()->all(), 'id', 'zone'),
                    'options' => [
                        'placeholder' => 'Select Zone ...',
                        'class' => 's2-tog-button',
                        'data-id' => $model->id,
                        'multiple' => true,
                    ],
                    'pluginOptions' => [
                        'tags' => true,
                    ],
                ]);
            }
        ],

controller Action:

public function actionTest()
{
    $searchModel = new DriverSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    $dataProvider->pagination->pageSize = 50;

    return $this->render('test', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

Here Is Model Search function:

public function search($params)
{
    $query = Driver::find();

    $query->joinWith(['zones']);
    // add conditions that should always apply here

    // add conditions that should always apply here

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to return any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }

    // grid filtering conditions
    $query->andFilterWhere([
        'id' => $this->id,
        'presence' => $this->presence,
        'priority' => $this->priority,
        'created_at' => $this->created_at,
    ]);

    $query->andFilterWhere(['like', 'name', $this->name])
        ->andFilterWhere(['like', 'visible_name', $this->mobile])
        ->andFilterWhere(['like', 'mobile', $this->mobile])
        ->andFilterWhere(['like', 'other', $this->other]);

    return $dataProvider;
}

The problem is that, the select2 widget is displayed for one driver only(First driver having zones). Others have no widget even if they have zones in driverzonemapping table. Any idea?

0

There are 0 best solutions below