How to get form element value inside Zend_Form::isValid() method?
Solution 1
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 that isValid()
usually needs some data passed - $form->isValid($_POST)
, for example - and you just end up ignoring it (assuming the parent is Zend_Form
, which has an empty isValid()
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_hour
elements). The signature for the validator's isValid()
can use the optional $context
parameter - isValid($value, $context = null)
. When you call $form->isValid($data)
, it will pass that $data
as the $context
to the the element validator. You can then use that $context
variable to inspect the other values (start_min
, end_hour
, end_min
, etc).
Solution 2
Try with $this->getValue('start_hour');
Solution 3
Try calling
$form->populate($data)
Before calling isValid that way the data will be in your form.
Then $this->getValue('start_hour');
should work from within isValid()
.
So to be sure: Somewhere in your code (probably controller) there is somthing like:
$this->view->form = new MyForm();
$this->populate($data); //add this
if($this->view->form->isValid($data)){
//do stuff
}
Vovkin
Updated on June 05, 2022Comments
-
Vovkin almost 2 years
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.
-
Vovkin over 12 yearsit returns an empty value too