I’m looking for best way of getting form element values inside isValid() method.
I had something like this isValid():
public function isValid($data) {
$start = (int)($data['start_hour'] . $data['start_minute']);
$end = (int)($data['end_hour'] . $data['end_minute']);
if ($start >= $end) {
$this->getElement('start_hour')->addError('Start time should be less than end time');
return false;
}
return parent::isValid($data);
}
but problem is that when my data structure changes I have to change validation too.
For example, now values of start_hour, start_minute, etc becomes elements of multidimensional array, and I need edit validation like
public function isValid($data) {
$start = (int)($data['send']['start_hour'] . $data['send']['start_minute']);
$end = (int)($data['send']['end_hour'] . $data['send']['end_minute']);
.......
}
It would be great to get value of element by permanent key (like element name), so my isValid could looks like:
public function isValid($data) {
$start = (int)($this->getElement('start_hour')->getValue() . $this->getElement('start_minute')->getValue());
$end = (int)($this->getElement('end_hour')->getValue() . $this->getElement('end_minute')->getValue());
.......
}
but $this->getElement(‘start_hour’)->getValue() inside validation method return an empty value.
Is this possible to get element value in such way?
Thanks.
If this code takes place in the
isValid()method of the form, then sure you could do it as you have described. It’s just thatisValid()usually needs some data passed –$form->isValid($_POST), for example – and you just end up ignoring it (assuming the parent isZend_Form, which has an emptyisValid()method; intermediate ancestors could potentially inspect the passed data). I would consider that to be potentially confusing.Al alternative could be to create a custom validator, attach it to one of the form elements (say, the
start_hourelements). The signature for the validator’sisValid()can use the optional$contextparameter –isValid($value, $context = null). When you call$form->isValid($data), it will pass that$dataas the$contextto the the element validator. You can then use that$contextvariable to inspect the other values (start_min,end_hour,end_min, etc).