First error without attribute


(Biz) #1

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.


#2

You could use firstErrors instead of errors:

return reset($model->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.


(Biz) #3

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


(Alexander Makarov) #4

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.


#5

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


(Alexander Makarov) #6

Try

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