Yii - dynamically change rules from controller

You can use scenario. In the model:

class Model extends CActiveRecord {
    // ....
    public function rules() {
        return array(
            array('colour', 'required', 'on' => 'hasColour')
        );
    }
    // ....
}

And in the controller:

public function actionOrder() {
    // ....
    $model = new Product();
    if ($product->HasColour) {
        $model->setScenario('hasColour');
    }
}

So, required colour will be validated when the model's scenario is hasColour


class LoginForm extends CFormModel
{
    public $username;
    public $password;
}

$form = new LoginForm();
$form->validatorList->add(
    CValidator::createValidator('required', $form, 'username, password')
);

Now $form has two required fields.


One approach is to use a custom validation rule. For example, the rule:

array('colour', 'requiredOnHasColour'),

And then the validator method in the same model class:

public function requiredOnHasColour($attribute, $params) {
    if ($this->hasColour && $this->$attribute == null)
        $this->addError($attribute, 'Colour is required.');
}

More info: Create your own validation rule

Tags:

Php

Yii