1

我在 Codeigniter 中使用 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>
<? } ?>

如何查询购物车以查看该项目是否在其中并获取“rowid”以便我可以将其用于删除功能?

非常感谢!

4

2 回答 2

1

我有一个类似的问题 - 我通过使用 2 个新函数 - in_cart() 和 all_item_count() 扩展 CI_Cart 库来解决它。

<?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 */
于 2012-10-22T16:18:58.463 回答
0

如果作业名称或您想要检查的任何内容已经存在,您可以签入您的模型。如果存在则显示删除按钮,否则显示添加。

于 2012-10-22T16:09:51.470 回答