Use Yii rule validation to change attribute name if form attribute value is empty

1.3k Views Asked by At

I have a model that extends the Yii CFormModel and I would like to define a validation rule that checks whether the attribute value is empty and - if that is the case - sets the attribute name to an empty string instead of changing the input value.

Is such a scenario even possible or are validation rules only intended for warnings and/or changes of the input values?

Any help would be much appreciated.

Below is the example code of my model:

class LoginForm extends CFormModel
{
    public $firstName;
    public $lastName;

    public function rules()
    {
        return array(
            array('firstName, lastName', 'checkIfEmpty', 'changeAttributeName'),
        );
    }
    // some functions
}
3

There are 3 best solutions below

0
On BEST ANSWER

Not sure whether your use case is very elegant, but the following should work:

class LoginForm extends CFormModel
{
    public $firstName;
    public $lastName;

    public function rules()
    {
        return array(
            array('firstName, lastName', 'checkIfEmpty'),
        );
    }

    public function checkIfEmpty($attribute, $params) 
    {
        if(empty($this->$attribute)) {
            unset($this->$attribute);
        }
    }

    // some functions
}

Based on hamed's reply, another way would be to use the beforeValidate() function:

class LoginForm extends CFormModel
{
    public $firstName;
    public $lastName;

    protected function beforeValidate()
    {
        if(parent::beforeValidate()) {
            foreach(array('firstName, lastName') as $attribute) {
                if(empty($this->$attribute)) {
                    unset($this->$attribute);
                }
            }
        }
    }

}
0
On

You can use default rules set.

public function rules()
{
        return array(
           array('firstName', 'default', 'value'=>Yii::app()->getUser()->getName()),
        );
}

Take note that this will run at validation time, which is normally after the form has been submitted. It will not populate the form value with the default value. You can use the afterFind() method to do that.

2
On

CModel has beforeValidate() method. This method call before yii automatic model validation. You should override it in your LoginForm Model:

protected function beforeValidate()
    {
        if(parent::beforeValidate())
        {

            if($this->firstname == null)
               $this->firstname = "Some String";
            return true;
        }
        else
            return false;
    }