【问题标题】:Symfony 3 weird "choice" errorSymfony 3 奇怪的“选择”错误
【发布时间】:2017-06-14 11:21:02
【问题描述】:

我正在尝试在 Symfony 3 中构建一个复选框列表。 这段代码:

    $choices = [
        'a' => 'fsssssss',
    ];

    $builder->add('memberships', ChoiceType::class, [
        'choices' => $choices,
        'expanded' => true,
        'multiple' => false
    ]);

返回以下错误:Catchable Fatal Error: Object of class Doctrine\ORM\PersistentCollection could not be convert to string in vendor/symfony/symfony/src/Symfony/Component/Form/ChoiceList/ ArrayChoiceList.php(第 73 行)

如果我再添加两个选项,错误就会消失并正确显示该字段:

    $choices = [
        'a' => 'fsssssss',
        'd' => 'fsssssss',
        'g' => 'fsssssss',
    ];

    $builder->add('memberships', ChoiceType::class, [
        'choices' => $choices,
        'expanded' => true,
        'multiple' => false
    ]);

实际上,有很多组合有效,也有很多无效;我没有看到任何模式。

我做错了吗?我需要清除某种缓存吗?

【问题讨论】:

  • 尝试将其添加到'multiple'=>false下方:'choice_label' => function ($value, $key, $index) { return $key; },
  • 它没有帮助:(
  • fsssssss 是您选择的关键而不是价值,您需要更改它
  • 用什么改?有更好的弦吗? :)
  • 会员资格是与 orm 相关的对象吗?如果是这样,请使用 EntityType

标签: symfony symfony-forms


【解决方案1】:

只是为了结束这个问题:

如果您使用带有data_class 选项的表单并且表单字段表示应通过选项选择的实体的属性,您可以使用EntityType

    $builder->add('memberships', EntityType::class, [
        'class'     => MyClass::class,
        'choices'   => $choices,
        'expanded'  => true,
        'multiple'  => false
    ]);

【讨论】:

    猜你喜欢
    • 2011-10-12
    • 2019-03-10
    • 2012-09-27
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多