Search code examples
phpvalidationyiiyii-components

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?


Solution

  • 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.