I am working on the back office of a restaurant website. When I add a dish, I can add the ingredients in two ways.
In my form template, I manually added a text input field. I have applied the jQuery UI autocomplete method in this field, which allows you to:
- Select existing components (previously added)
- Add ingredients
However, when I submit the form, each ingredient is inserted into the database (normal behavior that you tell me). For ingredients that do not exist, this is good, but I do not want to reinsert the ingredients that are already inserted.
Then I thought of Doctrine events like prePersist() . But I do not see how to proceed further. I would like to know if you have any idea how to do this.
Here is the buildForm method of my DishType :
<?php public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('category', 'entity', array('class' => 'PrototypeAdminBundle:DishCategory', 'property' => 'name', 'multiple' => false )) ->add('title', 'text') ->add('description', 'textarea') ->add('price', 'text') ->add('ingredients', 'collection', array('type' => new IngredientType(), 'allow_add' => true, 'allow_delete' => true, )) ->add('image', new ImageType(), array( 'label' => false ) ); }
and the method in my controller where I process the form:
<?php public function addDishAction() { $dish = new Dish(); $form = $this->createForm(new DishType, $dish); $request = $this->get('request'); if ($request->getMethod() == 'POST') { $form->bind($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($dish); $em->flush(); return $this->redirect($this->generateUrl('prototype_admin_get_dish', array('slug' => $dish->getSlug()))); } } return $this->render('PrototypeAdminBundle:Admin:addDish.html.twig', array( 'form' => $form->createView(), )); }
duplicates symfony many-to-many
Adrien g
source share