Adam
Adam

Reputation: 1475

Codeigniter Cart - Check if item added to cart

I'm using the Cart class in Codeigniter. What I want to do should (hopefully!) be simple... but i'm struggling.

On the product page, I have a button to 'add to cart'. What I want to happen is that when the item is already in the cart, the button changes to 'remove from cart'.

<? //if(**not in cart**) { ?>
    <a href="<?=base_url()?>jobs/addjob/<?=$row->id?>">Add to cart</a>
<? } else { ?>
    <a href="<?=base_url()?>jobs/removejob/<? /**cart 'rowid'**/ echo $rowid?>">Remove from cart</a>
<? } ?>

How can I query the cart to see if that item is in there or not and get the 'rowid' so I can use that for a remove function?

Many thanks!

Upvotes: 1

Views: 6107

Answers (2)

RayZor
RayZor

Reputation: 665

I had a similar problem - I got round it by extending the CI_Cart library with 2 new functions - in_cart() and all_item_count().

<?php
class MY_Cart extends CI_Cart {

    function __construct() 
        {
            parent::__construct();
            $this->product_name_rules = '\d\D';
        }

/*
 * Returns data for products in cart
 * 
 * @param integer $product_id used to fetch only the quantity of a specific product
 * @return array|integer $in_cart an array in the form (id => quantity, ....) OR quantity if $product_id is set
 */
public function in_cart($product_id = null) {
    if ($this->total_items() > 0)
    {
        $in_cart = array();
        // Fetch data for all products in cart
        foreach ($this->contents() AS $item)
        {
            $in_cart[$item['id']] = $item['qty'];
        }
        if ($product_id)
        {
            if (array_key_exists($product_id, $in_cart))
            {
                return $in_cart[$product_id];
            }
            return null;
        }
        else
        {
            return $in_cart;
        }
    }
    return null;    
}

public function all_item_count()
{
    $total = 0;

    if ($this->total_items() > 0)
    {
        foreach ($this->contents() AS $item)
        {
            $total = $item['qty'] + $total;
        }
    }

    return $total;
}
 }
 /* End of file: MY_Cart.php */
 /* Location: ./application/libraries/MY_Cart.php */

Upvotes: 1

user1607528
user1607528

Reputation:

You could check in your model if the job name or whatever you would like to check already exists. If it exists display delete button else show add.

Upvotes: 0

Related Questions