isValid in zend framework form returns FALSE - zend-framework

I have zend framework controller.
In init method i create a form and fill the drop-down box with
$form = new FORM_NAME();
$form->getElement('ZdGroup')->addMultiOptions($zendesk_groups);
then in action i check
$formData = $this->getRequest()->getParams();
if ($form->isValid($formData)) {
...
}
but isValid() returns FALSE
if I delete this line
$form->getElement('ZdGroup')->addMultiOptions($zendesk_groups);
it return TRUE.
I don't understand why, does anybody have an idea?

To answer the question of 'why', have you dumped the form error messages?
$form->getMessages(); //error messages
$form->getErrors(); //error codes
$form->getErrorMessages(); //any custom error messages
That might at least give you a better idea of 'why'.

Related

Symfony Form - Value Object, DataMappers and EventSubscriber

I am having trouble to dynamically modify field in my form using DataMapper and EventSubscriber.
Here is my form:
A select field
A field which will be modified by the select field above.
I am using an EventSubscriber to dynamically modify my form using AJAX.
And a DataMapper to map my Value Object to the form and vice-versa.
So when i do that:
$moneyForm = $this->createForm(MoneyType::class);
Everything is working. But when i pass my Value Object as data class:
$money = new Money(199, 'USD');
$moneyForm = $this->createForm(MoneyType::class, $money);
I got an error here:
public function mapDataToForms($viewData, $forms)
{
$forms = iterator_to_array($forms);
$forms['money']->setData($viewData ? $viewData->money() : 0);
$forms['currency']->setData($viewData ? $viewData->currency() : 'USD');
}
This error says that: Notice: Undefined index:.
It seems like the form has been replaced by a new one and i don't understand it.
I don't know why when i use a data mapper alone, or event subscriber alone everything is working.
But when i try to mix, both of them i got this error.
Does anyone have a clue of what's going on here?
Thank you

Symfony 2 unchecked checkbox missing in POST data

Unchecked checkbox is not present in GET or POST data.
How to handle it?
Is there need to do it manually or there is another reason why symfony $form->getData() does not handle it automatically?
Symfony by default parse your checkboxes to an array so if you have a checked one you will have it in your form->getData() else you will not have it, so in your controller if you don't get your checkbox in form data that's mean that the checkbox is unchecked
As explained above
I had the same issue, to be honest I dont understand why there is no option value for unchecked checkboxtype like 'unchecked_value' => false
I had to manually go over submitted fields, check if field has not been submitted then I know it is missing in form submit and that means it equal to false.
this is in my class to be run before persisting...it will basically loop over properties and set its values to false
public function setUncheckedReplacementFields(array $data)
{
foreach($this as $property => $value){
if(str_contains('Replacement', $property) !== false){
if(!in_array($property, $data)){
$method = sprintf('set%s', ucfirst($property));
if(method_exists(this, $method)){
$this->$method(false);
}
}
}
}
}
before I am persisting form I run this
$object->setUncheckedReplacementFields($request->request->get($form->getName()));
so if field is not part of form I know it has been unchecked and I loop over object to find those checkboxes and setting them to false in my case unchecked.

Silex / Symfony2 Post-Validation

Im sure this must be a RTM question, but I must be looking in the wrong places. In symfony 1.4 I used post validator callbacks quite a lot. For example checking that start and end dates were in the correct order. I am developing an app in Silex but cant figure out how to add similar functionality as a validator. This is what I am working with (basically):
$app['form.example'] = function ($app) {
$constraints = new Assert\Collection(array(
'date1' => new Assert\Date(),
'date2' => new Assert\Date(),
));
$builder = $app['form.factory']->createNamedBuilder('form', 'example', array(), array('validation_constraint' => $constraints));
return $builder
->add('date1', 'date')
->add('date2', 'date')
->getForm();
};
I can put my own validation test in the 'process form' part, like: if ($form->isValid() && --my datetest--) but it doesnt feel right to me there.
Any help? Thanks!
I guess you can use form events for this kind of thing; certainly for Symfony2, so I assume Silex too? There's a cookbook article about using it to generate dynamic forms:
http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html
Some useful detail in another SO question:
Description of Symfony2 form events?
Could have sworn I had a SO discussion about this with someone before but I cannot find the question. I used BIND_CLIENT_DATA to calculate some form fields in some code a while back; I'll see if I can dig it out.
EDIT
Okay, I found something but I'm modifying this from Symfony code so I'm not 100% on this but it might be a starting point (I hope):
$builder->addEventListener(FormEvents::BIND_NORM_DATA, function($event) {
// your form data
$data = $event->getData();
// get date objects - if you cannot dereference this way try getters
$d1 = $data['date1'];
$d2 = $data['date2'];
// naive comparison :)
$isCorrectDateOrder = $d1->getTimestamp() < $d2->getTimestamp();
// check the comparison
if (!$isCorrectDateOrder) {
// trouble... create and add a FormError object to the form
$event->getForm()->get('date1')->addError(new \Symfony\Component\Form\FormError('uh oh...'));
}
});
Hope this helps :)

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.

Populate values to checkbox while editing in zend framework

I am trying to populate the values into check box. I want check box to be checked when there is value stored in database.
This is my code in form:
$form ['test_1'] = new Zend_Form_Element_Checkbox('test_1');
$form['test_1']->setLabel('test1')->setCheckedValue('1');
$form ['test_2'] = new Zend_Form_Element_Checkbox('test_2');
$form['test_2']->setLabel('test2')->setCheckedValue('2');
If there is value 1 in database i want first check box to be checked and if its 2 then 2nd checkbox needs to be checked.
What do i need to do in the controller.
Could anyone please help me on this issue.
The easiest way would be to fetch the values from the database as an array that maps to the form input elements, e.g. return a row like
array('test_1' => 'value of checkbox', 'test_2' => 'value of checkbox');
You could then simply call $form->populate($values) and let do Zend_Form do the setting, e.g. in your controller do
public function showFormAction()
{
$form = $this->getHelper('forms')->get('MyForm');
$data = $this->getHelper('dbGateway')->get('SomeTable');
$form->populate($data->getFormData());
$this->view->form = $form;
}
Note: the helpers above do not exist. They are just to illustrate how you could approach this. Keep in mind that you want thin controllers and fat models, so you should not create the form inside the controller, nor put any queries in there.