Check any errors in Zend Form text input - zend-framework

When i submit a form of Zend Framework 2, i would like to check in each single input has any errors, and if so, do something in the view.
Is there any "hasError()" (of the single input element) method?
For the Form, there is the "isValid()" method.
Thanks

Use getMessages() and check if variable is empty.
foreach ($form as $element) {
$messages = $element->getMessages();
if (!empty($messages)) {
// do something
}
}

Related

How to get form element value inside Zend_Form::isValid() method?

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.
Try with $this->getValue('start_hour');
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).
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
}

Symfony2 - Multiple forms in one action

I implemented a page to create an instance of an entity and a user related to this. My problem is to bind the request after the submit.
Now i have this :
$formA = $this->createForm(new \MyApp\ABundle\Form\AddObjectForm());
$formB = $this->createForm(new \MyApp\UserBundle\Form\AddUserForm());
if ($request->getMethod() == 'POST')
{
$formA->bindRequest($request);
$formB->bindRequest($request);
if ($formA->isValid() && $formB->isValid())
{
}
// ...
}
With formA and formB extends AbstractType. But, naturally, $formA->isValid() returns false. How can I do to "cut" the request for example ?
If your forms are related and need to be processed and validated at once, consider using embedded forms. Otherwise, use a separate action for each form.
If you need to provide a select field to choose a user from existing ones, consider using an entity type field.
I know that has been a long time since the answer, but maybe if someone is looking for it this could be helpfull.
I've got two forms: user_form and company_form, and the submit has take place in the same function of the controller. I can know wich form has been submit with the follow code:
if ($request->getMethod() == 'POST') {
$data = $request->request->all();
if (isset($data['user_form'])) //This if means that the user_form has been submit.
{
The company_form will pass through the else.

Zend Form MutliCheckbox Validate Number of Checked Items

I have a Zend Form with a MutliCheckbox element.
I would like to validate the number of checked items, i.e. verify that exactly 3 items are checked.
Can I do it with any current validates or do I have to write my own?
Thanks.
You will have to write your own, but that's quite simple. There is a second optional argument on the isValid() method that gives you access to all the form values, and enables this way to validate against multiple inputs.
class MyValidator extends Zend_Validate_Abstract {
public function isValid($value, $formData = null){
//you can access to all the form values in the $formData, and check/count
//the values of your multicheckbox
//this is the super-quick way, but you could also add error messages
return $isValid;
}
}
and then add it to your element
$myElement->addValidator( new MyValidator());

Zend_Form - How to addValidator after the form has been submitted

I have 2 text fields in my form.
TextFieldA - not required
TextFieldB - not required
After user submitted the form,
How to add validator / setRequired(true) to TextFieldB if the value of TextFielA is not empty?
I see two approaches in addition to #Marcin's idea.
Conditionally call setRequired() on the relevant elements by creating a preValidate() method on the form and calling it in your controller. [Really the same idea as #Marcin, but pushed down into the form itself, keeping the controller a bit leaner.]
Create a custom validator called something like ConditionallyRequired that accepts as an option the fieldname of the "other field". Then attach this validator to each element, configuring it with the name of the "other" element. Then in the validator's isValid($value, $context) method, conditionally test $value if $context['otherfield'] is non-empty.
You could do as follows:
if ($this->getRequest()->isPost()) {
$textFieldA = $yourForm->getElement('TextFieldA');
$textFieldB = $yourForm->getElement('TextFieldB');
if (!empty($_POST['TextFieldA'])) {
$textFieldB->setRequired(true);
}
if (!empty($_POST['TextFieldB'])) {
$textFieldA->setRequired(true);
}
if ($mainForm->isValid($_POST)) {
// process the form
}
}
Basically, you add the validators after the post, but before the form is validated.
Hope this helps.

Zend: Quick and succinct way of inserting custom HTML into a Zend_Form?

Is there some method that accepts inserting custom html without having to actually add form controls, even if they're hidden and making my html a decorator?
I'm looking for something like:
$this->addCustomElement( array(
'div',
'body' => '<p>inner text</p>'
) );
I need something short and quick, I don't want to create a new class or something overkill.
Well it's really as simple as this:
$note = new Zend_Form_Element('note');
$note->helper = 'formNote';
$note->setValue('<b>hi</b>');
$form->addElement($note);
But the problem is that when you submit the form, the form calls $note->isValid(), which overrides the value, so if there are errors with the form, the next time you display it, the custom HTML won't be shown. There are two easy ways to fix this, the first is to override isValid() in your Form class like this:
public function isValid($data)
{
$note = $this->note->getValue();
$valid = parent::isValid($data);
$this->note->setValue($note);
return $valid;
}
But personally I find this kinda hackish way, and prefer the second option. That is to write a very simple class (this should really be part of Zend itself, I have no idea why it isn't, since it includes a formNote view helper, but no element that uses it):
class My_Form_Element_Note extends Zend_Form_Element_Xhtml
{
public $helper = 'formNote';
public function isValid($value, $context = null) { return true; }
}
Then you just have to do:
$note = new My_Form_Element_Note('note');
$note->setValue('<b>hi</b>');
$form->addElement($note);
And everything will just work.
Other options include doing some black magic with decorators, but I really recommend you to not go down that path.
Also note the AnyMarkup Decorator.