First error without attribute

Hi people!
Very often it is necessary to show the user just first error in the form validation process.

I found only $model->firstErrors[$attribute] solution, but it does not work without $attribute value. I did not want to overload Model or use traits so I made the function for my base controller as follows:

public function firstErrorMessage($model){
    if(!empty($model->errors)){
        $errors=array_values($model->errors);
        if($errors[0][0]!=''){return $errors[0][0];} else {return Yii::t('msg','Some data not correct.');}
    } else {return '';}
}

So I can get first error of any model without specifying an attribute. But I am wandering if there any other solution? Thanks.

You could use firstErrors instead of errors:

$firstErrors = $model->firstErrors;
return reset($firstErrors);

This will give you the first entry in firstErrors, or false if there are no errors.

From a usability point of view I wonder however why you would want to hide other errors? As someone who has filled out a form I’d like to know and correct all errors in one step, not only one.

1 Like

Hi CeBe!
A single error used when showing alerts. Especially on mobile devices where displays are not big.

While it makes sense for alerts, displaying errors in a mobile web view is used in many apps out there and it feels just fine despite you have to scroll.

I tried this but I am getting error:

PHP Notice ‘yii\base\ErrorException’ with message ‘Indirect modification of overloaded property app\models\RegisterForm::$firstErrors has no effect’

I then tried doing return reset($model->getFirstErrors());

And got error:

PHP Notice 'yii\base\ErrorException' with message 'Only variables should be passed by reference'

I am using Yii 2.0.16.1 with PHP 7.2.14 on Ubuntu 16.04

1 Like

Try

$errors = $model->getFirstErrors();
return reset($errors);
4 Likes

updated my post to fix this error.