从zend框架3中的select form元素获取条令\集合



我正在尝试实现https://github.com/ZF-Commons/zfc-rbac在我的模块中。目前我被卡住了,因为我得到了以下异常:

传递给User\Entity\User::setRoles()的参数1必须实现接口Doctrine\Common\Collections\Collection,给定数组。。。

Line,导致UserManager类中的错误:$user->setRoles($data['role']);

所以很明显,实体中的setter是错误的,或者形成了返回$data['role']元素的select类型的元素。

设置者代码:

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

UserForm中选择元素的代码:

$this->add([            
'type'  => 'DoctrineModuleFormElementObjectSelect',
'name' => 'role',
'attributes' => [
'multiple' => true,
],
'options' => [
'object_manager' => $this->entityManager,
'target_class' => 'UserEntityRole',
'label' => 'Role',
'value_options' => $roles,
'disable_inarray_validator' => true, //TODO: create validator
'required' => true,
],
]);

那么,我如何使select元素返回Doctrine\Common\Collections\Collection

我尝试使用来自Doctrine命名空间的ArrayCollection,但没有成功。我是否必须制作单独的类,实现Collection接口并将其与select元素一起使用?或者可能有一些更方便的方法来实现这一点?

我还尝试在实体中删除@var、@param注释和类型,但在这种情况下,我得到了以下消息:

关联字段"User\Entity\User#$roles"的类型"Doctrine\Common\Collections\Collection|array"的预期值,而得到了"string"。

我找到了解决问题的方法。User实体中的setter是正确的,我只需要制作一个小助手函数,它将把select输入的数组转换为Role对象的数组:

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

所以ArrayCollection有效!此外,在Form对象中也有适当的选择字段:

$this->add([            
'type'  => 'DoctrineModuleFormElementObjectSelect',
'name' => 'role',
'attributes' => [
'multiple' => true,
],
'options' => [
'object_manager' => $this->entityManager,
'target_class' => 'UserEntityRole',
'label' => 'Role',
'required' => true,
],
]);

最新更新