How to hide no image items from Magento configurable options? - magento

I want to hide configurable options that doesn't have any image associated. I tried to rewrite the configurable product block but it doesn't work. anyone has any idea about this ?

I think a good solution is to set all simple products that don't have any pictures as out of stock and set the config system->catalog->inventory->stock options->Display Out of Stock Products to no.
If you have an product import logic you can integrate that code into that.

I got solution.
What I noticed, the configurable product options are coming from function $this->getJsonConfig(); located at Mage_Catalog_Block_Product_View_Type_Configurable block. what I did is, I rewrite this block in my module and alter the function by putting the below code in it.
public function getJsonConfig()
{
$attributes = array();
$options = array();
$store = $this->getCurrentStore();
$taxHelper = Mage::helper('tax');
$currentProduct = $this->getProduct();
$preconfiguredFlag = $currentProduct->hasPreconfiguredValues();
if ($preconfiguredFlag) {
$preconfiguredValues = $currentProduct->getPreconfiguredValues();
$defaultValues = array();
}
foreach ($this->getAllowProducts() as $product) {
if($product->getImage() && $product->getImage() != 'no_selection'){
$productId = $product->getId();
foreach ($this->getAllowAttributes() as $attribute) {
$productAttribute = $attribute->getProductAttribute();
$productAttributeId = $productAttribute->getId();
$attributeValue = $product->getData($productAttribute->getAttributeCode());
if (!isset($options[$productAttributeId])) {
$options[$productAttributeId] = array();
}
if (!isset($options[$productAttributeId][$attributeValue])) {
$options[$productAttributeId][$attributeValue] = array();
}
$options[$productAttributeId][$attributeValue][] = $productId;
}
}
}
I just added if($product->getImage() && $product->getImage() != 'no_selection'){ in allowed products foreach loop. This will only filter image items to configurable options json object array.

Related

How to get Product listing filters through custom module of magento?

I want to create product filters in listing pages of category using our own custom apis i have tried many things like
$layer = Mage::getModel("catalog/layer");
$category = Mage::getModel("catalog/category")->load($categoryid);
$layer->setCurrentCategory($category);
$attributes = $layer->getFilterableAttributes();
But this only loads the Filterable atrribute code for the category But we want the Filters values and count for the product collection available in that category.
Below code will load all the available options of that attribute but I want it for product collection specific
foreach($attributes as $attribute){
$options = $attribute->getSource()->getAllOptions(false);
}
Like we have Mobiles category having 1000s of mobiles and having filterable attribute Brand so i need
Brand
Brand A (100 products)
Brand B (500 products)
Brand C (400 products)
How can this be achived if i don't want to load whole product collection as loading 1000s of product will take too much time to response.
This code works for me :
public function ws_getfiter($store_id,$categoryid){
Mage::app()->setCurrentStore($store_id);
$layer = Mage::getModel("catalog/layer");
$category = Mage::getModel("catalog/category")->load($categoryid);
$layer->setCurrentCategory($category);
$attributes = $layer->getFilterableAttributes();
$filter = array();
$count = 0;
foreach ($attributes as $attribute)
{
if ($attribute->getAttributeCode() == 'price') {
$filterBlockName = 'catalog/layer_filter_price';
} elseif ($attribute->getBackendType() == 'decimal') {
$filterBlockName = 'catalog/layer_filter_decimal';
} else {
$filterBlockName = 'catalog/layer_filter_attribute';
}
$filter[$count]["code"] = $attribute->attribute_code;
$filter[$count]["type"] = $attribute->frontend_input;
$filter[$count]["label"] = $attribute->frontend_label;
$result = Mage::app()->getLayout()->createBlock($filterBlockName)->setLayer($layer)->setAttributeModel($attribute)->init();
$innercount = 0;
$filter_data = array();
foreach($result->getItems() as $option) {
$filter_data[$innercount]["count"] = $option->getCount();
$filter_data[$innercount]["label"] = $option->getLabel();
$filter_data[$innercount]["id"] = $option->getValue();
$innercount++;
}
$filter[$count]["values"] = $filter_data;
$count++;
}
return $filter;
}
But using this we are only getting single level of filter but i want it for multiple level.

Magento Multiple Wishlist creation programmatically

I know how to add products to a customer's wishlist programmatically however it only adds to one wishlist. I have the multiple wishlist option set to enabled however I do not know how to create a new wishlist instead of merging products into the existing wishlist.
public function submitQuote(Mage_Adminhtml_Model_Session_Quote $quote)
{
$currentQuote = $quote->getQuote();
$customer = $currentQuote->getCustomer();
$items = $currentQuote->getAllVisibleItems();
//$wishlist = Mage::helper('wishlist')->getWishlist();
//Mage::register('wishlist', $wishlist);
$wishlist = Mage::getModel('wishlist/wishlist');
$curretDate = date('m/d/Y', time());
$wishlist->setCustomerId($customer->getId());
$wishlist->setName('Quote ' . $curretDate)
->setVisibility(false)
->generateSharingCode()
->save();
foreach ($items as $item)
{
$productId = $item->getProductId();
$product = Mage::getModel('catalog/product')->load($productId);
$buyRequest = $item->getBuyRequest();
$result = $wishlist->addNewItem($product, $buyRequest);
if(is_string($result))
{
Mage::throwException($result);
}
$wishlist->save();
}
//Mage::unregister('wishlist');
}
I've had this problem before. To add a product to a customer's wishlist you need to start a wishlist model and call the addNewItem method passing the product object. Here is how I do it.
$customer = Mage::getModel('customer/customer');
$wishlist = Mage::getModel('wishlist/wishlist');
$product = Mage::getModel('catalog/product');
$customer_id = 1;
$product_id = 1;
$customer->load($customer_id);
$wishlist->loadByCustomer($customer_id);
$wishlist->addNewItem($product->load($product_id));
Hope this helps!
EDITED:
$customerid= "YOUR CUSTOMER ID "; // Modify This
$customer=Mage::getModel("customer/customer")->load($customerid);
$wishlist=Mage::getModel("wishlist/wishlist")->loadByCustomer($customer,true);
Check for reference this: app/code/core/Mage/Wishlist/Model/Wishlist.php
LATEST EDIT:
I see that your problem is here:
$result = $wishlist->addNewItem($product, $buyRequest);
FINAL EDIT:
Then create another function and add the items and wishlist you want to add it to (as parameters). This should add items to the wishlist that you have passed as an argument when calling the function. Its the only solution I can come up with. Hope this helps!
I just stumbled across this question because I'm trying to do something similar - your code part helped me to create a new wishlist, and I've managed to do the rest so thought I'd share.
This code will;
Create a new wishlist with the name 'Quote dd/mm/YY h:m:s'
Load the wishlist collection for the current user, ordered by highest ID first
Load the newest wishlist
Add all basket items to it
Redirect the user to the new wishlist view.
public function addToQuoteAction() {
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
$customerId = $customerData->getId();
} else {
Mage::getSingleton('core/session')->addError($this->__('Please login to use this feature'));
return $this->_redirectUrl($this->_getRefererUrl());
}
// Create the wishlist
$newWishlist = Mage::getModel('wishlist/wishlist');
$curretDate = date('d/m/Y h:m:s', time());
$newWishlist->setCustomerId($customerId);
$newWishlist->setName('Quote ' . $curretDate)
->setVisibility(false)
->generateSharingCode()
->save();
// Find the newly create list and load it
$wishlistCollection = Mage::getModel('wishlist/wishlist')->getCollection()
->addFieldToFilter('customer_id',$customerId)->setOrder('wishlist_id');;
$firstWish = $wishlistCollection->getFirstItem();
$wishlist = Mage::getModel('wishlist/wishlist')->load($firstWish->getWishlistId());
$cart = Mage::getModel('checkout/cart')->getQuote();
//getAllItems
foreach ($cart->getAllVisibleItems() as $item) {
$productId = $item->getProductId();
$buyRequest = $item->getBuyRequest();
$result = $wishlist->addNewItem($productId, $buyRequest);
$wishlist->save();
}
Mage::getSingleton('core/session')->addSuccess($this->__('All items have been moved to your quote'));
return $this->_redirectUrl(Mage::getBaseUrl().'wishlist/index/index/wishlist_id/'.$firstWish->getWishlistId().'/');
}

Magento get last added products options in cart

I am using ajax to add products to cart.when New product added to cart i want to display its details on right sidebar. I am able to list simple product, but i am not able to display bundle product options.I used following code to display cart items to right sidebar
$cartItems = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems();
foreach($cartItems as $item){
echo $item->getName();
}
Try this code:
$cartItems = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems();
foreach($cartItems as $item){
$result = array();
// Load the configured product options
$options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
// Check for options
if ($options)
{
if (isset($options['options']))
{
$result = array_merge($result, $options['options']);
}
if (isset($options['additional_options']))
{
$result = array_merge($result, $options['additional_options']);
}
if (!empty($options['attributes_info']))
{
$result = array_merge($options['attributes_info'], $result);
}
}
$finalResult = array_merge($finalResult, $result);
}
I think, it can help you.

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);

Resources