Zend Form: Dependant field validation

2019-09-05 00:55发布

I have a form with two select boxes: country and city, city depending on the selected country. Note that the city field is populated dynamically when a country is selected using Ajax.

So far I extended Zend_Form_Element_Select overriding isValid() for the city select box, and I'll use the $context argument to get the selected country and check if the city is valid (for that country).

I want to skip city validation if the country validation fails. For example someone can inject a bad value into the country field (and the country validation will fail), and my city validation shouldn't take place and don't do that query on db, it simply shouldn't pass the validation.

How can I achieve this?

1条回答
【Aperson】
2楼-- · 2019-09-05 01:20

Override the isValid() and setDefaults() methods in your Form class to populate the city element when the country element is set.

function isValid($data) {
    if (isset($data['country'])) {
        $this->populateCity($data['country']);
    }
    return parent::isValid($data);
}

function setDefault($name, $value) {
    if ('country' === $value) {
        $this->populateCity($value);
    }
    return parent::setDefault($name, $value);
}
查看更多
登录 后发表回答