Steinbock
Steinbock

Reputation: 868

Symfony2 OneToMany Relation - get object via hidden form field?

I'm currently developing a small website in Symfony where visitors can comment on hummanitarian projects. A project can have many comments (oneToMany relation).

On the Project show.html.twig page I'm rendering the Comment new form.

{{ render(controller('DbeDonaciBundle:Comment:new')) }}

Now if someone creates a comment I need to asign the current displayed project. The project is displayed via a route:

dbe_project_show:
pattern:  /{id}/{name}/show
defaults: { _controller: "DbeDonaciBundle:Project:showProjectWithDetails" }

Here is the create Controller for the comments:

 public function createAction(Request $request)
    {
        $entity = new Comment();


        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);


        if ($form->isValid()) {
            // get current user
            $entity->setUser($this->get('security.context')->getToken()->getUser());

            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('dbe_comment_show', array('id' => $entity->getId())));
        }

        return $this->render('DbeDonaciBundle:Comment:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

I know there are two options:

  1. Add a hidden field containing project id to your form.
  2. Have your project id in route (and therefor as action parameter too).

But I'm still struggeling to get the project object to asign it to the comment. How would option 1 work? How do I get the current project into the hidden field form?

Thanks already!

Upvotes: 0

Views: 490

Answers (1)

Turdaliev Nursultan
Turdaliev Nursultan

Reputation: 2576

Try this one:

{{ render(controller('DbeDonaciBundle:Comment:new',{'id': app.request.get('id')})) }}

In your form template add:

<input type="hidden" name="id" value="{{ id }}"/>

Upvotes: 1

Related Questions