【问题标题】:Getting Doctrine\Collection from select form element in zend framework 3从 zend 框架 3 中的选择表单元素中获取 Doctrine\Collection
【发布时间】:2017-07-03 09:53:37
【问题描述】:

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

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

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

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

setter代码:

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

UserForm中选择元素的代码:

$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,
        ],
    ]);

那么如何让选择元素返回 Doctrine\Common\Collections\Collection?

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

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

关联字段“User\Entity\User#$roles”的类型为“Doctrine\Common\Collections\Collection|array”的预期值,改为“string”。

【问题讨论】:

    标签: php zend-framework doctrine-orm


    【解决方案1】:

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

    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,
            ],
        ]);
    

    【讨论】:

      猜你喜欢
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多