[英]Patch manyToMany relation in Symfony via a React Application
在 Symfony4 項目中,我有一個實體Infrastructure ,它可以有很多Contacts 。 我在我的 React 應用程序中創建了一個功能,您可以在其中將現有聯系人添加到基礎架構。
以下是在我的 InfrastructureType 中配置聯系人的方式:
->add('contacts', CollectionType::class, array(
'entry_type' => ContactType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
))
這是 React 應用程序發送到 SF 應用程序的有效負載:
{"contacts":[
{
"id":3,
"firstname":"Maeva",
"lastname":"CAMGUILHEM",
"job":"Acheteuse Industrielle",
"email":"maeva.test@test.fr",
"phone":"03 00 00 00 00",
"mobilePhone":"NULL"
}
] }
當它到達我的控制器時,我正在嘗試通過這樣做來修補(僅更新聯系人)我的基礎設施:
public function patchInfrastructure(Request $request, Infrastructure $infrastructure): JsonResponse
{
$parameters = json_decode($request->get('appbundle_client_infrastructure'), true);
$form = $this->createForm(InfrastructureType::class, $infrastructure);
$form->submit($parameters, false);
if ($form->isSubmitted() && $form->isValid()) {
$this->em->persist($infrastructure);
$this->em->flush();
}
return $this->error(
500,
$this->getErrorMessagesAsArray($form)
);
}
如果我刪除聯系人,這有效,但當我添加現有聯系人時無效。 似乎 Symfony 無法識別 id 為 3 的聯系人並喜歡它。 相反,它會創建一個具有空值的新聯系人。
我試圖只傳遞 ID,這可能是一個好主意,但它告訴我表單無效。
如果有人可以幫忙,非常感謝
好的,我讓它工作了。
因此,如果您想知道如何在 Symfony 中修補 ManyToMany / oneToMany 關系並鏈接已經存在的實體,以“Api Rest”的方式,只需執行以下操作:
在 formType 中,我更改了我的聯系人屬性:
->add('contacts', EntityType::class, array(
'class' => Contact::class,
'choice_label' => function ($contact) {
return $contact->getName();
},
'multiple' => true,
'by_reference' => false,
))
使用 EntityType 而不是 CollectionType 可以解除這種情況,並允許您傳遞要鏈接的實體的 id 數組。
就我而言,我只需要發送:
appbundle_client_infrastructure: {"contacts":[3]}
到我的控制器,他自動將聯系人 ID 3 鏈接到我的實體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.