Symfony选择类型数组:无法转换属性路径的值:必须是数组

uqdfh47h  于 2022-11-16  发布在  其他
关注(0)|答案(2)|浏览(159)

首先我是Symfony的新用户
实际上,我正在使用一些字段自定义表单EasyAdmin,但遇到了以下问题:
ChoiceField::new('villa')->setChoices($villasChoices)->allowMultipleChoices()
我得到这个错误是因为allowMultipleChoices()函数:
Unable to transform value for property path "villa": Expected an array.
我的字段实际上是集合类型,这就是为什么我有这个错误,有我的实体

#[ORM\OneToMany(mappedBy: 'Name', targetEntity: Villa::class)]
    private Collection $Villa;

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

    /**
     * @return Collection<int, Villa>
     */

    public function getVilla(): Collection
    {
        return $this->Villa;
    }

如何用数组替换集合类型?

x4shl7ld

x4shl7ld1#

尝试使用AssociationField而不是ChoiceFieldAssociationField自动列出实体,而ChoiceField手动传递数组。

->setFormTypeOption('multiple', true)

如果您的属性允许多个值(OneToMany、ManyToMany),则可用于多项选择

jtoj6r0c

jtoj6r0c2#

你必须有一个这样的表格:

$form = $this->createFormBuilder($yourEntity)
        ->add('villa', EntityType::class, [
            'class' => Villa::class
            'multiple' => true
        ])
    ;

使用EntityType::class设置'villa'项,并在选项'multiple'中设置=〉true。
在您的Villa实体中,您必须设定__tostring方法,如下所示:

public function __toString(): string
{
    return $this->name; //name is a string value
}

相关问题