Reputation: 1231
In my project I can add products to the shopping cart and I can remove them. Everything works fine, however the problem is that when my cart is empty I am getting an error instead of just displaying the template without the cart. THe error is: Variable "product" does not exist in.... How can I bypass this error to show the template?
This is my shopping cart action:
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,
));
}
}
This is my template:
{% 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 %}
Upvotes: 1
Views: 128
Reputation: 3762
There are several ways to check for variable/object presence:
{% if product is defined %}
This will check if you've assigned the variable product from your controller to your template.
{% if product is not empty %}
This will check if your product has any data in it or it's simply null
. Beware that you must pass variable from the controller.
You can also combine them like this:
{% if product is defined and product is not empty %}
{# Show something when product is available #}
Upvotes: 2