Codeigniter Cart - Check if item added to cart - codeigniter

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**) { ?>
Add to cart
<? } else { ?>
Remove from cart
<? } ?>
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!

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 */

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.

Related

MAGENTO - Load last created Product to Cart

is it possible to load the last registered (created) Product in my Cart?
How?
I know it sounds crazy but i need this for one of my project.
I think this is the part where the Product gets loaded:
cartcontroller.php
/**
* Initialize product instance from request data
*
* #return Mage_Catalog_Model_Product || false
*/
protected function _initProduct()
{
$productId = (int) $this->getRequest()->getParam('product');
if ($productId) {
$product = Mage::getSingelton('checkout/session')->getQuote()->getAllItems()
->setStoreId(Mage::app()->getStore()->getId())
->load($productId);
if ($product->getId()) {
return $product;
}
}
return false;
}
This (if I´m right) i need to be replaced with the last in shop created Product - sound weired but i need this....
You're almost there - try this code:
$collection = Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection();
$collection->getSelect()->order('created_at DESC');
$latestItem = $collection->getLastItem();
Note that when you get the latest quote item, you're not actually obtaining the product. To get the actual product, you would need to add this line:
$product = $latestItem->getProduct();
You can get the items in the cart like this:
$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
Then loop through the items and see which one has the biggest id.
$max = 0;
$lastItem = null;
foreach ($items as $item){
if ($item->getId() > $max) {
$max = $item->getId();
$lastItem = $item;
}
}
if ($lastItem){
//do something with $lastItem
}

get the values of custom options

I'm trying to alter a price based on some custom options set. Therefore I'm trying to get the value a customer has entered, not the default values set in the backend. To do this I'm using the event catalog_product_get_final_price used in Mage_Bundle_Model_Product_Price. I have registered the following observer:
public function observer_callback($evt_obs)
{
$event = $evt_obs->getEvent();
$data = $event->getData();
/* #var $collection Mage_Catalog_Model_Resource_Product_Collection */
$collection = $data['collection'];
$items = $collection->getItems();
/* #var $item Mage_Catalog_Model_Product */
foreach ($items as $item) {
if ( $item->getName() == 'Bundel Test2') {
$options = $item->getCustomOptions();
/* #var $option Mage_Catalog_Model_Product_Option */
foreach ($options as $option) {
// Here I'm trying to get the value given by the user/customer
var_dump($option->getData());
}
}
}
return $this;
}
It is a custom option from a bundle type. So the product can't be configurable.
I'm new to magento so I'm probably missing something.
Can anyone help me?
Hope this piece of code can help you:
public function productFinalPrice($observer){
$product = $observer->getEvent()->getProduct();
$productType=$product->getTypeID();
if($productType == 'your_product_type')
{
$option = $product->getCustomOptions();
$searchedOption = null;
//search for your option;
foreach ($product->getOptions() as $o) {
if($o->getTitle()=="your_attribute_title" && $o->getType()=="your_type_of_option(eg. area"){
$optionId = $o->getOptionId();//got your searched optionId
break;
}
}
foreach($option as $key => $o) {
if($key == "option_".$optionId) {
$searchedOption = $o;
//here you get the option object with the values in it
}
}
$articleNumber = $searchedOption->getData('value'); // getthe value of your option
//calculate final price like you need it
$product->setFinalPrice($finalPrice);
}
return $this;
}
best regards

Creating categories and sub-categories in Magento Extension

