gpt4 book ai didi

php - Symfony 2,实体上带有 ChoiceType 的 createFormBuilder,choice_label 是 int

转载 作者:搜寻专家 更新时间:2023-10-31 21:02:28 27 4
gpt4 key购买 nike

我对 Symfony 2 和表单生成器有点小问题。我想根据 Doctrine findAll 结果创建一个 ChoiceType 字段。

我的选择是实体数组,但在 choice_label 函数上,第一个变量是 int !

我放了一些代码来解释:

    $categories = $categoryRepository->findAll();

foreach ($categories as $value) {
echo "category name : ".$value->getName()."<br/>";
}
/* Result :
category name : First
category name : Second
*/

$form = $this->createFormBuilder($dance)
->add('name', TextType::class, array('label' => 'Nom de la dance'))
->add('description', TextareaType::class, array('label' => 'Description'))
->add('creationDate', DateTimeType::class, array('label' => 'Date de création'))
->add('category', ChoiceType::class, [
'choices' => $categories,
'choice_label' => function($category, $key, $index) {
var_dump($category);
// Result : int(0)
return $category->getName();
// Exception !
},
'choice_attr' => function($category, $key, $index) {
return ['class' => $category->getId()];
},
])
->add('save', SubmitType::class, array('label' => 'Sauvegarder'))
->getForm();

当然,我有一个 fatal error :调用整数上的成员函数 getName() ...

有人可以帮我解决这个问题吗?

谢谢!

最佳答案

如果您使用的是比 Symfony 2.7 更旧的版本,您不能简单地将一个对象数组传递给 choices 选项。这仅在 Symfony >=2.7 中受支持。如果你想在 Symfony 2.7 或 2.8 中这样做,你必须激活 choices_as_values option :

'choices_as_values' => true

默认情况下,在 Symfony 2.x 中 choices 是相反构建的:the keys of the array become the value and the value of they array becomes the label .因此,数组中的第一个元素将为 0。 :)

或者,您可能想使用 EntityType class而不是 ChoiceType。在任何情况下,它都会将实际对象传递给函数。

此外,如果你想指定你的实体(或引用实体)的属性作为你的标签,你也可以使用property paths :

'choice_label' => 'name'

关于php - Symfony 2,实体上带有 ChoiceType 的 createFormBuilder,choice_label 是 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39377545/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com