购物车为空时出现Symfony2错误

时间:2015-04-23 13:36:37

标签: php symfony session

在我的项目中,我可以将产品添加到购物车中,我可以删除它们。一切正常,但问题是,当我的购物车是空的时,我收到一个错误,而不是只显示没有购物车的模板。错误是:变量"产品"在...中不存在。如何绕过此错误以显示模板?

这是我的购物车行动:

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 %}

1 个答案:

答案 0 :(得分: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 #}