2017-02-14 116 views
1

我試圖在我的模塊中實現https://github.com/ZF-Commons/zfc-rbac。此刻我卡住了,因爲我得到以下異常:從Zend框架中選擇表單元素獲取Doctrine Collection 3

將參數1傳遞給User \ Entity \ User :: setRoles()必須實現接口Doctrine \ Common \ Collections \ Collection,給定的數組...

線,這導致的UserManager類錯誤:$user->setRoles($data['role']);

所以,很明顯,在實體二傳手是類型選擇,它返回$data['role']元素的錯誤或表單元素。

代碼二傳手:

選擇元素的
public function setRoles(Collection $roles) 
{ 
    $this->roles->clear(); 
    foreach ($roles as $role) { 
     $this->roles[] = $role; 
    } 
} 

代碼在用戶窗體:

$this->add([    
     'type' => 'DoctrineModule\Form\Element\ObjectSelect', 
     'name' => 'role', 
     'attributes' => [ 
      'multiple' => true, 
     ], 
     'options' => [ 
      'object_manager' => $this->entityManager, 
      'target_class' => 'User\Entity\Role', 
      'label' => 'Role', 
      'value_options' => $roles, 
      'disable_inarray_validator' => true, //TODO: create validator 
      'required' => true, 
     ], 
    ]); 

那麼,如何使甘蔗的選擇元素返回主義\ COMMON \收藏\收藏?

我試圖從Doctrine命名空間使用ArrayCollection,但它沒有奏效。我是否必須創建單獨的類,實現Collection接口並將它與select元素一起使用?或者也許有一些更方便的方法來實現這一目標?

我也試圖與去除@var,@參數註釋和類型的實體,但在這種情況下,我已經得到了以下信息:

類型的

期望值「學說\ COMMON \收藏\收藏|數組「用於關聯字段」User \ Entity \ User#$ roles「,取而代之的是」string「。

回答

0

我找到了解決我的問題的方法。在用戶實體二傳手是正確的我只是做小助手功能,將數組轉換從選擇輸入到數組作用對象:

private function getRolesFromArray($array){ 
    $roles = $this->entityManager->getRepository(Role::class) 
      ->findBy(['id'=> $array]); 
    return new ArrayCollection($roles); 
} 

那麼ArrayCollection的作品! 此外Form對象中還有適當的選擇字段:

$this->add([    
     'type' => 'DoctrineModule\Form\Element\ObjectSelect', 
     'name' => 'role', 
     'attributes' => [ 
      'multiple' => true, 
     ], 
     'options' => [ 
      'object_manager' => $this->entityManager, 
      'target_class' => 'User\Entity\Role', 
      'label' => 'Role', 
      'required' => true, 
     ], 
    ]);