Page 1 of 1

Using the number of items in the cart in header.tpl

Posted: Wed May 12, 2010 2:48 am
by veganista
Hello Folks,

Im developing a site for a client and its the first time i've tried to work with opencart so im not 100% sure about the best way to do things, i could do with some advice.

I have added the following code to the header controller in controllers/common/header.php

Code: Select all

        if (isset($this->session->data['cart']) && !empty($this->session->data['cart'])) {
            $this->data['cart_count'] = array_sum($this->session->data['cart']);
        }else{
            $this->data['cart_count'] = 0;
        }
 
So this has the affect of lettign me use $cart_count in my header template.

Is the correct way to go about modifying opencart? It doesn't seem like its very upgrade proof.

Thanks

Re: Using the number of items in the cart in header.tpl

Posted: Wed May 12, 2010 5:50 am
by johnnyart
There is already a written function in the cart library (system/library) that returns that value.

You can store it on your own variable, remember that to access it from the view file (.tpl) you need to type directly the variable name, in this case 'yourvar' instead of the data array:

Code: Select all

$this->data['yourVar'] = $this->cart->countProducts(); 
then you can print the value like this:

Code: Select all

echo $yourVar; 
Of course you already knew that part, but I cant be bothered deleting it :)
Hope it helps

Re: Using the number of items in the cart in header.tpl

Posted: Wed May 12, 2010 7:49 am
by Qphoria
Actually you're both right.. partially

Instead of $data you do need $this->data

And you don't really need an if/else because the $this->cart->countProducts(); will return a valid response either way
So simply

Code: Select all

$this->data['cart_count'] = $this->cart->countProducts(); 

Re: Using the number of items in the cart in header.tpl

Posted: Wed May 12, 2010 4:56 pm
by johnnyart
Oh sorry, It was a typo. Corrected now.
Thanks Q