如何在Symfony 5中为与其他具有关系的实体以Symfony方式建立关系创建表单?

问题描述

大家好,在此先感谢您的帮助! 假设我有一个Symfony 5 应用,其实体如下: 英雄,职业,装甲群与装甲和武器群与武器。 它们之间的关系是这样的:

  • 唯一的英雄是一组职业,一个 Armor 和一个 武器
  • 单个独特的职业可以包含许多英雄,许多 ArmorGroups 和许多武器组
  • 单个唯一的 ArmorGroup 是许多 Armors
  • 的集合
  • 单个独特的武器组是许多武器
  • 的集合
  • 单个唯一的 Armor 位于一个 ArmorGroups 的集合中,专门用于一个 Professional
  • 单个独特的武器位于一个武器组的集合中,并且专门用于一个专业

这是一个图:

enter image description here

我想创建一个 HeroType 表单,以将 Armor 武器的选择限制为先前选择的 Profession 和将其显示为 EntityType 单选列表,其名称基于 Armor ArmorGroups WeaponGroups 的数据strong>武器。所有类都有许多唯一的参数。

这是我无法使用的方式:

<?php
class HeroType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder,array $options)
    {
        $builder
            ->add('name',NumberType::class,[
            'attr' => ['placeholder' => 'John Doe'],'label' => 'Hero name.','required' => true,])
            ->add('profession',EntityType::class,[
            'choice_label' => 'name','class' => Profession::class,'group_by' => 'affiliation','label' => 'Profession','multiple' => false,'required' => false,])
            ->add('item_armor',[
            'choice_label' => 'model','class' => ItemArmor::class,'group_by' => 'material','label' => 'Armor',])
            ->add('item_weapon','class' => ItemWeapon::class,'label' => 'Weapon',])
            ->add('save',SubmitType::class,['label' => 'Create Hero!']);
    }

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

它无法获取'choice_label''group_by'的属性。我想为英雄创建一个表单,该表单可从 ArmorGroups /武器组获取数据以用作标签,但值应为 Armor /武器 ID

更新: 这段代码正确并按预期呈现了表单:

<?php
class HeroType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder,[
            'choice_label' => function ($profession) {
                return $profession->getName();},'group_by' => function ($profession) {
                return $profession->getAffiliation();},[
            'choice_label' => function ($item_armor) {
                return $item_armor->getIdItemArmor()->getModel();},'group_by' => function ($item_armor) {
                return $item_armor->getIdItemArmor()->getMaterial();},[
            'choice_label' => function ($item_weapon) {
                return $item_weapon->getIdItemWeapon()->getModel();},'group_by' => function ($item_weapon) {
                return $item_weapon->getIdItemWeapon()->getMaterial();},''
        ]);
    }
}

但是现在我得到了错误:

在属性路径“专业”处给出的类型为“ App \ Entity \ Profession或null”,“ Doctrine \ Common \ Collections \ ArrayCollection实例”的预期参数。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...