Pragmatism in the real world

Creating a ZF2 form from config

I have a requirement to create a Zend\Form from a dynamically created array which means that I can’t use the FormAbstractServiceFactory and so will use Zend\Form\Factory directly.

If you need to override any form elements, validators or add new ones, then you’ll need the correct plugin managers for the factory. The way to set this up is like this:

$factory = new Factory();
$formElements = $this->serviceLocator->get('FormElementManager');
$factory->setFormElementManager($formElements);
$inputFilters = $this->serviceLocator->get('InputFilterManager');
$factory->getInputFilterFactory()->setInputFilterManager($inputFilters); 

Your $factory is now configured and so you can create a form like this:

$formConfig = [
    'elements' => [
        [
            'spec' => [
                'name' => 'name',
                'options' => [
                    'label' => 'Your name',
                ],
                'attributes' => [
                    'type' => 'text',
                    'class' => 'form-control',
                    'required' => 'required',
                ],
            ],
        ],
        [
            'spec' => [
                'name' => 'email',
                'options' => [
                    'label' => 'Your email address',
                ],
                'attributes' => [
                    'type' => 'text',
                    'class' => 'form-control',
                    'required' => 'required',
                ],
            ],
        ],
    ],
    'input_filter' => [
        'name' => [
            'name'       => 'name',
            'required'   => true,
            'validators' => [
                [
                    'name' => 'not_empty',
                ],
                [
                    'name' => 'string_length',
                    'options' => [
                        'max' => 30,
                    ],
                ],
            ],
        ],
        'email' => [
            'name'       => 'email',
            'required'   => true,
            'validators' => [
                [
                    'name' => 'not_empty',
                ],
                [
                    'name' => 'email_address',
                ],
            ],
        ],
    ],
];

$form = $factory->createForm($formSpec);