2016-05-22 58 views
0

經過很長時間的這些板子上的行事之後,我終於決定做我的第一篇文章。我最近開始玩Symfony(2.4,請不要吼我:))。使用原則的終端命令,我生成了CRUD事件。現在,這是偉大的,除了你必須在URL中傳遞ID,例如:www.mydomain.com/account/16/。這將使用來自mysql中id爲16的行的數據預填充表單。我的問題是,如何操作預先創建的CRUD(僅對更新感興趣),以便我不必將id傳遞給url,而是根據登錄用戶的id呈現表單與他們的賬戶有關聯?如何 - Symfony 2執行CRUD而不將ID傳遞給url

這裏是我的代碼:

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

}

+0

更改路由地址別的東西(沒有ID PARAM)'* @路由(「/ account」'。從函數聲明中刪除$ id,因爲你將不再從路由'public function editAction()'中獲取它。改變行$ entity = $ em-> getRepository('UserBundle :User') - > find($ id);'to'$ entity = $ this-> getUser();'獲取當前登錄的用戶,而不是某個用戶,編號爲 – JimL

+0

工作!謝謝! –

+0

希望它至少能讓你有所感覺 – JimL

回答

1

簡單地得到登陸用戶控制器:

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

謝謝你這麼快評論。我做了你推薦的改變,並且我得到了一個沒有任何內容的空白頁面。調試器顯示沒有錯誤。 –