Magento - get cart items for a given product id - magento

I try to get the cart items for a given product;
I have tried this code :
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load('2784');
$quote = Mage::getSingleton('checkout/cart')->getQuote();
$cartItems = $quote->getItemByProduct($product);
foreach ($cartItems as $item) {
echo $item->getId()."<br/>";
}
but it don't gives anything.
How can I modify my code to use "getItemByProduct" in the right form ?
Thanks for help.

getItemByProduct() returns the first matching Mage_Sales_Model_Quote_Item so there is no need for an extra loop.
$item = $quote->getItemByProduct($product);
if ($item !== false) echo $item->getId();

I'd use
foreach ($quote->getItems() as $item) {
if ($item->getProductId() == $product->getId()) {
print_r($item->getData());
}
}

You can not use getItemByProduct() function on the checkout/cart or checkout/quote model as that method is of the sales/quote model.
You can find this method at the Mage_Sales_Model_Quote class. so it is used withe sales/quote. hope this is useful.

Related

Magento Collection get clients by payment method

I would like to know if anyone already coded a Magento Collection to get the customer name by the payment method? I used the code bellow and now I have the payment method that I need, now I just have to get the client's first and last name. Thank you all for the help.
$collection = Mage::getResourceModel('sales/order_payment_collection')
->addFieldToSelect('*');
foreach ($collection as $method) {
if ($method->getMethod() == "mundipagg_boleto") {
print $method->getMethod()."<br>";
}
}
$collection = Mage::getResourceModel('sales/order_payment_collection')
->addFieldToSelect('*')
->addFieldToFilter('method', "mundipagg_boleto");
foreach ($collection as $orderPayment) {
$orderId = $orderPayment->getParentId();
$order = Mage::getModel('sales/order')->load($orderId);
$customerId = $order->getCustomerId();
}
After that you can load customer's model by customerId

How to remove item from quote in Magento?

During the checkout process I sometimes want to programmatically remove items from the session's quote. So I tried this code:
$quote = Mage::getSingleton('checkout/session')->getQuote();
$all_quote_items = $quote->getAllItems();
foreach ($all_quote_items as $item) {
$quote->removeItem($item->getId())->save();
}
However, after this loop the list of items in the $quote object is still the same, i.e. no items have been removed.
Any ideas what I am missing here?
Using Magento 1.4.1.1
Try
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item)
{
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
}
See http://www.magentocommerce.com/boards/viewthread/30113/
In Magento 1.7.0.0 version, you can use:
Mage::getSingleton('checkout/cart')->truncate()->save();
I do a similar process while looking for items of a certain type, The logic I applied is:
$session= Mage::getSingleton('checkout/session');
$quote = $session->getQuote();
$cart = Mage::getModel('checkout/cart');
$cartItems = $cart->getItems();
foreach ($cartItems as $item)
{
$quote->removeItem($item->getId())->save();
}
Try the above and if that fails I would start dumping the quote objects out before and after this logic is executed to see what differences there are.
Try the below code It will work
$product = $observer->getEvent()->getProduct();
$cart = Mage::getSingleton('checkout/cart');
foreach ($cart->getQuote()->getItemsCollection() as $_item) {
if ($_item->getProductId() == $productId) {
$_item->isDeleted(true);
//Mage::getSingleton('core/session')->addNotice('This product cannot be added to shopping cart.');
}
}

get custom attributes from an Mage_Sales_Model_Order_Item object

