Question

In the Yii-framework, validations still continue even after a validation failed. This is useful for showing the user errors to every field (like you have to fill out field1 and field2), but if the user doesn't exists in the database, he tries to check, if the passwords match in the database (with the non-existing user).

Is there any way to abort the validation after the validation of a certain attribute failed?

I've found this link, but I don't want to edit framework-classes. Many different teams in our company use the same framework folder. So if I override a base class, somebody might then re-override my class (e.g. updating the framework).

Is there any other approach than extending from CValidator and tell the other validators to extend from the new CValidator?

My current idea was to tell Yii to use another class as CValidator, but I can't find where to accomplish this.

I could aswell import a class named CValidator, so he automatically picks my class. But then again, I receive an error because he tries to redeclare the class.

Or is there probably any way to solve this problem using namespaces?

Was it helpful?

Solution

You may override validate method of CActiveRecord like this:

public function validate($attributes=null, $clearErrors=true)
{
    if($clearErrors)
        $this->clearErrors();
    if($this->beforeValidate())
    {
        $breakableAttributes = $this->breakableAttributes();
        foreach($this->getValidators() as $validator) {
            $validator->validate($this,$attributes);
            foreach ($breakableAttributes as $ba) {                    
                if ($this->hasErrors($ba))
                    return false;
            }
        }
        $this->afterValidate();
        return !$this->hasErrors();
    }
    else
        return false;
}

it will return false on getting first validation error.

Answering your question "But how if I only want to abort the validation on certain attributes?"

In this case I would do the next:

At your BaseModel except overriden validate() method define the next one:

abstract public function breakableAttributes()
{
    return array();
}

and override it in certain models, something like

public function breakableAttributes()
{
    return array('email', 'username');
}

method validate() has been also changed for handling this

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top