Коллекция форм Symfony


Я пытаюсь добавить тип формы в другой тип формы.

Тип пользователя:

class CustomerType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('firstname', 'text', array(
                    'required' => 'required'
                ))
                ->add('middlename')
                ->add('lastname')
                ->add('email', 'email')
                ->add('groups', 'entity', array(
                    'class' => 'MV\CMSBundle\Entity\Group',
                    'property' => 'name',
                    'query_builder' => function(EntityRepository $er) {
                        return $er->createQueryBuilder('g')
                                  ->orderBy('g.name', 'ASC');
                    }
                ))
                ->add('profile', 'collection', array(
                    'type' => new ProfileType()
                ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'MV\CMSBundle\Entity\User',
        ));
    }

    public function getName()
    {
        return 'customer';
    }
}

Тип профиля:

class ProfileType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('isActive', 'checkbox', array(
                    'required' => false
                ))
                ->add('phone')
                ->add('address')
                ->add('city')
                ->add('zipcode')
                ->add('country')
                ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'MV\NameBundle\Entity\Profile',
        ));
    }

    public function getName()
    {
        return 'profile';
    }
}

Затем я получаю это сообщение:

Expected argument of type "array or (\Traversable and \ArrayAccess)", "MV\NameBundle\Entity\Profile" given.

Если я прокомментирую эту строку, я получу: (просто чтобы проверить, что пойдет не так;))

The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class MV\NameBundle\Entity\Profile. You can avoid this error by setting the "data_class" option to "MV\NameBundle\Entity\Profile" or by adding a view transformer that transforms an instance of class MV\NameBundle\Entity\Profile to scalar, array or an instance of \ArrayAccess. 

Что я делаю не так?

Symfony2: 2.1.8-РАЗРАБОТКА

Author: j0k, 2013-02-03

1 answers

Неясно, каково ваше сопоставление между вашей сущностью Customer и вашей сущностью Profile, но я предполагаю, что есть 2 варианта:


Вариант 1: У вас есть отношения OneToOne (у одного клиента может быть только один профиль). Поэтому вам вообще не нужна коллекция, а просто нужно встроить один объект.

->add('profile', new ProfileType());

Вариант 2: Вам нужны отношения со многими клиентами (у одного клиента может быть много профилей). В этом случае вам нужно использовать, чтобы встроить набор форм . Если это то, что вы хотите, переименуйте $profile в $profiles в своей сущности клиента и выполните следующие действия:

   //MV\CMSBundle\Entity\Customer  
   use Doctrine\Common\Collections\ArrayCollection;
   /**
   * Your mapping here. 
   * 
   * @ORM\ManyToOne(targetEntity="MV\NameBundle\Entity\Profile")
   */
   protected $profiles;

    public function __construct()
    {
         //This is why you had an error, this is missing from your entity
         //An object was sent instead of a collection.
         $this->profiles = new ArrayCollection();
    }

Наконец, обновите свою базу данных.

 12
Author: Mick, 2013-02-03 16:16:19