Add success message in model/validator?

I notice that I can call addError method in model. Is there any way to add a custom successful message to the model after validation?

Well how are you calling the validate method? In most cases I call it from my controller and then if it’s validated I render the success page.

Why can’t you do it this way?

You can test if ($model->hasErrors() returns true or false) and display a message accordingly

You could do it in your controller

public function actionCreate() {

    	$model = new Whatever();

    	if ($model->load($_POST)) {

        	if ($model->save()) {

            	//set your message only if it saves

            	Yii::$app->session->setFlash('success', 'Saved Successfully!');

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


    	} else {

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

                    	'model' => $model




or in your model

	public function afterSave() {

    	Yii::$app->session->setFlash('success', 'Saved Successfully after save!');


just make sure you add the alert widget to you main layout or where ever you want to show the messages


//for advanced temp. if you aren't using advanced switch the common/ to whatever yours is

use common\widgets\Alert;


<?= Alert::widget() ?>

Your probably going to want to set some sort of timeout or even do a foreach loop to display all of the messages.

I did test the above code and both ways work. I’d personally use the afterSave() unless there is some reason you need to do more than just display a message.

It is done automatically when we have ActiveForm input.

<?= $form->field($model, 'username', [])->textInput(['data-default' => '', 'placeholder'=>'Fill in username']) ?>

with rules and custom error message for the "username" input defined as follow.

    public function rules()


        return [

            [['username', 'password'], 'required', 'message' => 'Input cannot be left blank'],

            ['username', 'string', 'max' => 50]



Is it possible to have success message in the rule or using some method?

Hi skworden, great! This is what I need, thank you!