I use model which not contain attribute 'countries' because I'm saving it in relations-model via many-to-many relation. When I'm creating form in view I use multiple select for custom field 'countries'. How can I validate it from model on $model->validate()
?
Asked
Active
Viewed 102 times
-1

Danila Ganchar
- 10,266
- 13
- 49
- 75

Сергей Перенец
- 27
- 6
1 Answers
0
// protected/extensions/validators/CountryValidator.php
class CountryValidator extends CValidator
{
/**
* @inheritdoc
*/
protected function validateAttribute($object, $attribute)
{
/* @var $object CFormModel */
// for example check exist countryId in db or no
// you can use any other logic
$country = Country::model()->findByPk($object->$attribute);
if (null != $country) {
$object->addError($attribute, 'country not found');
}
}
...
// in your model
public function rules()
{
return array(
array('countryId', 'ext.validators.CountryValidator'),
...
// in config
'import' => array(
'ext.validators.*',
...
How to use:
$yourModel = new YourModel();
$yourModel->countryId = -1;
$yourModel->validate();
print_r($yourModel->getErrors()); die();

Danila Ganchar
- 10,266
- 13
- 49
- 75