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

前端 未结 6 1356
没有蜡笔的小新
没有蜡笔的小新 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:30

    This is the way I used get around that issue.

    firstly, In Module.php, create the service (just as you have done):

    // module/Users/Module.php  
    public function getServiceConfig()
    {
        return array(
                'factories' => array(
                        'Users\Model\UsersTable' =>  function($sm) {
                            $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                            $uTable     = new UsersTable($dbAdapter);
                            return $uTable;
                        },
                        //I need to get this to the list of groups
                        'Users\Model\GroupsTable' =>  function($sm) {
                            $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                            $gTable     = new GroupsTable($dbAdapter);
                            return $gTable;
                        },
                ),
        );
    }
    

    Then in the controller, I got a reference to the Service:

    $users = $this->getServiceLocator()->get('Test\Model\TestGroupTable')->fetchAll();
            $options = array();
            foreach ($users as $user)
               $options[$user->id] = $user->name;
            //get the form element
            $form->get('user_id')->setValueOptions($options);
    

    And viola, that work.

提交回复
热议问题