DEV Community


Discussion on: Removing Products from the Cart | Building a Shopping Cart with Symfony

qferrer profile image
Quentin Ferrer Author

Hello Isabelle. Let me explain how does cart clearing work:

  1. When the user click on the clear button, the form is submitted and the CartController::index() method is invoked thanks to the Symfony routing.
  2. We get the current cart, using the CartManager manager:
    • If the cart is already associated with the user in the session, we use it,
    • If the cart does not exist in the session, a new cart is created using the CartFactory factory and becomes the current cart. Note that it will be associated with the user in the session after being persisted in the database (see CartManager::save() method).
  3. The current cart is binded to the form using the FormFactory factory and then the submitted data are merged into the Order object thanks to the Form::handleRequest() method. Next, the form triggers a post submit event to let you manipulate the form data, the current cart in this case.
  4. As we have registered a ClearCartListener listener to the Cart Form, the ClearCartListener::postSubmit() method is invoked. So, we clear the cart using the form data (the current cart by reference) if the clear button has been clicked.
  5. At this time, the cart is not yet saved in the database so let's go back to the controller. If the form is submitted and valid, we save the cart modifications using the CartManager::save() method.
  6. Finally, we redirect the user to the cart page.

Let me know if you need more information.

Have a good day.

Thread Thread
isabellebengrine profile image
Isabelle Bengrine • Edited

Thanks for this reply! of course, I realized later that the persist and flush parts are in the save method of the cartmanager! this was silly of me to ask about that... now if you are curious, I finally found what was preventing the remove and clear buttons to work properly: (oddly this did not prevent your project from working just fine, whereas mine could not): in the twig file we had : form_end(form, {'render_rest': false})
and I found on stackoverflow some comments about a similar issue to mine that said:
"But to submit it separately you must ensure that you're building the "complete" child form in your view" and looking at the forms, I thought we are displaying all the fields anyway, so why do we need this? so I removed the ", {'render_rest': false}" part and now it works!!!
I still do not quite understand why I had some trouble and you did not but this just shows I have so much to learn!!! anyway, again thanks for your help and your patience!!! I love your tutorials!!!