Why does not work short names when I create custom form elements in Zend Framework 2? -
i create custom element here: zf2docs: advanced use of forms
1.create customelement class in application/form/element/customelement.php
2.add module.php function
public function getformelementconfig() { return array( 'invokables' => array( 'custom' => 'application\form\element\customelement', ), ); }
if use fqcn works fine:
$form->add(array( 'type' => 'application\form\element\customelement', 'name' => 'mycustomelement' ));
but if use short name:
$form->add(array( 'type' => 'custom', 'name' => 'mycustomelement' ));
throws exception:
zend\servicemanager\servicemanager::get unable fetch or create instance custom
problem
the error due how instantiating $form
object. if use new zend\form\form
expression or similar form not set correct service locator.
$form = new \zend\form\form; $form->add(array( 'type' => 'custom', 'name' => 'foobar', ));
solution
the trick here use formelementmanager
service locator instantiate form.
// inside controller action $form = $this->getservicelocator()->get('formelementmanager')->get('form'); $form->add(array( 'type' => 'custom', 'name' => 'foobar', ));
better yet, define form()
method in controller shortcut you:
class mycontroller extends abstractactioncontroller { public function form($name, $options = array()) { $forms = $this->getservicelocator()->get('formelementmanager'); return $forms->get($name, $options); } public function createaction() { $form = $this->form('someform'); // ... } }
explanation
each form object attached form factory in turn attached service locator. service locator in charge of fetching classes used instantiate new form/element/fieldset objects.
if instantiate new form object (all itself), blank service locator instantiated , used fetch later classes within form. each subsequent object attached same service locator.
the problem here getformelementconfig
configures specific instance of service locator. formelementmanager
service locator. once it's configured, forms pulled service locator attached service locator , used fetch other elements/fieldsets etc.
hope solves issue.
Comments
Post a Comment