3
votes

I am currently playing around with ZF2 beta 4 and I seem to be stuck when i try to use fieldsets within a form and getting the data back into the form when the form is submitted. I am not sure if I am not setting the input filters right for fieldsets or I am missing something. For example, I have the following (simplified to make it clear):

Controller

public function indexAction(){
   $form = new MyForm();
   $request = $this->getRequest();
          if ($request->isPost()) {
                 $form->setData($request->post());
                 if ($form->isValid()) {
                        //Do something
                        print_r($form->getData()); //for debug
                 }
          }
   return array('form' => $form);
}

MyForm.php

class MyForm extends Form
{
    public function __construct()
    {
        parent::__construct();
        $this->setName('myForm');
        $this->setAttribute('method', 'post');

        $this->add(array(
                    'name' => 'title',
                    'attributes' => array(
                    'type'  => 'text',
                    'label' => 'Title',
                    ),
                 ));

        $this->add(new MyFieldset('myfieldset'));

        //setting InputFilters here
        $inputFilter = new InputFilter();
        $factory = new InputFactory();

        $inputFilter->add($factory->createInput(array(
            'name'     => 'title',
            'required' => true,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
        )));

        //Now add fieldset Input filter
        foreach($this->getFieldsets() as $fieldset){
              $fieldsetInputFilter = $factory->createInputFilter($fieldset->getInputFilterSpecification());
              $inputFilter->add($fieldsetInputFilter,$fieldset->getName());
        }

        //Set InputFilter
        $this->setInputFilter($inputFilter);
    }
}

MyFieldset.php

class MyFieldset extends Fieldset implements InputFilterProviderInterface{
    public function __construct($name)
    {
        parent::__construct($name);
        $factory = new Factory();

        $this->add($factory->createElement(array(
            'name' => $name . 'foo',
            'attributes' => array(
                'type'  => 'text',
                'label' => 'Foo',
            ),
        )));
    }

    public function getInputFilterSpecification(){
        return array(
            'foo' => array(
                'required' => true,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
            ),
        );
    }
}

I am able to output the form as expected and I end up with two input elements named 'title' and 'myfieldsetfoo' (the name given when outputing with the ViewHelper). So of course when I submit the raw post will show values for 'title' and 'myfieldsetfoo'. However, when I use SetData() the values for the field set are not being populated (although I can see the values in the raw post object). Instead, examining the output of '$form->getData()' I receive:

Array(
   [title] => Test,
   [myfieldset] => Array(
                         [foo] =>
                        )
)

What am I missing? What do I need to do so that ZF2 understands how to populate the fieldset?

Thanks for any help, this is driving me crazy.

3

3 Answers

8
votes

Why I do is concatenate InputFilter so I could handle the whole HTML form array posted.

<form method="POST">
<input type="text" name="main[name]" />
<input type="text" name="main[location]" />
<input type="text" name="contact[telephone]" />

<input type="submit" value="Send" />
</form>

This will create an array posted like

post["main"]["name"]
post["main"]["location"]
post["contact"]["telephone"]

Filtered and validated with:

use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;

$post = $this->request->getPost();
$inputFilter = new InputFilter();
$factory = new InputFactory();

// $post["main"]
$mainFilter = new InputFilter();
$mainFilter->add($factory->createInput(array(
    'name'     => 'name',
    'required' => true,
    'filters'  => array(
        array('name' => 'StripTags'),
        array('name' => 'StringTrim'),
    ),
    'validators' => array(
        array(
            'name'    => 'StringLength',
            'options' => array(
                'encoding' => 'UTF-8',
                'min'      => 1,
                'max'      => 100,
            ),
        ),
    ),
    )));

$mainFilter->add($factory->createInput(array(
    'name'     => 'location',
    'required' => true,
    'filters'  => array(
        array('name' => 'StripTags'),
        array('name' => 'StringTrim'),
    ),
    'validators' => array(
        array(
            'name'    => 'StringLength',
            'options' => array(
                'encoding' => 'UTF-8',
                'min'      => 1,
                'max'      => 100,
            ),
        ),
    ),
    )));
$inputFilter->add($mainFilter, "main");

// $post["contact"]
$contactFilter = new InputFilter();
$contactFilter->add($factory->createInput(array(
    'name'     => 'name',
    'required' => true,
    'filters'  => array(
        array('name' => 'StripTags'),
        array('name' => 'StringTrim'),
    ),
    'validators' => array(
        array(
            'name'    => 'StringLength',
            'options' => array(
                'encoding' => 'UTF-8',
                'min'      => 1,
                'max'      => 100,
            ),
        ),
    ),
    )));
$contactFilter->add($mainFilter, "contact");

//Set posted data to InputFilter
$inputFilter->setData($post->toArray());

http://www.unexpectedit.com/zf2/inputfilter-validate-and-filter-a-form-data-with-fieldsets

0
votes

I think you forgot to prepare your form in the controller:

return array('form' => $form->prepare());

This will rename the "name" field of your fieldset to "myfieldset[foo]", so you don't have to prepend the fieldsets name on your own.

Just use

'name' => 'foo'

instead of

'name' => $name . 'foo'

in your fieldset class.

-1
votes

I think the problem is that you declare a new form in your controller. And that clear the previous form.

$form = new MyForm();

I use the Service Manager to declare the form and filters. And then in the controller I do:

$form = $this->getServiceLocator()->get('my_form');

That way I always get the object I want

Update

I no longer use service manager to call forms. I just call a new form and issue $form->setData($data);

The source for the data can also be entity though then I would issue: $form->bind($entity)