2014-10-31 24 views
1

我是Symfony的新手,希望儘早使用最佳做法。我的代碼下面的作品,但它感覺有點骯髒。Symfony 2.5&twig:如何清理這段代碼?

我擔心,如果我在這裏寫的代碼太多。也許我想念一些我還不知道的Symfony-background-magic。下面的細節。

你會改變什麼(爲什麼)?我感謝每一個建議,成爲一個更好的開發者。提前致謝!

的routing.yml

items_edit: 
    path:  /items/edit/{id} 
    defaults: { _controller: myBundle:items:edit, id: null } # null = if not set? 
    requirements: 
    id: \d+ 

ItemController.php

我一定要通過$item或者是其他的數據無論如何gettable通過樹枝?

public function editAction($id, Request $request) { 
    $em = $this->getDoctrine()->getManager(); 
    $repo = $em->getRepository('ItemsRepo'); 
    $item = $repo->find($id); 
    $form = $this->createForm(new ItemFormType(), $item); 

    if ($request->isMethod('POST')) { 
     $form->handleRequest($request); 
     if ($form->isValid()) { 
      $em->persist($item); 
      $em->flush(); 

      $this->get('session')->getFlashBag()->add('info', 'saved.'); 
      return $this->redirect($this->generateUrl('items_list')); 
     } 
    } 

    return $this->render('edit.html.twig', array(
     'form' => $form->createView(), 
     'item' => $item // !!! 
    )); 
} 

edit.html.twig

我必須補充{id: item.id}這裏?

{% block content %} 
    <form action="{{ path('items_edit', {id: item.id}) }}" method="POST" {{ form_enctype(form) }}> 
     {# ... custom stuff ... #}  
    {{ form_end(form) }} 
{% endblock %} 
+1

http://codereview.stackexchange.com/ – FoxMcCloud 2014-10-31 18:33:59

+0

@ChaseC很好,謝謝! – 2014-10-31 18:36:19

+1

@ Mr.B。什麼是'parentId'? – xurshid29 2014-10-31 19:20:41

回答

1

id: null在你的路線\d+的要求也沒用,因爲你實際上編輯現有的實體,你最好將其刪除; $em->persist($item);也是不必要的,因爲你已經在創建時保存並刷新了它,這次你不需要再次保存,只需刷新它即可。通過$item形成什麼,如果你想向用戶顯示一些信息,如「編輯帶有SOME_TITLE標題的項目」,或者如果有一些圖像字段想要顯示縮略圖..,你可以通過它和retreive字段值,它是u到你..補充說明,/items/edit/{id}是不是很漂亮,平時它就像/items/{id}/edit/items/{id}/delete做...