当前位置: 动力学知识库 > 问答 > 编程问答 >

rest - Can not retrieve the object manager in the input_filter config

问题描述:

I want to reuse a Fieldset that implements InputFilterProviderInterface o it has the method getInputFilterSpecification where I can declare the specifications for all the elements in the fieldset.

public function getInputFilterSpecification()

{

return array(

'email' => array(

'filters' => $this->getTextFilters(),

'validators' => array(

$this->getUniqueObjectValidator()

...

The problem is that the getUniqueObjectValidator needs the Doctrine\ORM\EntityManager but it is not declared in the ServiceLocator for the InputFilter.

How do you think I can acces to the EntityManager in the inputFilter factories?

网友答案:

To do that, you need to inject the DoctrineORM EntityManager in your fieldset. You could for example transfer ther $em from controller to form, and then from form to fieldset but this is a bad and ugly solution especialy when you have a complexe form with many fieldsets. A good solution is to take advantage from the Zend\ServiceManager\ServiceLocator.

Here is a proper way handle this :

First, you have to implement the getFormElementConfig() function in your Module class. Something like this :

// module.php
public function getFormElementConfig()
{
return array(
    'factories' => array(
        'yourfieldset' => function ($sm) {
            $em = $sm->getServiceLocator()->get('Doctrine\ORM\EntityManager');
            $fieldset = new YourFieldset($em);
            return $fieldset;
        }
    )
);
}

Then make sure your fieldest calls the parent constructor like this :

parent::__construct('yourfieldset'); //with the name of the factory

And finaly instantiate the form via the FormElementManager. :

$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('ModuleName\Form\YourForm');

Please see these links for more details :

  • Handling dependencies in ZF2 forms
  • Inject DoctrineORM EntityManager in ZF2 Form
  • SO : Handling dependencies in Zend Framework 2 Forms
  • Howto Handle External Form Element Dependencies with FormElementManager

Hope this helps

分享给朋友:
您可能感兴趣的文章:
随机阅读: