Show addError without specifying a field.

Hi,

How do I show an error message without hooking it onto a specific field.

For example I have tried:


$this->addError('', 'Logon incorrect, please check both your Email Address and Password!');

and


$this->addError('Logon incorrect, please check both your Email Address and Password!');

Above does not work and I don’t want to do this:


$this->addError('username', 'Logon incorrect, please check both your Email Address and Password!');

Doing this, the username field is highlighted and the user thinks that the username is the problem.

Thanks

Why don’t you use a variable in controller and pass this to view?

Thanks, I could do that, but is there no way for addError to do this?

It would be nice to handle most such things on the Controller and keep the view clean.

addError refers to model.

In this case error handling is at controller level (login process), so in my humble opinion is more correct to handle this in controller and then pass value to view.

Thanks, I will do that then.

It is controller level, yes, but passing value to view and then doing some more coding to show in view is an overhead if you ask me. The addError function already exists and the framework already allows for it to display messages on the view based on a field.

It will be a nice feature to have in the next release if the addError function could be used without specifying any field attribute.

hi, you can do that by adding custom validation in rules

example





class LoginForm exdtends Model

{


   public $username,$password;


   public function rules()

   {

     return [

       [['username', 'password'], 'myValidator'],

     ];

   }


   public function myValidator($attribute, $params)

   {

     $this->addError($attribute, 'Incorect username or password');

   }


}






Thanks, but that will not work. It will mark the password field as red and give the error message. I don’t want any fields marked because it must be a general error.

Hello all!
on the model, treat the erro (if…) and send it to ‘message’

$this->addError('message', 'User invalid for example');

on view get the errors ‘message’

if ($error = $model->getErrors('message')) {
    if ($error && isset($error[0])) {
        $error = $error[0];
    }
};

and show it wherever you wish

<div class="col alert alert-danger" role="alert">
                    <?= $error ?>
                </div>