Reputation: 7404
I want to validate field based on condition in Yii model.
I've two fields in my view
type (radiobutton): standard & special
term (textfield) : any text data
Current I am showing term textbox based on type condition i.e. if type is special then show o/w hide.
I want to validate it using Yii required rule that is if user select radio button special then he must have to fill term textfield data o/w its not mandatory.
If I use required for special then its validating in case of type = standard which is wrong. I've did following custom validation but its not working.
public function rules() {
array('type', 'required'),
array('term', 'checkTerm', 'trigger' => 'type'),
}
public function checkTerm($attribute, $params) {
if ($this->$params['trigger'] == "Special") {
if (empty($attribute))
$this->addError($attribute, 'Special term cannot be blank.');
}
}
Where I am going wrong? Need Help. Thanks
Upvotes: 3
Views: 4028
Reputation: 6297
Instead of
if (empty($attribute))
$this->addError($attribute, 'Special term cannot be blank.');
}
use
if (empty($this->term))
$this->addError($attribute, 'Special term cannot be blank.');
}
Upvotes: 1
Reputation: 4607
Try this :
public function rules() {
array('type', 'required'),
array('term', 'checkTerm'),
}
public function checkTerm() {
if ($this->type == "Special") {
if (empty($this->term))
$this->addError("term", 'Special term cannot be blank.');
}
}
Upvotes: 3