Symfony Doctrine ArrayCollection错误

时间:2018-05-24 23:23:02

标签: php forms symfony doctrine

我目前的设置如下所述。我想要的是。一个经销商可以有多个类别。但是一个类别可以具有1个分发者1:N< => N:1。但是,即使分发者输入字段为空,单击创建类别也会失败。

分类

/**
 * @var string
 *
 * @ORM\Id()
 * @ORM\Column(type="string", nullable=false, unique=true)
 * @ORM\GeneratedValue(strategy="UUID")
 */
private $id;

/**
 * @var string
 * @ORM\Column(type="string", nullable=false)
 */
private $title;

/**
 * @var Distributor
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Distributor", inversedBy="category")
 * @ORM\JoinColumn(referencedColumnName="id")
 */
private $distributor;

发行者:

/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(type="string", length=100)
 */
private $name;

/**
 * @var ArrayCollection
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Category", mappedBy="distributor")
 */
private $category;

public function __construct()
{
    $this->category = new ArrayCollection();
}

CategoryForm:

$builder
        ->add('parent', EntityType::class, [
            'class' => Category::class,
            'choice_label' => 'title',
            'multiple' => true,
            'required' => false,
            'attr' => [
                'class' => 'select2 form-control select2insidemodal js-example-matcher'
            ]
        ])
        ->add('title', TextType::class, [
            'label' => 'Title',
            'required' => true,
            'by_reference' => true
        ])
        ->add('distributor', EntityType::class, [
            'class' => Distributor::class,
            'choice_label' => 'name',
            'required' => false,
            'attr' => [
                'class' => 'select2 form-control select2insidemodal js-example-matcher'
            ]
        ]);

创建类别操作

public function createAction(Request $request)
    {
        $category = new Category();
        $categoryForm = $this->createForm(CategoryForm::class, $category);
        $categoryForm->handleRequest($request);


        if ($categoryForm->isSubmitted() && $categoryForm->isValid()) {
            $result = $this->categoryService->create($category);

        }

        return $this->render(
            '@app_bar/Category/categoryNew.twig',
            [
                'form' => $categoryForm->createView(),
            ]
        );
}

我得到的错误消息:

  

“AppBundle \ Entity \ Category”类型的预期参数,   给出了“Doctrine \ Common \ Collections \ ArrayCollection”

1 个答案:

答案 0 :(得分:2)

据我了解,parent不是一个集合,因此将parent multiple选项更改为false:

 ->add('parent', EntityType::class, [
        'class' => Category::class,
        'choice_label' => 'title',
        'multiple' => false,
        'required' => false,
        'attr' => [
            'class' => 'select2 form-control select2insidemodal js-example-matcher'
        ]
    ])