如何 - Symfony 2执行CRUD而不将ID传递给url

时间:2016-05-22 20:13:04

标签: php symfony

经过长时间的努力,我终于决定发表我的第一篇文章了。我最近开始玩Symfony(2.4,请不要对我大喊:))。使用doctrine的终端命令,我生成了CRUD事件。现在,这很好,除了你必须在网址中传递ID,例如:www.mydomain.com/account/16/。这将使用mysql中id为16的行中的数据预先填充表单。我的问题是,如何操作预制的CRUD(只对更新感兴趣),这样我就不必将id传递给url,而是根据登录用户的id呈现表单与他们的帐户相关联吗?

这是我的代码:

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()
    ));
}

}

1 个答案:

答案 0 :(得分:1)

只需登录控制器中的用户:

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