Clone active record with update logic

Sometimes I have to clone a complex active record.

I use this code in the gridview:


    <?= GridView::widget([

    'dataProvider' => $dataProvider,

    'filterModel' => $searchModel,

    'columns' => [

    ...

    ['class' => 'yii\grid\ActionColumn', 'template' => '{view} {update} {clone} {delete}',

	'buttons' => [

	    'clone' => function ($url) {

		return Html::a(

		'<span class="glyphicon glyphicon-retweet"></span>' ,

		$url, 

		[

		    'title' => 'Clone',

		    'data-pjax' => '0',

		]

		);

	    },

	],

	'contentOptions'=>['style'=>'width: 85px;']

       ],

      ],

    ]); ?>

And in the controller


    public function actionClone($id)

    {

        $tobeclonedmodel = $this->findModel($id);

	$model = new yourmodelclassname();

	$model->attributes=$tobeclonedmodel->attributes;

        // make the primary key empty. This prevents a double key error.

	$model->youridfield =null;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->youridfield]);

        } else {

            return $this->render('update', [

                'model' => $model,

            ]);

        }

    }

It is just a copy of the standard update function with 3 lines added.

To make it even better. Copy the ‘update’ view and rename it to ‘clone.php’.

Change the 3 ‘Update’ names to ‘Clone’ and change in the controller


 

return $this->render('update', [

                'model' => $model,

            ]);



to


 

return $this->render('clone', [

                'model' => $model,

            ]);



Yii2 is so wonderful simple once you get it!