gridviewyii2yii-form

yii2 change gridview model


I am maintaining a form with a model and a grid of child records. I want the grid to show url of the child, not the parent.

I have two database tables which share a parent-child relationship. I showed only the important fields.

describe ops;
+---------------+--------------+
| serial_number | int(11)      |
+---------------+--------------+
describe opsitem;
+---------------+--------------+
| opsitem_id    | int(11)      |
| ops_id        | int(11)      |   # foreign key
| serial_number | int(11)      |
+---------------+--------------+

In my controller, I display a form for Ops, then create an activeRecord for the child records - Opsitem

class OpsController extends Controller

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);


        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->ops_id]);
        } else {

            $searchModel = new OpsitemSearch();
            $dataProvider = $searchModel->search(
                ['OpsitemSearch' => ['ops_id' => $model->ops_id]]
            );

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

My form contains form fields for ops (parent) and then a grid containing oppsitem (child) records

// $model is Parent - Ops
<?php echo $this->render('_form', [
    'model' => $model,
 ]) ?>
 // $searchModel is Opsitem - Child
<?php echo GridView::widget([
            'dataProvider' => $dataProvider,
            'columns' => [
                'ops_item_id',
                'ops_id',
                'serial_number'
                [
                    'class' => 'yii\grid\ActionColumn',
                    'template' => '{update}{delete}',
                ],
            ],
        ]); ?>

Clicking on the 'update' button on the grid is pointing me to url:

/ops/update?id=1234

I want

/opsitem/update?id=1234


Solution

  • You need to add controller property for change controller. Like as,

    <?php echo GridView::widget([
                'dataProvider' => $dataProvider,
                'columns' => [
                    'ops_item_id',
                    'ops_id',
                    'serial_number'
                    [
                        'class' => 'yii\grid\ActionColumn',
                        'template' => '{update}{delete}',
                        'controller' => 'opsitem', 
                    ],
                ],
            ]); ?>