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.
Of course, you have to set this up inside Module.php via the Form Element Manager
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;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()!
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;
}
}
Of course, you have to set this up inside Module.php via the Form Element Manager
//Module.phpTo access the form, simply pull it from the Form Element Manager
public function getFormElementConfig()
{
return array(
'invokables' => array(
'MyForm' => 'class\name\space\MyForm',
'MyCustomFieldset' => 'class\name\space\MyFieldset',
)
);
}
// some controller
public function indexAction()
{
$form = $this->getServiceLocator()->get('FormElementManager')->get('MyForm');
return ViewModel(array(
'form' => $form,
))
}