Tomislav Mladenovski
Tomislav Mladenovski

Reputation: 35

How to - Symfony 2 Perform CRUD without passing ID to url

After long time of lerking on these boards I have finally decided to make my first post. I have recently started to play around with Symfony (2.4, don't yell at me please :) ). Using doctrine's terminal commands I generated CRUD events. Now, that is great and all, except that you have to pass the ID in the url, for example: www.mydomain.com/account/16/. This will pre-fill the form with the data from a row that has id 16 in mysql. My question is, how do I manipulate the pre-made CRUD (only interested in the update) so that I don't have to pass the id to the url, but rather, it renders the form based on the id the logged in user has associated with their account?

Here is my code:

class AccountController extends Controller
{
/**
 * Displays a form to edit an existing Event entity.
 * @Route("/account/{id}", name="post_login_account_edit")
 * @PreAuthorize("isFullyAuthenticated()")
 */
public function editAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('UserBundle:User')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Event entity.');
    }

    $editForm = $this->createEditForm($entity);

    return $this->render('UserBundle:Account:account.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView()
    ));
}

/**
 * Creates a form to edit a Event entity.
 *
 * @param User $entity The entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createEditForm(User $entity)
{
    $form = $this->createForm(new UserType(), $entity, array(
        'action' => $this->generateUrl('post_login_account_update', array('id' => $entity->getId())),
        'method' => 'PUT',
    ));

    $form->add('submit', 'submit', array('label' => 'Update'));

    return $form;
}
/**
 * Edits an existing User entity.
 * @Route("/account/{id}/update", name="post_login_account_update")
 * @PreAuthorize("isFullyAuthenticated()")
 */
public function updateAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('UserBundle:User')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Event entity.');
    }

    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);

    if ($editForm->isValid()) {
        $em->flush();

        return $this->redirect($this->generateUrl('post_login_account'));
    }

    return $this->render('UserBundle:Account:account.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView()
    ));
}

}

Upvotes: 1

Views: 421

Answers (1)

malcolm
malcolm

Reputation: 5542

Simply get logged in user in controller:

$entity = $this->get('security.context')->getToken()->getUser();

Upvotes: 1

Related Questions