Php 在Symfony 2.0中呈现表单集合时出现问题

Php 在Symfony 2.0中呈现表单集合时出现问题,php,forms,symfony,Php,Forms,Symfony,我拥有以下用户实体: class User extends BaseUser implements ParticipantInterface { /** * @Exclude() * @ORM\OneToMany(targetEntity="App\MainBundle\Entity\PreferredContactType", mappedBy="user", cascade={"all"}) */ protected $prefer

我拥有以下用户实体:

class User extends BaseUser implements ParticipantInterface
{   
     /**
     * @Exclude()   
     * @ORM\OneToMany(targetEntity="App\MainBundle\Entity\PreferredContactType", mappedBy="user", cascade={"all"})
     */
    protected $preferredContactTypes;

   /**
     * Add preferredContactType
     *
     * @param \App\MainBundle\Entity\PreferredContactType $preferredContactType
     * @return User
     */
    public function addPreferredContactTypes(\App\MainBundle\Entity\PreferredContactType $preferredContactType)
    {
        $this->preferredContactTypes[] = $preferredContactType;

        return $this;
    }

    /**
     * Remove preferredContactType
     *
     * @param \App\MainBundle\Entity\PreferredContactType $preferredContactType
     */
    public function removePreferredContactTypes(\App\MainBundle\Entity\PreferredContactType $preferredContactType)
    {
        $this->preferredContactTypes->removeElement($preferredContactType);
    }

    /**
     * Get preferredContactType
     *
     * @return \App\MainBundle\Entity\PreferredContactType 
     */
    public function getPreferredContactTypes()
    {
        return $this->preferredContactTypes;
    }
}
我想创建一个表单,显示preferredContactType的多个选项:

  $contactOptions = $em->getRepository('AppMainBundle:ContactType')->findAll();
  $settingsForm = $this->createForm(new UserType(), $user, array(
            'contact' => $contactOptions,
        ));
下面是我的用户类型:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
                $builder->add('preferredContactTypes', 'collection', array('type' => 'choice', 'options' => array('choices'  => $options['contact'], 'multiple' => true, 'expanded' => true)))

                ;

    }
但现在我得到了一个错误:

需要一个数组


如何解决这个问题?

它失败了,因为您将ArrayCollection类的参数实例(在
$em->getRepository('AppMainBundle:ContactType')->findAll();
中返回)传递给了
选项。但是
选项
参数需要是数组()

您可以在ArrayCollection上使用
toArray()
方法来检索数组,但它不会给出预期的结果,因为它将是
ContactType
的实例数组

从实体中形成一些选择列表的最佳方法是使用
entity
类型,而不是
choice
。请参阅此处的详细信息:

您还可以在某些类中实现
Symfony\Component\Form\Extension\Core\ChoiceList\choicelisterface
,并将其用作
choice
表单字段中的参数
choice\u列表
。例如,您可以扩展
Symfony\Component\Form\Extension\Core\ChoiceList\lazycchoicelist
并实现
loadChoiceList()
方法