首页 > 解决方案 > Symfony ArrayCollection

问题描述

我有 2 个实体: CategoryArticle具有以下关系:

问题

我想使用此表单添加新类别:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class)
        ->add('submit', SubmitType::class, [
            'label' => 'Add a new category'
        ])
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => Category::class,
    ]);
}

这是我在字段名称中输入字符串值时遇到的错误:

Name Error This value should be of type array|IteratorAggregate.

我从未ArrayCollection在 symfony 中使用过 / Relation,但我尝试将其更改TextType::classCollectionType::class它给了我一个白色方块,我无法输入任何内容。

在一个更通用的问题中:
如何验证表单中的值而不会出现错误:This value should be of type array|IteratorAggregate.

Category

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

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\Unique(message="Cette catégorie existe déjà")
 */
private $name;

/**
 * @return mixed
 */
public function getId()
{
    return $this->id;
}

/**
 * @return mixed
 */
public function getName()
{
    return $this->name;
}

/**
 * @param $name
 * @return Collection|null
 */
public function setName($name): ?Collection
{
    return $this->name = $name;
}


文章

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

/**
 * @ORM\Column(type="text")
 */
private $title;

/**
 * @ORM\Column(type="text")
 */
private $content;

/**
 * @ORM\Column(type="datetime")
 */
private $createdAt;

/**
 * @ORM\Column(type="string", nullable=true)
 */
private $image;

/**
 * @ORM\Column(type="datetime", nullable=true)
 */
private $editedAt;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Category")
 */
private $category;

标签: symfonyormarraycollection

解决方案


推荐阅读