【问题标题】:Codeigniter Cart - Check if item added to cartCodeigniter 购物车 - 检查商品是否已添加到购物车
【发布时间】:2012-10-22 15:31:08
【问题描述】:

我在 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”以便我可以将其用于删除功能?

非常感谢!

【问题讨论】:

    标签: codeigniter


    【解决方案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 */
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-14
        • 2011-04-09
        • 1970-01-01
        • 2015-03-28
        • 2017-05-06
        • 1970-01-01
        • 2016-12-19
        相关资源
        最近更新 更多