2012-09-19 72 views

回答

1

你可以這樣做:

創建擴展字段集的類。

如果您希望對此字段進行某種驗證,請實現InputFilterProviderInterface類。

要訪問服務管理器,需要實現ServiceLocatorAwareInterface和兩個方法setServiceLocator()和getServiceLocator()。

默認情況下,Zend Framework MVC註冊一個初始化程序,它將ServiceManager實例注入到實現Zend \ ServiceManager \ ServiceLocatorAwareInterface的任何類中。 read this

namespace Users\Form; 

use Zend\InputFilter\InputFilterProviderInterface; 
use Zend\ServiceManager\ServiceLocatorAwareInterface; 
use Zend\ServiceManager\ServiceLocatorInterface; 
use Zend\Form\Element; 
use Zend\Form\Fieldset; 

class GroupsFieldset extends Fieldset implements InputFilterProviderInterface, 
     ServiceLocatorAwareInterface 
{ 

    /** 
    * @var ServiceLocatorInterface 
    */ 
    protected $serviceLocator; 

    public function __construct() 
    { 
     parent::__construct('groups'); 

     $this->setLabel('Group'); 

     $this->setName('groups'); 

     $sl = $this->getServiceLocator(); 

     $sm = $sl->get('Users\Model\GroupsTable'); 

     $groups = $sm->fetchAll(); 

     $select = new Element\Select('groups'); 

     $options = array(); 

     foreach ($groups as $group) { 
      $options[$group->id] = $group->name; 
     } 

     $select->setValueOptions($options); 
    } 

    /** 
    * Set serviceManager instance 
    * 
    * @param ServiceLocatorInterface $serviceLocator 
    * @return void 
    */ 
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator) 
    { 
     $this->serviceLocator = $serviceLocator; 
     return $this; 
    } 

    /** 
    * Retrieve serviceManager instance 
    * 
    * @return ServiceLocatorInterface 
    */ 
    public function getServiceLocator() 
    { 
     return $this->serviceLocator; 
    } 

    /** 
    * 
    * @return multitype:multitype:boolean 
    */ 
    public function getInputFilterSpecification() 
    { 
     return array(
       'name' => array(
         'required' => true 
       ) 
     ); 
    } 
} 

比module.php

public function getServiceConfig() 
{ 
    return array(
      'factories' => array(
        'Users\Model\UsersTable' => function($sm) { 
         $dbAdapter1 = $sm->get('Zend\Db\Adapter\Adapter'); 
         $table1  = new UsersTable($dbAdapter1); 
         return $table1; 
        }, // Adapter and table groups here 
        'Users\Model\GroupsTable' => function($sm) { 
         $dbAdapter2 = $sm->get('Zend\Db\Adapter\Adapter'); 
         $table2  = new GroupsTable($dbAdapter2); 
         return $table2; 
        }, 
      ), 
    ); 
} 

終於在表單

$groups = new GroupsFieldset(); 
    $this->add($groups); 
+1

過得好服務管理器在那裏? –

+0

我得到致命錯誤:在$ sm = $ sl-> get('Dashboard \ Model \ DepTable');中調用一個非對象的成員函數get()。 DepTable工作正常,我可以列出,添加,刪除等 –

+0

我猜這是因爲服務定位器沒有設置。 ServiceLocatorAware接口將使ServiceLocator被注入到對象中,但是在類被實例化後會發生這種情況。關於這個問題的好博客 - http://www.michaelgallego.fr/blog/?p=205 – DrBeza