course when you register on learnphalcon
The examples on this site are currently tested to work on Phalcon V3.4 and Phalcon Devtools V3.2 Some issues may arise when using later versions.

Please get in touch or post a comment below the post if you encounter a problem.

The cart is now working well and the cart contents are stored in a session so even if the user leaves the page the information will not be lost. When we created the page in step 1 we included a div called 'cart' which would indicate the number of items in the cart this was hard coded to 0. Now that we have a session we can change this to show the number of items from the session.

To do this first edit the file /app/views/product/displayGrid.phtml. Locate the div with id='cart' at the top of the page. Replace the 0 inside the div tags with the following.

<?php echo $totalItems;?>

$totalItems is a view variable which we need to set in the action which corresponds to this view in the Product Controller. Edit the file /app/controllers/ProductController.php and locate the displayGridAction() function. Replace the one you created earlier with the following code.

public function displayGridAction()
	if ($this->session->has('cart')) {
		$cart = $this->session->get('cart');
		foreach ($cart as $product => $qty) {
			$totalQty = $totalQty + $qty;
	else {
	$this->view->products = Product::find();

This function needs to check the number of items in the cart (if there are any) and set the view variable appropriately. It then loads all the products from the database into a view variable called products before rendering the view.

Now, even if the user's browser crashes and they have to restart their browser the number of items in their cart will be reloaded from the session.

Clearing the cart is relatively straightforward. You just need a function in the controller which will remove the 'cart' session variable from the session. Edit the /app/controllers/ProductController.php file and add the following function.

public function emptyCartAction()
Now to enable the Empty Cart button on the navbar add the following jquery function below the addItem function inside the script tags at the bottom of the file /app/views/product/displayGrid.phtml
$("#emptyCart").click(function() {
	  type: "get",
	  url: "<?php echo $this->url->getBaseUri()?>" + "product/emptyCart",
	  success: function() {
	  error: function() {
		  alert("problem communicating with the server");

Next we need to think about how to handle the checkout process.