HELPME
HELPME

Reputation: 754

How to display success message if users was added to the database in Yii2?

I know this is a dumb question, but I just started learning with Yii2. I haven't found any useful information here related to this, so. What I need to do is display a message if the user was added to the database successfuly. Could somoene help me to solve this? I've no idea where it has to be written: in a model, controller or view.

Here is my controller action:

    public function actionCreate()
{
    $model = new Employee();
    $model->scenario = Employee::SCENARIO_CREATE;

    $post = Yii::$app->request->post();

    if ($model->load($post) && $model->save()) {
        return $this->redirect(['create']);
    }

    return $this->render('create', [
        'model' => $model,
    ]);
}

Here is my view:

<div class="employee-form">

<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'name')->textInput([
    'maxlength' => 50,

]) ?>
<?= $form->field($model, 'surname')->textInput([
    'maxlength' => 50,
]) ?>
<?= $form->field($model, 'employment_date')->textInput() ?>

<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

Now what is happening is that the script doesn't allow to enter the date, which is later than today's date and also doesn't allow to enter a string into the date field. So to be clear, if the user has entered correct information, I need to add the message that would say "Users has been entered to the database successfully".

Thanks for any help!

Upvotes: 0

Views: 3529

Answers (2)

Irfan Ali
Irfan Ali

Reputation: 2258

Set flash message in your controller. like below.

 Yii::$app->session->setFlash('flashMsg', 'flash Msg or any kind of content like variables');

and show this message in your view page. like below.

<?php if (Yii::$app->session->hasFlash('flashMsg')){ ?>
    <div class="alert alert-success">
        <!-- flash message -->
         <?php Yii::$app->session->getFlash('flashMsg'); ?>
    </div>
<?php } ?>

Upvotes: 2

gmc
gmc

Reputation: 3990

You can use the Yii::$app->session->setFlash method in your controller with no need to add anything in the view:

public function actionCreate() 
  $model = new Employee();
  $model->scenario = Employee::SCENARIO_CREATE;
  $post = Yii::$app->request->post();

  if ($model->load($post) && $model->save()) {
    Yii::$app->session->setFlash('success', 'User added');

    return $this->redirect(['create']);
  }
  else {
    Yii::$app->session->setFlash('error', 'Error adding user');
  }

  return $this->render('create', [
      'model' => $model,
  ]);
}

Upvotes: 0

Related Questions