2015-04-23 64 views
1

在我的項目中,我可以將產品添加到購物車,我可以刪除它們。一切工作正常,但問題是,當我的購物車是空的,我得到一個錯誤,而不是顯示沒有購物車的模板。錯誤是:變量「產品」不存在於...。我怎樣才能繞過這個錯誤來顯示模板?當購物車是空的Symfony2錯誤

這是我的購物車的行動:

public function summaryAction() 
    { 

      $session = $this->getRequest()->getSession(); 
      $cart = $session->get('cart', array()); 
      // fetch the information using query and ids in the cart 
      if($cart != '') { 

       $em = $this->getDoctrine()->getEntityManager(); 
       foreach($cart as $id => $quantity) { 
          $productIds[] = $id; 

       } 
      if(isset($productIds)) 
       { 
        $em = $this->getDoctrine()->getEntityManager(); 
        $product = $em->getRepository('MpShopBundle:Product')->findById($productIds); 
       } else { 
        return $this->render('MpShopBundle:Frontend:product_summary.html.twig', array(
         'empty' => true, 
        )); 
       } 

       return $this->render('MpShopBundle:Frontend:product_summary.html.twig',  array(
      'product' => $product, 
        )); 
       } else { 
        return $this->render('MpShopBundle:Frontend:product_summary.html.twig',  array(
         'empty' => true, 
        )); 
       } 
      } 

這是我的模板:

{% if product %} /// error at this line 
       <tbody> 

      {% for key, item in cart %} 

       {% for item in product %} 
       <tr> 

        <td> <img width="60" src="{{ asset('bundles/mpFrontend/assets/products/4.jpg') }}" alt=""/></td> 

        <td>{{ item.model }}</td> 
        <td> 
        <div class="input-append"><input class="span1" style="max-width:34px" placeholder="1" id="appendedInputButtons" size="16" type="text"> 
        <button class="btn" type="button"><i class="icon-minus"></i></button> 
        <button class="btn" type="button"><i class="icon-plus"></i></button> 
        <button class="btn btn-danger" type="button"><a href="{{ path('cart_remove', {'id': key}) }}"><i class="icon-remove icon-white"></i></button> 
        </div> 
        </td> 

        <td>$120.00</td> 
        <td>$25.00</td> 
        <td>$15.00</td> 
        <td>$110.00</td> 
       </tr> 

       {% endfor %} 

{% endfor %} 
{% endif %} 

回答

2

有幾種方法檢查變量/對象存在:

{% if product is defined %} 

這將檢查您是否已將控制器中的變量產品分配給您的模板。

{% if product is not empty %} 

這將檢查如果你的產品有任何數據或者它只是null。請注意,您必須通過控制器傳遞變量。

你也可以像這樣將它們組合起來:

{% if product is defined and product is not empty %} 
{# Show something when product is available #}