= 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('' . 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('',
yii\helpers\Url::toRoute(['clone', 'id' => $model['id']]) // clone record
);
},
],
],
],
]); ?>