I’m writing an Observer for manage the order’s items, I need to send an email for every order based on some custom attributes.
The item object is Mage_Sales_Model_Order_Item and searching around I’ve tried methods like getData(’my_code’), getCustomAttribute, getAttributeText without success.
I need to get the category, size, color and some custom attributes…
Here my little code
class Example_OrderMod_Model_Observer{
public function doSomething($observer){
$order = $observer->getEvent()->getOrder();
$id_ordine = $order->getRealOrderId();
$cliente = $observer->getEvent()->getOrder()->getCustomerName();
foreach ($order->getAllItems() as $item) {
//$item is an instance of Mage_Sales_Model_Order_Item
$quantita = $item->getQtyOrdered();
$codice_giglio = $item->getSku();
//echo $item->getData('size');
var_dump($item->getAttributeText('size'));
var_dump($item->getProductOptionByCode('size'));
var_dump($item->getProductOptionByCode('famiglia'));
}
// die();
}
}
any ideas?
many thanks
You'll probably want to load up the product object, and then get your data off of that object. That will allow you to utilize all the methods you are looking for:
$product = Mage::getModel('catalog/product')->load($item->getProductId());
$size = $product->getAttributeText('size');
If $item is instance of Mage_Sales_Model_Order_Item you could simply use:
$product = $item->getProduct();
solution of display custom attributes
function getAttr($product_id, $attributeName) {
$product = Mage::getModel('catalog/product')->load($product_id);
$attributes = $product->getAttributes();
$attributeValue = null;
if(array_key_exists($attributeName , $attributes)) {
$attributesobj = $attributes["{$attributeName}"];
$attributeValue = $attributesobj->getFrontend()->getValue($product);
}
return $attributeValue;
}
When i tried the above methods it didn't worked somehow in my observer class. Actually the product model is unable to load with the above code block. I found this code and it worked. It loads the product model in observer.
$product = Mage::getModel('catalog/product');
$productId = $product->getIdBySku($item->getSku());
$product->load($productId);

How to load products media gallery along with the collection?

