I'm just learning Yii 2 framework. I'm curios what is the best practice to implement Cancel button in Create/Update form of typical CRUD application. I generated CRUD application from the Yii 2.0. tutorial https://www.yiiframework.com/doc/guide/2.0/en/start-gii. Then I added Cancel button in _form.php view
<div class="country-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'code')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'population')->textInput() ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
<?= Html::submitButton(Yii::t('app', 'Cancel'), ['name' => 'cancel', 'class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
And modified actionUpdate method of CountryController:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$request = Yii::$app->request;
if(null !==(Yii::$app->request->post('cancel'))) {
return $this->redirect(['index']);
}
if ($model->load($request->post()) && $model->save()) {
//return $this->redirect(['view', 'id' => $model->code]);
return $this->redirect(['index']);
}
return $this->render('update', [
'model' => $model,
]);
}
It works, but I stuck with the validation. I want to skip validation when the user presses Cancel button.
To cancel you need to use a link
<?= Html::a('Cancel', ['/controller/action'], ['class'=>'btn btn-primary']) ?>
However to reset, you can use a button
<?= Html::resetButton('Reset', ['class' => 'reset']) ?>
Please refer this doc to see how you can customize it https://www.yiiframework.com/doc/guide/2.0/en/helper-html