2012-10-22 143 views
1

我在Codeigniter中使用购物车类。我想做的事情应该(希望!)简单......但我很挣扎。Codeigniter购物车 - 检查商品是否已添加到购物车

在产品页面上,我有一个“添加到购物车”的按钮。我想要发生的事情是,当物品已经在购物车中时,该按钮变为“从购物车中移除”。

<? //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”这样我就可以使用了删除功能?

非常感谢!

回答

1

我有一个类似的问题 - 我通过扩展CI_Cart库和2个新函数in_cart()和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 */ 
+0

完美。谢谢! – Adam

0

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

相关问题