dqa35710 2016-10-26 15:30 采纳率: 0%
浏览 38
已采纳

Symfony表单,将ManyToMany关系显示为复选框列表而不是选择

I want to show a ManyToMany relation in an entity as a list of checkboxes in a form instead of a select with the multiple selection.

In my entity I have this:

/**
 * @var ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="Language")
 * @ORM\JoinTable(name="courses_languages",
 *      joinColumns={@ORM\JoinColumn(name="course_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="language_id", referencedColumnName="id")}
 *      )
 */
private $languages = [];

And in my FormType for this entity I have this:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('languages', ChoiceType::class, [
            'multiple' => true,
            'expanded' => true
        ])
    ;
}

But when setting multiple and expanded to true I receive this error:

Unable to transform value for property path "languages": Expected an array.

I've investigated and it is in Symfony\Component\Form\Extension\Core\DataTransformer\ChoicesToValuesTransfomer in function transform

public function transform($array)
{
    if (null === $array) {
        return array();
    }

    if (!is_array($array)) {
        throw new TransformationFailedException('Expected an array.');
    }

    return $this->choiceList->getValuesForChoices($array);
}

The type of the array is Doctrine\ORM\PersistentCollection so it fails in checking is_array.

How could I fix this? Thank you

  • 写回答

1条回答 默认 最新

  • doutang7383 2016-10-26 15:42
    关注

    Change ChoiceType by EntityType (setting class option) or simply leave it null, Doctrine is able to guess the type (EntityType in this case) from your mapped property:

    $builder
        ->add('languages', null, [
            'multiple' => true,
            'expanded' => true
        ]);
    

    In a nutshell, the problem is that ChoiceType is designed to work with array of elements whilst EntityType with array and Doctrine\Common\Collections\Collection as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 视频编码 十六进制问题
  • ¥15 Xsheii7我安装这个文件的时候跳出来另一个文件已锁定文件的无一部分进程无法访问。这个该怎么解决
  • ¥15 unity terrain打包后地形错位,跟建筑不在同一个位置,怎么办
  • ¥15 FileNotFoundError 解决方案
  • ¥15 uniapp实现如下图的图表功能
  • ¥15 u-subsection如何修改相邻两个节点样式
  • ¥30 vs2010开发 WFP(windows filtering platform)
  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊
  • ¥15 求多普勒频移瞬时表达式