Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple form include symfony (same page)

Tags:

php

symfony

I have a problem with multiple form symfony (include).

I have a multiple article in the same page, the user can add comment for each article. I would like to show the form add comment.

My problem is this : when I submit my comment adding form, Symfony does not save the information in the database (without error message).

I tried to add a class for to change the name of my form, but it's the same.

My form action in the controller (call by the twig view for each article)

public function formAction($post_id, Request $request) {
    $user = $this->getUser();
    $em = $this->getDoctrine()->getManager();
    $post = $em->getRepository('AppBundle:Post')->find($post_id);

    $comment = new Comment();
    $comment -> setPost($post);
    $comment -> setAuthor($user);

    $form_comment = $this->createForm(CommentType::class, $comment);

    $form_comment->handleRequest($request);
    if ($form_comment->isSubmitted()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($comment);
        $em->flush();

        $request->getSession()->getFlashBag()->add('msg_success', 'Votre contribution a bien été ajoutée');

    }

    return $this->render('account/form-comment.html.twig', array(
      'form_comment' => $form_comment->createView(),
      'post_id' => $post_id
    ));

}

Get Name in the Form Type (for unique id)

public function getName() {
    return self::NAME . '_' . uniqid();
}
like image 458
Benjamin Avatar asked Nov 09 '22 23:11

Benjamin


1 Answers

If I'm not mistaken, the problem comes from the getName() method with uniqid().
The name in your controller is not the same as your twig so your form is not valid.

I suppose you want to change the name of the form to have different ids in your view, if that is the case, you can put an id in your form like this:

{{ form_start(form_comment, {'attr': {'id' : uniqvalue}}) }}

with uniqvalue which may be a counter

like image 92
doydoy44 Avatar answered Nov 14 '22 21:11

doydoy44