0
votes

Just solved one issue here, now another...

As mentioned before, I'm following this tutorial to create a simple shopping cart using CakePHP, Ajax and Bootstrap.

I've got it working for the most part except it appears though that the items added to the cart aren't saved. I can add an item, move around the website and even change it's quantity and it remains as is - however, when I try to add another item - the second item just completely overwrites the first item.

This is the CakePHP Cart Model function that runs when adding an item:

public function addProduct($productId) {
        $allProducts = $this->read();
        if (null!=$allProducts) {
            if (array_key_exists($productId, $allProducts)) {
                $allProducts[$productId]++;
            } else {
                $allProducts[$productId] = 1;
            }
        } else {
            $allProducts[$productId] = 1;
        }

        $this->saveProduct($allProducts);
    }


public function saveProduct($data) {
        return CakeSession::write('cart',$data);
}

That's called by the add Function in the Controller:

 public function add() {
        $this->autoRender = false;
        if ($this->request->is('post')) {
            $this->Cart->addProduct($this->request->data['Cart']['product_id']);
        }
        echo $this->Cart->getCount();
    }

My Cart Model looks like this at the start:

<?php
App::uses('AppModel', 'Model');
App::uses('CakeSession', 'Model/Datasource');

class Cart extends AppModel {....}
1
what's $this->read()?Ross
any reason why you are using CakeSession instead of Session Component?Nunser
Looks like a logic error. Unless you've redefined $this->read() - when you call it you'll get the data for one item returned. You then overwrite the session data with that one item's data. @Nunser there's no session component in a model; there is a static session interface anywhere though.AD7six
To be honest, I'm still learning so I'm not sure what it exactly does... It's straight off the tutorial here and it says it works for them! @AD7six - how would I redefine it to read them all instead of just one?Chronix3
I solved it! It was a typo on the tutorial. It should've been readProduct() not just read(), since later on there is this function: public function readProduct() {return CakeSession::read('cart');}Chronix3

1 Answers

0
votes

Solved: There is a typo in the tutorial, it should be readProduct() not read() at the start of the addProduct function.