[英]How to set the choices of a Symfony EntityType form field after the form has been created and handled?
我正在使用Symfony 3.4
並想創建一個簡單的表單,該表單顯示一個列表實體,可以使用復選框選擇刪除:
問題是,“前 50 個實體”取決於實體是否已被刪除/表單已被處理。
choises
class SomeController
{
public function deleteUsersAction(Request $request)
{
$users = $this->loadUsersFromDB(50);
$form = $this->creatFormBuilder()
->add('users', EntityType::class, [
'class' => 'AppBundle:User',
'choices' => $users, // $users are added here
'multiple' => true,
'expanded' => true,
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$users = $form->getData();
$this->deleteUsers($user);
// Load the now first 50 users
$users = $this->loadUsersFromDB(50);
// How to add these users to the form??
}
return $this->render('AppBundle::user_list.html.twig', ['form' => $form->createView()]);
}
}
提交的用戶被刪除后,如何為表單設置正確的用戶?
為了回答評論中的問題,我提供了一個小例子:
$users = $this->loadUsersFromDB(5)
以獲得正確的結果,例如問題:
所以:在處理表單之前加載用戶列表是必要的工作,因為處理表單時列表會發生變化。
如何避免這項工作?
當然,在示例中加載 5 個用戶沒什么大不了的,但在實際代碼中,這可能是數百個沉重的實體,並且兩次運行相同的代碼可能會對性能產生重大影響。
我想你沒有理解我在評論中的建議,所以我會在這里更詳細地解釋/現在我也是用筆記本電腦寫的:)/
class SomeController {
public function deleteUsersAction(Request request) {
$users = $this->loadUsersFromDB(50);
$form = $this->creatFormBuilder()
->add('users', EntityType::class, [
'class' => 'AppBundle:User',
'choices' => $users, // $users are added here
'multiple' => true,
'expanded' => true,
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$users = $form->getData();
$this->deleteUsers($user);
// Load the now first 50 users
$users = $this->loadUsersFromDB(50); <-- you don't need this
// Q: How to add these users to the form??
// A: When you return a redirect response to the same page /you can also pass any query parameters if you had any filters and etc../
// This will ensure that the page is loaded properly with the new list of the users and Bob and Alice will NOT be in the list
// If you don't do it with a redirect and the user submits the form the browser remembers the data and if the users hits the refresh button of the browser it will resubmit the form and with your approach it may delete next 2 users /Mike and John/.
return $this->redirectToRoute('YOUR_ROUTE', $request->query->all());
}
return $this->render('AppBundle::user_list.html.twig', ['form' => $form->createView()]);
}
}```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.