Symfony 3 FormType - 实体到选项数组

时间:2017-06-07 15:33:27

标签: php arrays forms symfony entity

我想知道如何在我的createForm函数中正确传递我的实体和另一个变量?

让我解释一下,我想这样做:

$repo = $em->getRepository('ProjectBundle:Organisation\Organisation');
            $list = $repo->children($this->getUser()->getOrganisation());
            $form = $this->createForm('ProjectBundle\Form\Robot\RobotType', array($entity,$list));

我需要将另一个变量传递给我的FormType,所以我直接使用数组。

我的FormType:

<?php

namespace ProjectBundle\Form\Robot;

use ProjectBundle\Entity\Robot\Robot;
use ProjectBundle\Form\User\UserType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RobotType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('serial_number')
            ->add('shell_color',ChoiceType::class,array(
                'choices' => Robot::getArrayShellColor()
            ))
            ->add('tray1Color',ChoiceType::class,array(
                'choices' => Robot::getTrayColor()
            ))
            ->add('tray2Color',ChoiceType::class,array(
                'choices' => Robot::getTrayColor()
            ))
            ->add('tray3Color',ChoiceType::class,array(
                'choices' => Robot::getTrayColor()
            ))
            ->add('hasBattery')
            ->add('volume')
            ->add('organisation',null,array('choices' => $options['data'][1]));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'ProjectBundle\Entity\Robot\Robot'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'projectbundle_robot_new';
    }


}

在这里,我需要为组织字段获取变量$ list,因此它是$options['data'][1]

但我有一个错误,我理解但我不知道如何纠正:

The form's view data is expected to be an instance of class ProjectBundle\Entity\Robot\Robot, but is a(n) array. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) array to an instance of ProjectBundle\Entity\Robot\Robot.

这是正常的,因为现在我将它传递给一个数组,它是我的变量$options['data'][0],它现在包含我的对象。

怎么办? 谢谢

1 个答案:

答案 0 :(得分:1)

您应该将ProjectBundle \ Entity \ Robot \ Robot实体作为第二个参数传递给createForm方法,将options数组作为第三个参数传递。

$form = $this->createForm('ProjectBundle\Form\Robot\RobotType', $entity, array($list));