jcropp
jcropp

Reputation: 1246

How to configure submit elements in one place in ZF2

I create submit buttons for my ZF2 forms using array notation similar to the skeleton application tutorial:

     $this->add(array(
         'name' => 'submit',
         'type' => 'Submit',
         'attributes' => array(
             'value' => 'Go',
             'id' => 'submitbutton',
         ),
     ));

If I expand my project from lists of Albums to lists of Books, lists of DVDs, lists of Pets, lists of YuGiOhCards, etc.; each new module requires its own form. It's easy enough to rewrite the same code to add a submit button to each form; but to ensure consistency, it makes sense to code a submit button once in a single location and call it from each of the form classes.

If I want to reuse a "global" submit button, where do I code it and how do I call it?

Upvotes: 0

Views: 67

Answers (2)

Stafox
Stafox

Reputation: 1005

You may use traits.

Just create trait which will contain addSubmit() method

protected function addSubmit()
{
    $this->add([
        'name' => 'submit',
        'type' => 'Submit',
        'attributes' => [
            'value' => 'Go',
            'id' => 'submitbutton',
        ],
    ]);
}

and use it in your form.

class MyForm extends Form
{
    use SubmitButtonFormTrait;

    // ...

    public function __construct($name = null)
    {
        parent::__construct('customName');

        // ...

        $this->addSubmit();
    }
}

Upvotes: 0

AlexP
AlexP

Reputation: 9857

You can use the form element manager; which is a specialised service manager for form elements providing all the usual reusable services and DI using factories.

For example, you could provide your button as a service.

'form_elements' => [
    'factories' => [
        'MySubmitButton' => 'MyModule\Form\Element\MySubmitButtonFactory',
    ],
],

Then create the factory.

namespace MyModule\Form\Element;

use Zend\Form\Element\Submit; 

class MySubmitButtonFactory
{
    public function __invoke($formElementManager, $name, $requestedName)
    {
        $element = new Submit('submit');
        $element->setAttributes([
            'value' => 'Go',
            'id' => 'submitbutton'
        ]);
        return $element;
    }
}

When you need to add this to a form you should fetch the element from the FormElementManager service first.

$formElementManager = $serviceManager->get('FormElementManager');
$button = $formElementManager->get('MySubmitButton');

Or when you need to add via config in a form, the form factory will use the type key and pull from the FormElementManager for you.

 $this->add([
     'name' => 'submit',
     'type' => 'MySubmitButton',
 ]);

Upvotes: 1

Related Questions