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.

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

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择