Tuesday, January 25, 2022

[FIXED] CakePHP 3 : creating multidimensional cookie

Issue

I'm working in CakePHP 3.2 and building a shopping cart.

I'm using Cookie component to store the products in the cart.

This is what I'm doing to add products to the cart

public function addToCart()
    {
      $this->loadModel('Products');

      if ($this->request->is('post')) {
        $p_id = $this->request->data('product_id');
        $p_quantity = $this->request->data('qnty');

        $product = $this->Products->get($p_id);

        if (!$product) {
          throw new NotFoundException(__('Invalid Product'));
        }

          $this->Cookie->write('Cart',
            ['id' => $p_id, 'quantity' => $p_quantity]);

          $itemsCount = count($this->Cookie->read('Cart'));

          $this->Flash->success(__('Product added to cart'));
          return $this->redirect($this->referer());

      }
    }

How could I add multidimensional array in Cookie because Cart can have multiple products and each product carry multiple value. Also, How could I print in view of cart() method ?

This is how my cart() method is

public function cart()
    {
      $cart_products = $this->Cookie->read('Cart');

      $this->set('cart_products', $cart_products);
    }

and printing in view as

foreach($cart_products as $c_product):
  echo $c_product->id.' : '.$c_product->quantity;   // line 45
endforeach;

But this gives error as

Trying to get property of non-object [ROOT/plugins/ArgoSystems02/src/Template/Orders/cart.ctp, line 45]

Solution

You write array to cookie:

$this->Cookie->write('Cart', ['id' => $p_id, 'quantity' => $p_quantity]);

I believe what You want is to store all products in cookie:

$cart = $this->Cookie->read('Cart') ? $this->Cookie->read('Cart') : [];
$cart[] = $product;
$this->Cookie->write('Cart', $cart)


Answered By - Bogdan Kuštan

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.