I am new to Magento Extension Development and wondering which is the best way to create categories and sub-categories from within an extension. The Extension I am working on is synchronizing product-data from an ERP-System. The extension is operating with a System->Configuration Dialog which holds the data for the connection to the server (user/pwd/etc.) Now I am wondering, if it is better to connect via Ajax request or use a Soap call. Ajax seems very slow in this case for about 700 Products. So what do you suggest?
Furthermore, I am a little stuck by creating categories and sub-categories. Is there simple way to do that. I found some stuff on creating a category and then use the ->move() function. Moreover I am wondering if the 'path' of the category is essential on creating sub-categories.
You should use magento models:
Create category with subcategory:
/**
* After installation system has two categories: root one with ID:1 and Default category with ID:2
*/
/** #var $category1 Mage_Catalog_Model_Category */
$category1 = Mage::getModel('catalog/category');
$category1->setName('Category 1')
->setParentId(2)
->setLevel(2)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setIsActive(true)
->setPosition(1)
->save();
/** #var $category2 Mage_Catalog_Model_Category */
$category2 = Mage::getModel('catalog/category');
$category2->setName('Category 1.1')
->setParentId($category1->getId()) // set parent category which was created above
->setLevel(3)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setIsActive(true)
->setIsAnchor(true)
->setPosition(1)
->save();
public static function addCatalogCategory($item, $id, $storeId = 0) {
/*
* resource for checking category exists
* http://fishpig.co.uk/blog/load-a-category-or-product-by-an-attribute.html
*/
$categories = Mage::getResourceModel('catalog/category_collection');
// Select which fields to load into the category
// * will load all fields but it is possible to pass an array of
// select fields to load
$categories->addAttributeToSelect('*');
// Ensure the category is active
$categories->addAttributeToFilter('is_active', 1);
// Add Name filter
$categories->addAttributeToFilter('name', $item->GROUP_NAME);
// Limit the collection to 1 result
$categories->setCurPage(1)->setPageSize(1);
// Load the collection
$categories->load();
if ($categories->getFirstItem()->getId()) {
$category = $categories->getFirstItem();
return $category->getId();
}
/* get category object model */
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
$data = array();
/* if the node is root */
if (Heliumv_Synchronization_Helper_Data::xml_attribute($item, 'type') == 'root') {
$data['category']['parent'] = 2; // 2 top level id
} else {
/* is node/leaf */
$data['category']['parent'] = $id;
}
$data['general']['path'] = $item->PARENT_ID;
$data['general']['name'] = $item->GROUP_NAME;
$data['general']['meta_title'] = "";
$data['general']['meta_description'] = "";
$data['general']['is_active'] = "1";
$data['general']['url_key'] = "";
$data['general']['display_mode'] = "PRODUCTS";
$data['general']['is_anchor'] = 0;
/* add data to category model */
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
} else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
try {
$category->save();
return $category->getId();
} catch (Exception $e) {
echo Mage::log($e->getMessage());
}
}
I hope this helps someone. cheers

Check whether a product is in the wishlist or not

