Reputation: 18757
I am working on a simple form in Symfony 3.4
which allows to select any number of entities in a form for deletion.
What is the best / correct way to ask the user to confirm the deletion without using JS?
class SomeController {
public function deleteUsersAction(Request request) {
$users = $this->loadUsersFromDB();
$form = $this->creatFormBuilder()
->add('users', EntityType::class, [
'class' => 'AppBundle:User',
'choices' => $users,
'multiple' => true,
'expanded' => true,
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$users = $form->getData();
// Add confirmation here...
$this->deleteUsers($user);
}
return $this->render('AppBundle::user_list.html.twig', ['form' => $form->createView()]);
}
}
Of course I could use some JS (or other script code) which intercepts the form submission, shows a confirmation dialog and only then submits the data to the controller which handles the form and the deletion.
However, this is not the solution I am looking for. The submitted entities / users have to be check first, if deletion is even possible. So, controller should check the entities and then send the user to a confirmation page.
How to pass the selected entities to the confirmation page and then finally to the controller which handles deletion?
My first intention was to create a form for the confirmation page which could hold input hidden
fields for the selected entities. However hidden
fields cannot store entities (or can they) and I would have create a custom form type which handles the transformation (entity to id -> id to entity) or to do the transformation manually within the controller.
The second guess was to use EntityType
as before but simply hide the form fields using CSS. However these seems not be a clean solution.
I found some older posts form Symfony 2 which propose to use custom form types. Is this still the best option in Symfony 3?
Upvotes: 0
Views: 86
Reputation: 1082
I suggest you to have a separate path for delete and for delete confirmation (Single responsability). Then, from the delete path, you pass the list of ids of the entities that have to be deleted to the delete confirmation path. Check this question for more details : How to pass data/information between different forms on diffrent pages in Symfony 3?
Upvotes: 0
Reputation: 12384
Create an array of removed user IDs (or names, whatever)
if ($form->isSubmitted() && $form->isValid()) {
$users = $form->getData();
// create an empty array
$removed = [];
foreach($users as $user) { // I assume you do this here?
// Add confirmation here...
$removed[] = $user->getId(); // add to array (or whatever, username, etc)
$this->deleteUsers($user);
}
// now pass to your view
return $this->render('AppBundle::user_list.html.twig', [
'form' => $form->createView(),
'removed' => $removed,
]);
}
Then you can create an alert box or some other div with the information you wish to display.
Hope this helps! :-)
Upvotes: 1