Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii validation rules for foreign key

Let's say I have an ActiveRecord with the following validation rules:

public function rules() {
    return array(
        array('model', 'required'),
        // ....
        array('model', 'exist',
            'allowEmpty' => false,
            'attributeName' => 'id',
            'className' => 'Model',
            'message' => 'The specified model does not exist.'
        )
    );
}

The first rule forces the model field not to be blank, the second one checks it has a consistent value (model is a foreign key).

If I try to validate a form in which I leave empty the field model I get 2 errors, one for the first rule and one for the second rule.

I would like to receive only the "cannot be blank" error message.

Is there a way to stop the validation when the first rule is not satisfied?

like image 574
Andrea Avatar asked Dec 27 '22 19:12

Andrea


1 Answers

You can use skipOnError:

return array(
    array('model', 'required'),
    // ....
    array('model', 'exist',
        'allowEmpty' => false,
        'attributeName' => 'id',
        'className' => 'Model',
        'message' => 'The specified model does not exist.',
        'skipOnError'=>true
    )
);

Edit:

Someone commented about the above being not clear, probably because the field name here is also model. So keep that in mind when implementing.

like image 135
bool.dev Avatar answered Dec 29 '22 12:12

bool.dev