phpyiiyii-cformmodel

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


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
}

Solution

  • 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);
                    }
                }
            }
        }
    
    }