Yii 2 Controller Actions
Clone Action
Add action to controller:
public function actionClone($id) { // set to 'false' to overcome 'Unable to verify your data submission: // Bad request (#400)' error. $this->enableCsrfValidation = false; $model = $this->findModel($id); // Copy data (except ID) $dataCopy = $model->attributes; unset($dataCopy['id']); // to insert new record with a copy of the data $dataCopy['company_name'] = $dataCopy['company_name'] . ' (Copy)'; $newModel = new Distributor(); $newModel->setAttributes($dataCopy, false); if ($newModel->save()) { Yii::$app->session->setFlash('success', "Successfully cloned Distributor."); return $this->redirect(['update', 'id' => $newModel->id]); } else { // Could not save copy, so we simply view original record Yii::$app->session->setFlash('error', "Failed to clone Distributor."); return $this->redirect(['view', 'id' => $model->id]); } $this->enableCsrfValidation = true; // restore CSRF validation }
Add button to View view:
<?= Html::a('<i class="fa fa-clone" aria-hidden="true"></i>' . Yii::t('app', 'Clone'), ['clone', 'id' => $model->id], ['class' => 'btn btn-default']) ?>
Add button to Index view:
<?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', //... //['class' => 'yii\grid\ActionColumn'], [ // custom actions 'class' => 'yii\grid\ActionColumn', 'template' => '{view} {update} {delete} {clone}', /* '{view} {update} {delete}' */ 'buttons' => [ 'clone' => function ($url, $model, $key) { return Html::a('<i class="fa fa-clone" aria-hidden="true"></i>', yii\helpers\Url::toRoute(['clone', 'id' => $model['id']]) // clone record ); }, ], ], ], ]); ?>