0
votes

I have a fieldset with some elements, and a button. When I submit the form I am getting an empty value for the button. How do I tell ZF2 to not include the button in the return data?

//In fieldset

//...other elements

$this->add([
    'name' => 'add-question',
    'type' => 'button',
    'attributes' => [
        'onclick' => 'return add_question(this)',
        'value' => 'Add Add-On',
        'class' => 'add-element text-primary',
    ],
    'options' => [
        'label' => '',
        'label_options' => [
            'disable_html_escape' => true,
        ],
    ],
]);

//In controller
if($this->request->isPost()) {
    $form->setData($this->request->getPost());
    if($form->isValid()) {
        var_dump($form->getData());
        /*
        array (size=12)
            //... other elements
           'add-ons' => array (size=2)
               //... other elements
               'add-question' => null
        */

I am aware on the from I can add a validation group, but I can't do that in a fieldset. Also, the form is just an empty form with a submit button in it for re-use - all my form elements are in fieldsets.

1
So what is the reason why you shouldn't set the validation group on the form? You don't need to set the validation group within the form class itself. What about setting it within your factories or after you configure the form with the fieldsets? Might help to show a bit more of your code like an example of the basic form and how you insert/add the fieldsets to the form. - Kwido
The form class is re-used for many forms. The form is instantiated in the controller: $form = new \Application\Form\Form(); with the fieldsets added as needed: $form->add(new \Application\Form\Part1Fieldset()); $form->add(new \Application\Form\Part2Fieldset()); //etc. This allows me to re-use the fieldsets on other pages in other "forms". - Richard Parnaby-King
Maybe add that example of how you construct them to your question to clearify it for others. But after adding the fieldsets within your controller you can still call $form->setValidationGroup($validationGroup) with a propper nested array with the same structure as you've setup your elements. - Kwido
I was hoping to not do that in the controller so I could re-use the fieldset without having to add that function in every controller it is used in. Please post as an answer. - Richard Parnaby-King
You may use this unset($data['add-ons']['add-question']) before returning data while $data is $form->getData(). - unclexo

1 Answers

0
votes

I guess your Fieldsets extends \Zend\Form\Fieldset ?

If yes : You can't setValidationGroup in you Fieldsets as they are now because they're not implements \Zend\Form\Form.

As long as \Zend\Form\Form extends \Zend\Form\Fieldset, you should be able to use the setValidationGroup like you want to for all of your forms by using the extends \Form, without breaking anything.