【发布时间】:2020-06-11 14:56:36
【问题描述】:
我偶然发现了一个奇怪的行为,我仍然不确定我的解决方案是否是最合适的,即使它现在有效。
我有 2 个实体:
class Recipe
{
/** [...] */
public $id;
/** @ORM\Column(type="string", length=255) */
public $name;
/** @ORM\ManyToOne(targetEntity="App\Entity\Location") */
public $location;
}
class Location
{
/** [...] */
public $id;
/** @ORM\Column(type="string", length=255) */
public $name;
/** @ORM\OneToMany(targetEntity="App\Entity\Recipe", mappedBy="location") */
protected $recipes;
}
这里没什么特别的。一个位置可以保存多个配方,一个配方最多可以在一个位置。
配方表单构建如下:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add(
'name',
TextType::class,
['label' => 'Name',]
)
->add(
'location',
EntityType::class,
[
'label' => 'Location',
'class' => \App\Entity\Location::class,
'choice_value' => function ($location) {
// Why is this code necessary?
return is_object($location)
? $location->getId() // Object passed (when building choices)
: $location; // int value passed (when checking for selection)
},
'choice_label' => 'name',
]
)
;
}
然后控制器创建表单等等。
/**
* @ParamConverter("entity", class="App:Recipe", isOptional="true")
*/
public function edit(Request $request, object $entity = null) {
$form = $this->createForm(\App\Form\Recipe::class, $entity ?? new Recipe());
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// ...
}
// ...
}
我的原始实现在EntityType 表单元素上没有上面的choice_value 回调,并且当我打开现有位置时从未选择过该选项。但除此之外,一切都按预期工作,选择一个值确实将其正确保存在数据库中,无需更多代码,但 Symfony 的魔力。
你能告诉我为什么这里需要choice_value吗?我错过了什么?
为什么作为参数传递的值有时是对象,有时是整数?
【问题讨论】: