Get custom attribute from product in Magento 1.9 - php

I'm trying to fetch some product data based on the products SKU. This is working, but I also need to get a custom added attribute at the same time, named 'sku_supplier'. Is this possible?
This is what I got:
require $_SERVER['DOCUMENT_ROOT'] . "/app/Mage.php";
Mage::app();
$sku = '748547';
$products = Mage::getResourceModel('catalog/product_collection');
$products->addAttributeToSelect('*');
$products->addAttributeToFilter('visibility', array('neq' => 1));
$products->addAttributeToFilter('status', 1);
$products->addAttributeToFilter('sku', $sku);
$products->setCurPage(1)->setPageSize(1);
$products->load();
if ($products->getFirstItem()) {
$product = $products->getFirstItem();
$strProdName = $product->getName();
$strProdSku = $product->getSku();
$strProdSkuSup = $product->getSku_Supplier(); // <= I want to show this
}else{
$addError = 'true';
$addErrorMessage[] = 'Error...';
}
Thanks in advance,

Just remove the underscore:
$strProdSkuSup = $product->getSkuSupplier();
$strProdSkuSup = $product->getData('sku_supplier'); //alternative
Magento translates snake_case into camelCase when you want to use the magic getters; ie. an attribute with the attribute code cool_custom_attribute would translate into coolCustomAttribute, i.e. $product->getCoolCustomAttribute().
Edit:
You might need to load a product model as sometimes I've experienced that not all custom attributes are attached when you pull it out of a collection (intended for performance reasons I guess). Something like:
$_product = Mage::getModel('catalog/product')->load($product->getId());
$strProdSkuSup = $_product->getSkuSupplier();
Also, did you know that there's a dedicated StackExchange site for Magento?

Use this
$strProdSkuSup = $product->getSkuSupplier();
Instead of
$strProdSkuSup = $product->getSku_Supplier();

Related

Magento - Get the associated product attributes of an item in the wishlist

In app/code/local/Mage/Catalog/Product/Type/Configurable/Price.php, I am trying to get the attribute values of an associated product within the wishlist. I've attempted several approaches but I can only seem to produce data for the parent product.
Latest attempt
$customer = Mage::getSingleton('customer/session')->getCustomer();
if($customer->getId()) {
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $wlitem) {
$wishitem = Mage::getModel('catalog/product')->setStoreId($wlitem->getStoreId())->load($wlitem->getProductId());
//echo $wishitem->getId() . '<br>';
if($product->getId() == $wishitem->getId()) { //if the current product id equals the wishlist product id
echo $wishitem->getSku()."</br>";
}
}
}
That only gets me the parent product's sku. What I ultimately want to get is the attribute value for 2 attributes that I added for configurable products (not super attributes) but it seems that $product in Price.php only has the parent product collection.
Other Attempts:
$item_s = Mage::getModel('wishlist/item')->loadWithOptions($product->getId(), 'simple_product')->getOptionsByCode();
$simple_product = $item_s['simple_product']->getData();
$simple_product_id = $simple_product['product_id'];
$sim_product = Mage::getModel('catalog/product')->load($simple_product_id);
print_r($sim_product);
This only resulted in an error on the page.
Also:
$_item = Mage::getModel('catalog/product')->load($product->getId());
//echo $_item->getData('ppuom');
//print_r($_item);
$simpleProduct = $_item->getOptionsByCode()['simple_product']->getItem()->getProduct();
print_r($simpleProduct);
Seems as if you were most of the way there. I've tested this on my Magento site and it worked for me. It's pretty simple actually, you just have to grab the right model for that collection. Also, it seems like you're changing the pricing?!?! Be careful that your wishlist items contain the necessary attributes used in your logic.
$_item = Mage::getModel('catalog/product')->load($product->getId());
$attribute1 = $_item->getData('attribute1_code'); //see admin for attribute code
$attribute2 = $_item->getData('attribute2_code'); //see admin for attribute code
OR
Make changes to your template's wishlist files rather than the pricing logic in the code folder. You'll have access to all the data you need and it won't interfere with the price.php file which is relied on heavily in the cart and other critical areas of the website. The price in the wishlist is recalculated when it's moved to the cart anyway.

Magento - How to convert simple products to grouped ones programmat​ically?

My client and I are trying to achieve something that we are maybe not supposed to do. We have a demanding set of non-standard products that include different types of product conditions, e.g. grade B ware etc. In addition product data is coming in in form of feeds from several suppliers. In order not to clutter up the product listing we would like to convert existing, manually edited simple products into grouped ones (or whatever is appropriate) with associated new simple products programmatically on the fly and vice versa whenever necessary, i.e. when there are at least two different sub products.
So far we managed to do this somehow, a test scenario produces the seemingly right product structure – correctly associated products are displayed in the backend, the quantities have been correct before. The problem occurs with the frontend check on 'isSaleable()' for both the grouped product and the associated products, it returns 'false' no matter what we do. When we enforce the display of the qty input boxes and add-to-cart button they will (naturally?) just product the error message 'Please specify the quantity of product(s)'. We tried to set 'is_salable' by different means throughout the code. What else is missing? Any little hint, any advice here would be appreciated!
The code is quite lengthy already, and probably there's already some redundancy in there because of our attempts to somehow fix this. There's a main script that fetches a product collection and compares each entry with the existing supplier feeds. The essential part then is the function call to convert the product:
if (sizeof($newProducts[$productsSku]) > 1 && $_product->getTypeId() == 'simple') {
$newProductQtys = createGroupedProduct($_product, $newProducts[$productsSku]);
}
There are 2 functions for the actual conversion process, one which creates duplicates of the master products (type = simple) and sets their values accordingly:
function createDuplicate($product, $values) {
global $suppliers, $conditions_arr;
$sku = $product->getSku();
$newSku = $sku.'-v'.$suppliers[$values['feed']]['id'];
$qty = $values['qty'];
$feed = $values['feed'];
$cost = $values['cost'];
$item_condition = $values['item_condition'];
$box_condition = $values['box_condition'];
$notes = stripslashes($values['notes']);
$newProduct = $product->duplicate();
$newProduct->setTypeId('simple');
$newProduct->setStoreId(0);
$newProduct->setWebsiteIds(array(1));
$newProduct->setVisibility(2);
$newProduct->setSku($newSku);
$newProduct->setData('media_gallery', array());
$newProduct->setStatus(Mage_Catalog_Model_Product_​Status::smileyfrustrated:TATUS_ENABLED);
$newProduct->setPrice((real)($cost + $cost*$suppliers[$feed]['price_increase']));
$newProduct->setTaxClassId(2);
$newProduct->getResource()->save($newProduct);
$productId = $newProduct->getId();
// Check if there is a stock item object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loa​dByProduct($productId);
$stockItemData = $stockItem->getData();
if (empty($stockItemData)) {
// Create the initial stock item object
$stockItem->setData('inventory_manage_stock_defaul​t', 1);
$stockItem->setData('manage_stock',1);
$stockItem->setData('is_in_stock', $qty ? 1 : 0);
$stockItem->setData('is_salable', 1);
$stockItem->setData('use_config_manage_stock', 1);
$stockItem->setData('stock_id',1);
$stockItem->setData('product_id',$productId);
$stockItem->setData('qty',$qty);
$stockItem->setTypeId( $newProduct->getTypeId() );
$stockItem->save();
// Init the object again after it has been saved so we get the full object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loa​dByProduct($productId);
}
// Set the quantity
$stockItem->setData('qty',$qty);
$stockItem->setData('is_salable', 1);
$stockItem->save();
// $newProduct->assignProduct($newProduct, 1, 1);
$newProduct->setIsSalable(1);
$newProduct->setStatus(Mage_Catalog_Model_Product_​Status::smileyfrustrated:TATUS_ENABLED);
$newProduct->save();
$event = Mage::getSingleton('index/indexer')->logEvent($new​Product,$newProduct->getResource()->getType(),Mage​_Index_Model_Event::TYPE_SAVE,false);
Mage::getSingleton('index/indexer')->getProcessByC​ode('cataloginventory_stock')->setMode(Mage_Index_​Model_Process::MODE_REAL_TIME)->processEvent($even​t);
return $productId;
}
and
function createGroupedProduct($product, $newProductsArr) {
global $suppliers;
$origProductId = $product->getId();
$sku = $product->getSku();
$newProductId = array();
$newProductQtys = array();
$qty = 0;
$price = 999999;
$product->setTypeId('grouped');
$product->save();
foreach($newProductsArr as $key => $values) {
$id = createDuplicate($product, $values);
$newProductId[] = $id;
$newProductQtys[$id] = $values['qty'];
// add up all stock quantities of all slave products for master
$qty += $values['qty'];
// determine lowest price among all slave products
$subItemPrice = (real)($values['cost'] + $values['cost']*$suppliers[$values['feed']]['price​_increase']);
if ($subItemPrice < $price) $price = $subItemPrice;
}
if (sizeof($newProductId) > 1) {
$products_links = Mage::getModel('catalog/product_link_api');
foreach($newProductId as $key => $id) {
$products_links->assign('grouped', $origProductId, $id);
}
}
// set new values for grouped product according to slave products values
$product->setPrice($price);
$product->getResource()->save($product);
// Check if there is a stock item object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loa​dByProduct($origProductId);
$stockItemData = $stockItem->getData();
if (empty($stockItemData)) {
// Create the initial stock item object
$stockItem->setData('manage_stock',1);
$stockItem->setData('is_in_stock', $qty ? 1 : 0);
$stockItem->setData('is_salable', 1);
$stockItem->setData('use_config_manage_stock', 1);
$stockItem->setData('stock_id',1);
$stockItem->setData('product_id',$origProductId);
$stockItem->setData('qty',$qty);
// $stockItem->setTypeId( $product->getTypeId() );
$stockItem->setTypeId('grouped');
$stockItem->save();
// Init the object again after it has been saved so we get the full object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loa​dByProduct($origProductId);
}
// Set the quantity
$stockItem->setData('qty',$qty);
$stockItem->setData('is_in_stock', $qty ? 1 : 0);
$stockItem->setData('is_salable', 1);
$stockItem->save();
$product->setStatus(Mage_Catalog_Model_Product_Sta​tus::smileyfrustrated:TATUS_ENABLED);
$product->save();
$event = Mage::getSingleton('index/indexer')->logEvent($pro​duct,$product->getResource()->getType(),Mage_Index​_Model_Event::TYPE_SAVE,false);
Mage::getSingleton('index/indexer')->getProcessByC​ode('cataloginventory_stock')->setMode(Mage_Index_​Model_Process::MODE_REAL_TIME)->processEvent($even​t);
$cache = Mage::getSingleton('core/cache');
$cache->flush();
return $newProductQtys;
}
We tried using the store ID '1' as well and had some success with the shopping cart when the front end used the same kind of mass-product-add-to-cart form that we integrated into the product listing. But the associated products then showed no product name and no image, and not in the admin at all.
If more code from the main script is necessary I will happily provide this.

Magento Custom Sitemap

Magento's default sitemap generation produces an XML file that displays all products, including simple products that are associated with configurable products. I only want the configurable product not the associated simple products, can anyone help me?
In Mage/Sitemap/Model/Sitemap.php the function that generates the XML sitemap is generateXml() and the code block that generates the product urls is:
$changefreq = (string)Mage::getStoreConfig('sitemap/product/changefreq', $storeId);
$priority = (string)Mage::getStoreConfig('sitemap/product/priority', $storeId);
$collection = Mage::getResourceModel('sitemap/catalog_product')->getCollection($storeId);
foreach ($collection as $item) {
$xml = sprintf('<url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%.1f</priority></url>',
htmlspecialchars($baseUrl . $item->getUrl()),
$date,
$changefreq,
$priority
);
$io->streamWrite($xml);
}
unset($collection);
I tried using
Mage::getModel('catalog/product')->getCollection();
and changed this line:
htmlspecialchars($baseUrl . $item->getUrl()),
to this line to get it work
htmlspecialchars($item->getProductUrl()),
I get the correct products (without the associated ones), but the urls are like this:
http://www.domain.com/catalog/product/view/id/532/
I want the Url Rewrites, so i changed it to:
$collection = Mage::getModel('catalog/product')->getCollection($storeId)
->addUrlRewrite();
But i still get this:
http://www.domain.com/catalog/product/view/id/532/
Any ideas what's wrong?
you can try with below code.
$product_collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToFilter('entity_id', 16)->addUrlRewrite();
echo $product_collection->getFirstItem()->getProductUrl();
or you can load url separately as you already have product collection than try something like this
Mage::getResourceSingleton('catalog/product')->getAttributeRawValue($productId, 'attribute_code', Mage::app()->getStore());

get quote's product attribute

Hi I'm trying to get a product attribute admin value or id (since it's multilanguage) from the cart items. I've tried many versions of code like this one:
$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllItems() as $item) {
$_product = Mage::getModel('catalog/product')->load($item->getId());
$attribute = $_product->getAttribute('producttype');
}
But I only ever get false or null. Also how can I be sure to not get the store specific language value, but the attributes admin value/id? Maybe there's an even better way to read out the item attributes directly from the quote items without having to load the product first? Thanks in advance!
Solved with:
$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllVisibleItems() as $_item)
{
$_product = Mage::getModel('catalog/product')->load($_item->getProductId());
$attributeId = $_product->getProducttype();
}
and comparing by value ID instead of text.
If you need to get the product's value for a specific shop, while the items in the quote belong to a different store view, you can do the folowing:
$_product = Mage::getModel('catalog/product')
->setStoreId($adminStoreId)
->load($item->getId());
$value = $_product->getData('producttype');

How to get a list of simple products from a configureable product

i have the following code
$id = 19654;
$prod = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
$prod->addAttributeToFilter('entity_id',array('in'=> array($id)));
$prod->load();
using the following code
foreach($prod as $_prod)
{
var_dump($_prod->getData());
}
i can view almost all the data accosted with the configurable product i'm looking at, what i'm missing is at minimum, a list of entity_id's for the simple products that are associated with it
in terms of the database, i know the link between simple and configurable product is in either catalog_product_relation, catalog_product_super_link and/or catalog_product_link, ofcause, since i'm using a collection i can't just use an INNER JOIN
i'm running this code off from a test.php page in the root directory of my magento install
Try
$_product = Mage::getModel('catalog/product')->load($productId);
if($_product->getTypeId() == "configurable"){
$AssociatedProduct = $_product->getTypeInstance()->getUsedProducts();
}
Or
if($_product->getTypeId() == "configurable"){
$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
foreach($col as $simple_product){
var_dump($simple_product->getId());
}
}
See http://www.magentocommerce.com/boards/viewthread/41874/

Categories