Can anybody give me a hint about how to load product's media gallery along with the collection?
I'm getting the collection like this:
$collection = Mage::getModel('catalog/product')->getCollection()
->addStoreFilter($storeId)
->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
foreach ($collection as $product) {
var_dump($product->getMediaGalleryImages());
}
But getMediaGalleryImages() returns null. I know that I can load each product separately with $product = Mage::getModel('catalog/product')->load($product->getId()) but I want to avoid this, because it causing unnecessary workload.
In case anyone’s looking for another approach on this, I found this to work (in just one case so no guarantees!):
Be sure to do $collection->addAttributeToSelect(’image’); first, then when looping through the collection products, do:
$attributes = $product->getTypeInstance(true)->getSetAttributes($product);
$media_gallery = $attributes[’media_gallery’];
$backend = $media_gallery->getBackend();
$backend->afterLoad($product); //this loads the media gallery to the product object
Not sure if all of this is necessary but I’m in a hurry. In my particular case I was trying to get the image url using $product->getImageUrl(); and this approach worked for me.
Hope it helps someone else.
I had to do the same recently, fastest method:
class My_Module_Block_Name extends Mage_Catalog_Block_Product_View_Abstract
{
/** #var null|Mage_Catalog_Model_Resource_Eav_Attribute */
protected static $_mediaGalleryBackend = null;
public function getGalleryImages()
{
$product = $this->getProduct();
$this->_getBackend()->afterLoad($product);
$collection = $product->getMediaGalleryImages();
return $collection;
}
/**
* #return Mage_Catalog_Model_Resource_Eav_Attribute
*/
protected function _getBackend() {
if (self::$_mediaGalleryBackend === null) {
$mediaGallery = Mage::getSingleton('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'media_gallery');
self::$_mediaGalleryBackend = $mediaGallery->getBackend();
}
return self::$_mediaGalleryBackend;
}
}
try this
$collection = Mage::getModel('catalog/product')->getCollection()
->addStoreFilter($storeId)
->addAttributeToSelect(array('image', 'media_gallery'))
->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
foreach ($collection as $product) {
var_dump($product->getMediaGallery());
}
It can be used directly in loop:
foreach ($collection as $product) {
$product->getResource()->getAttribute('media_gallery')->getBackend()->afterLoad($product);
foreach ($product->getMediaGalleryImages() as $image) {
var_dump($image->debug());
}
}
You are going to have to use:
// Returns the Media Gallery Images
Mage::getModel(’catalog/product’)->load(productid)->getMediaGalleryImages();
Reference: http://www.magentocommerce.com/boards/viewthread/29639/
The secret sauce when working with custom collections involving products is the third parameter of init method... at least it was for me. This way I don't need to load the whole product and run expensive queries.
So, having my custom $product which represents an instance of Mage_Catalog_Model_Product but from my custom collection, I can do:
(string)Mage::helper('catalog/image')->init($product, 'small_image', $product->getImage())
I also needed to add the image attribute to my custom collection, and I did that by adding ->addAttributeToSelect(['image']) to it.
You can also resize your image accordingly:
(string)Mage::helper('catalog/image')->init($product, 'small_image', $product->getImage())->resize($width, $height=null)
Here is a function to add the media gallery to a collection:
// Source: http://www.magentocommerce.com/boards/viewthread/17414/#t141830
public function addMediaGalleryAttributeToCollection(Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection $_productCollection) {
$_mediaGalleryAttributeId = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'media_gallery')->getAttributeId();
$_read = Mage::getSingleton('core/resource')->getConnection('catalog_read');
$_mediaGalleryData = $_read->fetchAll('
SELECT
main.entity_id, `main`.`value_id`, `main`.`value` AS `file`,
`value`.`label`, `value`.`position`, `value`.`disabled`, `default_value`.`label` AS `label_default`,
`default_value`.`position` AS `position_default`,
`default_value`.`disabled` AS `disabled_default`
FROM `catalog_product_entity_media_gallery` AS `main`
LEFT JOIN `catalog_product_entity_media_gallery_value` AS `value`
ON main.value_id=value.value_id AND value.store_id=' . Mage::app()->getStore()->getId() . '
LEFT JOIN `catalog_product_entity_media_gallery_value` AS `default_value`
ON main.value_id=default_value.value_id AND default_value.store_id=0
WHERE (
main.attribute_id = ' . $_read->quote($_mediaGalleryAttributeId) . ')
AND (main.entity_id IN (' . $_read->quote($_productCollection->getAllIds()) . '))
ORDER BY IF(value.position IS NULL, default_value.position, value.position) ASC
');
$_mediaGalleryByProductId = array();
foreach ($_mediaGalleryData as $_galleryImage) {
$k = $_galleryImage['entity_id'];
unset($_galleryImage['entity_id']);
if (!isset($_mediaGalleryByProductId[$k])) {
$_mediaGalleryByProductId[$k] = array();
}
$_mediaGalleryByProductId[$k][] = $_galleryImage;
}
unset($_mediaGalleryData);
foreach ($_productCollection as &$_product) {
$_productId = $_product->getData('entity_id');
if (isset($_mediaGalleryByProductId[$_productId])) {
$_product->setData('media_gallery', array('images' => $_mediaGalleryByProductId[$_productId]));
}
}
unset($_mediaGalleryByProductId);
return $_productCollection;
}
An example of it's usage below:
$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
$this->addMediaGalleryToArray($products);

$item->getProduct()->getQty not working in magento

I wrote a function in shipping.php. I want to get the quantity from each product in the cart. I am using $item->getProduct()->getQty, but this is not working.
Is there any other method?
Have you tried $item->getQty() ?
For future readers: look into the relevant source code, e.g app/code/core/Mage/Sales/Model/Order/ to find the exact API.
In that case, the code you are looking for is probably $item->getQtyOrdered(). Not sure which one you're referring to above.
$cart = Mage::getModel('checkout/cart')->getQuote();
$result = array();
$i = 0;
foreach ($cart->getAllItems() as $item) {
$result[$i]['id'] = $item->getProduct()->getId();
$result[$i]['name'] = $item->getName();
$result[$i]['sku'] = $item->getSku();
$result[$i]['price'] = $item->getPrice();
$result[$i]['qty'] = $item->getQty();
$i++;
}
echo "<pre>";
print_r($result);
Try this.
You can use
$item->getId();
to get the cart product ID too.
$item->getProduct()->getQty; will be returned by NULL;

Resources