I have question is it possible to create model rules that are dependent from selection. Maybe I give example.
I have radio button with two possible choices individual client and company, then i have some fields like name, address city and so on. And last field is NIP (Tax Identification Number), witch should be required only if someone chooses company in first field. How can I do that.
I know i can use scenarios, but how can I change scenario depending on changes in my model?
I’d also use scenarios here (‘client’ and ‘company’ maybe). Then before you do validate() or save() on the model, just change the scenario:
// If your radio button attribute is clientType and 1=company, other=client:
$model->scenario = $model->clientType===1 ? 'company':'client';
if ($model->save())
...
The method of scenarious is confortable if you have a limited number of choices.
If, for example, you have 4 checkbox address1, address2, address3 and address4, each of them make some field to be required (country, city, zip, address), you can try a different approach.
you can add a custom rule
public function rules()
{
return array(
array(...),
array(...),
array('address1', 'address1Required'),
);
}
and then you create a function for do the validation itself:
public function address1Required()
{
if ($this->address1)
{
CRequiredValidator::validate($this, array('country1', 'city1', 'zip1', 'address1'))
}
}
i ld like to share trick i use to on dependent validation
Assign custom validator to your Model attribute.
public function rules()
{
return array(
array(...),
array(...),
array('type', 'customValidators'),
);
}
Now write another function named "customValidators" as follows and on condition basis write related validations
public function customValidators(){
if ((int)$this->type===1)
{
$labels = $this->attributeLabels(); // Getting labels of the attributes
if((int)$this->dependendentAttribute<=0){ // dependendentAttribute is dependent on type ... must be checked only when the value of type attribute is 1
$this->addError("dependendentAttribute", $labels["dependendentAttribute"]." cannot be blank.");
}
// More dependent on type can be written here
}
}
public function rules()
{
return array(
array(...),
array('Name', 'NameUnique'),
);
}
public function NameUnique()
{
$m = Users::model()->findByAttributes(array('Name'=>$this->Name, 'Active'=>1));
if(isset($m))
$this->addError("Name", $labels["Name"]."User with this name already exist and is active.");
}