Zend FrameWork 2 Get ServiceLocator In Form and populate a drop down list

前端 未结 6 1355
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 14:40

I need to get the adapter from the form, but still could not.

In my controller I can recover the adapter using the following:



        
6条回答
  •  灰色年华
    2021-02-02 15:33

    This is the method I used to get around that issue.

    firstly, you want to make your form implement ServiceLocatorInterface as you have done.

    You will then still need to manually inject the service locator, and as the whole form is generated inside the contrstuctor you will need to inject via the contructor too (no ideal to build it all in the constructor though)

    Module.php

    /**
     * Get the service Config
     * 
     * @return array 
     */
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                /**
                 * Inject ServiceLocator into our Form
                 */
                'MyModule\Form\MyForm' =>  function($sm) {
                    $form = new \MyModule\Form\MyFormForm('formname', $sm);
                    //$form->setServiceLocator($sm);
    
                    // Alternativly you can inject the adapter/gateway directly
                    // just add a setter on your form object...
                    //$form->setAdapter($sm->get('Users\Model\GroupsTable')); 
    
                    return $form;
                },
            ),
        );
    }
    

    Now inside your controller you get your form like this:

    // Service locator now injected
    $form = $this->getServiceLocator()->get('MyModule\Form\MyForm');
    

    Now you will have access to the full service locator inside the form, to get hold of any other services etc such as:

    $groups = $this->getServiceLocator()->get('Users\Model\GroupsTable')->fetchAll();
    

提交回复
热议问题