3

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.

3 Answers3

6

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

Azraar Azward
  • 1,586
  • 2
  • 12
  • 16
3

You are using submit button for cancel. Thats why form is validating. Use normal button instead on Submit button.

Replace this line

<?= Html::submitButton(Yii::t('app', 'Cancel'), ['name' => 'cancel', 'class' => 'btn btn-primary']) ?>

With

<?= Html::a(Yii::t('app', 'Cancel'), ['index'], ['class'=>'btn btn-primary']) ?>
Yasin Patel
  • 5,624
  • 8
  • 31
  • 53
3

could be you are looking for the reset button

 echo Html::resetButton('Reset', ['class' => 'btn btn-default']);
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107