[英]Symfony sonata EntityType edit form - select - get other that current
[英]Symfony Form EntityType doesn't select the current value on render by default
我偶然發現了一個奇怪的行為,我仍然不確定我的解決方案是否是最合適的,即使它現在有效。
我有 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',
]
)
;
}
然后 controller 創建表單等等。
/**
* @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
嗎? 我錯過了什么? 為什么作為參數傳遞的值有時是 object,有時是 integer?
我不知道這是不是問題的原因,但是對於EntityType
字段,您不需要手動設置choice_value
。
來自Symfony 文檔:
在 EntityType 中,默認情況下會覆蓋它以使用 id。 使用id時,Doctrine只查詢實際提交id的對象。
通常沒有必要.. 也許是因為實體之間的關系是單向的?
有效的例子:
在實體層面
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Level", inversedBy="steps")
*/
private $level;
在實體步驟
/**
* @ORM\OneToMany(targetEntity="App\Entity\Step", mappedBy="level")
*/
private $steps;
然后是步驟類型:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('level', EntityType::class, [
'label' => 'Related level',
'class' => Level::class,
'choice_label' => 'position'
])
;
}
哦……找到了。 實際上,我有一個與該字段相關聯的舊DataTransformer
,它弄亂了這些值。 反正我不再需要它了,所以只是將它移除就神奇地修復了這個錯誤。
無論如何,感謝您的幫助,它確實證實了某些事情是不對的,並迫使我進行更深入的研究。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.