I'm working on a Magento theme, and I need to build a function that can check to see whether or not a product has been added to the user's wishlist.
Magento has a "Mage_Wishlist_Helper_Data" helper class, but I have no idea how to build a check-if-already-in-wishlist function. Basically I need to use Magento's wishlist feature to build a favorites list. I want to add a special class to the "add to wishlist" link if the particular product was already added to the user's favorites.
<?php $wishlist = Mage::getModel('wishlist/item')->load($_product->getId(),'product_id');
if($wishlist->getId())
//product is added
echo "Added! - Product is in the wishlist!";
else
//add product to wishlist
echo "<a href='".$this->helper('wishlist')->getAddUrl($_product) ."'>Add This?</a>";
;?>
Since collections are lazy loaded, I am assuming you can do something such as:
$_product = ...; // some product object you already have
$_productCollection = Mage::helper('wishlist')->getProductCollection()
->addFieldToFilter('sku', $_product->getSku());
if($_productCollection->count() > 0) {
// User already has item in wishlist.
}
You can do similar filtering on other fields, but SKU should be sufficient in this case.
I'm only getting back to this project now, but I took Daniel Sloof's suggestion, and it worked perfectly using the function below:
public function isInWishlist($item)
{
$_productCollection = Mage::helper('wishlist')->getProductCollection()
->addFieldToFilter('sku', $item->getSku());
if($_productCollection->count()) {
return true;
}
return false;
}
This checks to see whether or not a product has been added into the current user's Wishlist. I called it my template file like this:
if ($this->helper('wishlist')->isInWishlist($_product)) :
I found this solution after checked select query of Mage::helper('wishlist')->getWishlistItemCollection(). I hope this solution help to someone.
/**
* Check customers wishlist on identity product.
* #param Mage_Catalog_Model_Product $_product
* #return bool
*/
private function _isInWishlist($_product)
{
$_productCollection = Mage::helper('wishlist')->getWishlistItemCollection()
->addFieldToFilter('product_id', $_product->getId());
if ($_productCollection->count()) {
return true;
}
return false;
}
I solved this by the below function. I Hope this may help some one.
function checkInWishilist($_product){
Mage::getSingleton('customer/session')->isLoggedIn();
$session = Mage::getSingleton('customer/session');
$cidData = $session->isLoggedIn();
$customer_id = $session->getId();
if($customer_id){
$wishlist = Mage::getModel('wishlist/item')->getCollection();
$wishlist->getSelect()
->join(array('t2' => 'wishlist'),
'main_table.wishlist_id = t2.wishlist_id',
array('wishlist_id','customer_id'))
->where('main_table.product_id = '.$_product->getId().' AND t2.customer_id='.$customer_id);
$count = $wishlist->count();
$wishlist = Mage::getModel('wishlist/item')->getCollection();
}
else {
$count="0";
}
if ($count) :
return true;
else:
return false;
endif;
}
Since #alexadr.parhomenk s' solution causes undesired results, here's a smaller method that does the trick:
/**
* Check customers wishlist on identity product.
* #param int $productId
* #return bool
*/
public function isInWishlist($productId)
{
$ids = Mage::registry('wishlist_ids');
if (!$ids) {
$productCollection = Mage::helper('wishlist')->getWishlistItemCollection();
$ids = $productCollection->getColumnValues('product_id');
Mage::register('wishlist_ids', $ids);
}
return in_array($productId, $ids);
}

Need help with Wishlist

The wishlist section in the sidebar disappears when all the items in it are removed.. but i want to shot it even when there is no items in wishlist with a text "Add some items to your wishlist".. as like "Compare section".. how do i do it?
i tried editing the .phtml file for doing it, but its not working.. do i need to edit any xml layout file for this?
For just info, please don't reputate.
The wishlist class has been changed after 1.4.2 :
* #deprecated after 1.4.2.0
* #see Mage_Wishlist_Block_Links::__construct
*
* #return array
*/
public function addWishlistLink()
{
return $this;
}
and here is the your requested feature ( look at count ) :
/**
* Add link on wishlist page in parent block
*
* #return Mage_Wishlist_Block_Links
*/
public function addWishlistLink()
{
$parentBlock = $this->getParentBlock();
if ($parentBlock && $this->helper('wishlist')->isAllow()) {
$count = $this->helper('wishlist')->getItemCount();
if ($count > 1) {
$text = $this->__('My Wishlist (%d items)', $count);
}
else if ($count == 1) {
$text = $this->__('My Wishlist (%d item)', $count);
}
else {
$text = $this->__('My Wishlist');
}
$parentBlock->addLink($text, 'wishlist', $text, true, array(), 30, null, 'class="top-link-wishlist"');
}
return $this;
}
Magento 1.6.1.0
/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php
contains the function _toHtml():
protected function _toHtml()
{
if (($this->getCustomWishlist() && $this->getItemCount()) || $this->hasWishlistItems()) {
return parent::_toHtml();
}
return '';
}
Copy:
/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php
to:
/app/code/local/Mage/Wishlist/Block/Customer/Sidebar.php
In the copied file, replace the contents of function _toHtml() with return parent::_toHtml();:
protected function _toHtml()
{
return parent::_toHtml();
}

Resources