Quantcast
Channel: Franz's Web Blog
Viewing all articles
Browse latest Browse all 26

How to Pass the ServiceManager to Forms and Taking Advantage of the init()

$
0
0
Seems pretty easy and its also documented in the ZF2 docs but I think its worth repeating here.

In short, when creating forms by extending the Form object it is a good practice to create your elements inside the init() method.

namespace class\name\space;
class MyForm extends Form implements ServiceLocatorAwareInterface
{
protected $serviceLocator;

public function __construct()
{
$this->setName('MyForm');
}

public function init()
{
$this->add(array(
'type' => 'MyCustomFieldset', // You are not using a class name space,
'name' => 'custom_fieldset',
));

$this->add(array(
'type' => 'Select',
'name' => 'custom_select',
'options' => array(
'value_options' => $this->getSelections(), // you can access methods via the ServiceManager now!
),
));
}

public function getSelections()
{
$mainServiceManager = $this->getServiceLocator()->getServiceLocator();

return $mainServiceManager->get('someService')
->someMethodThatCreateSelectionArray();
}

public function getServiceLocator()
{
return $this->serviceLocator;
}

public function setServiceLocator(ServiceLocator $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
}
As you see from above, you have access now to the ServiceManager. You can even use $this->getSelections(). You will not be able to do that inside the __construct()!

Of course, you have to set this up inside Module.php via the Form Element Manager
//Module.php

public function getFormElementConfig()
{
return array(
'invokables' => array(
'MyForm' => 'class\name\space\MyForm',
'MyCustomFieldset' => 'class\name\space\MyFieldset',
)
);
}
To access the form, simply pull it from the Form Element Manager
// some controller
public function indexAction()
{
$form = $this->getServiceLocator()->get('FormElementManager')->get('MyForm');
return ViewModel(array(
'form' => $form,
))
}

Viewing all articles
Browse latest Browse all 26

Trending Articles