Magento 1.5.1.0 - While trying to update stock quantity on products, getStockData is returning NULL - magento

I have products loaded in Magento that I am trying to bulk update the inventory qty on. I created all the products using Mage_Catalog_Model_Product and set the qty on them using setStockData like:
$product = new Mage_Catalog_Model_Product();
$product->setTypeId('simple');
$product->setStatus(1);
$product->setSku($sku);
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => $record['stockstatus'],
'manage_stock' => 0,
));
...
So I've seen setStockData work ... 13,000+ times.
Now, as I said, I'm trying to update the inventory on the products I created using a variation on what I did to create the products ... a variation that I see here and virtually identically elsewhere on the web.
My problem is that I can use a variation of the code at the link above and get a valid product object, but when I call getStockData on the object, it returns NULL:
$product = Mage::getModel('catalog/product')
->loadByAttribute('product_code', '678910');
var_dump($product->getName()); // returns 'Hello My Name is Product'
var_dump($product->getProductCode()); // returns '678910'
var_dump($product->getSku()); // returns 'SKU1234'
var_dump($product->getStockData()); // returns NULL (and there is a qty of 52 set)
(I've also tried getting the product with no variations on the code at the link above and have had the same results as I expected.)
$product_id = Mage::getModel('catalog/product')->getIdBySku('SKU1234');
$product = Mage::getModel('catalog/product');
$product->load($product_id);
$stockData = $product->getStockData();
var_dump($product->getName()); // returns 'Hello My Name is Product'
var_dump($product->getProductCode()); // returns '678910'
var_dump($product->getSku()); // returns 'SKU1234'
var_dump($product->getStockData()); // returns NULL (and there is a qty of 52 set)
So, if I can't get the stock data with getStockData, I can't set the stock data like:
$product = Mage::getModel('catalog/product')
->loadByAttribute('product_code', $record['productcode']);
$stockData = $product->getStockData();
$stockData['qty'] = $record['stockstatus'];
$stockData['is_in_stock'] = ($record['stockstatus'] > 0) ? 1 : 0;
$product->setStockData($stockData);
$product->save();
Is there something I'm missing? I don't understand why getStockData is returning NULL. Can someone help me understand what I may be doing wrong?

Use getStockItem() instead of getStockData()
$stockData = $product->getStockItem();
$stockData->setData('qty',555);
$stockData->setData('is_in_stock',1);
$stockData->setData('manage_stock',1);
$stockData->setData('use_config_manage_stock',1);
$stockData->save(); // This enough to save stock data.
Use getData for arrays, use getItem for objects.

yeah no why getStockData() returns null.. But I was able to get the stock quantity using the following:
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId())->getQty();

You should call save() on stock_item rather than product after changing qty. Following code worked for me:
$product = Mage::getModel('catalog/product')
->loadByAttribute('product_code', '678910');
$stock_obj = Mage::getModel('cataloginventory/stock_item')
->loadByProduct($product->getId());
$stockData = $stock_obj->getData();
$stockData['qty'] = $record['stockstatus'];
$stock_obj->setData($stockData);
$stock_obj->save();

Related

How to programmatically get option id's and values from configurable product in phtml?

I am modifying phtml code were I have access to
$this which happens to be Mage_Checkout_Block_Cart_Item_Renderer_Configurable class
and
$_item = $this->getItem();
$_product = $_item->getProduct();
where product is a configurable product in a cart.
Based on this I need to get a list of option id (swatches) and their values.
For example, to get specific size option id :
$product = $_item->getProduct();
$idStore = $_item->getOrder()->getStoreId();
$sizeSpecificAttributeCode = 'specific_size';
$sizeAttributeOptionId = $product->getResource()
->getAttributeRawValue($product->getId(), $sizeSpecificAttributeCode,$idStore);
from the same logic you can get the swatches or other options

How to get product name in magento?

I am trying to get only product name using the product id.
I have tried the below:
$product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$product->getName();
It load the whole resource object and than we can get the name using $product->getName() but I need only single name so we can reduce the extra overheads.
$product = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('name')->addAttributeToFilter('entity_id', PRODUCT_ID)->load();
It also load the resource object.
is there any easiest way to get the product name( for exa. 'Test product') without loading the resource object?
Use getAttributeRawValue() With this you can get the attribute value of your product :
$attribute_value = Mage::getResourceModel('catalog/product')->getAttributeRawValue(PRODUCT_ID, 'attribute_code');
Try this,hope it's work for you.
Try this :
$product = Mage::registry('current_product'); then
$product->getName();
$product->getId();
You can try this for product :
$id = $this->getRequest()->getParam('id');
$current_product=Mage::getModel('catalog/product')->load($id);
We need to pass store value as well to get product attribute directly from resource model.
You can get store id by using this code:- Mage::app()->getStore().
So the final query will be :-
$attribute_value = Mage::getResourceModel('catalog/product')->getAttributeRawValue(PRODUCT_ID,'attribute_code',Mage::app()->getStore());

Magento: where are catalog filter's (url get parameter's) handled in magento? and where is sql request made to fetch the result?

Magento currently handles only one filter parameter per category .
I want the filter to handle more than one parameter's for the same category.
eg, Suppose I choose 2 colors red and black in the filter using a checkbox for ex, and then click submit button (which I have added), then I want the page to display results for product's having color red or black.
For this, I want to know :
Where are GET parameter's for any filtering process handled in magento.
Where is the sql request made to fetch the results of filtering process.
So that I could handle more than one filter parameter's and display the results.
Any help or suggestion would be of great help.
Thanks in advance..
For your example scenario, you are filtering using attribute color having its attribute ID. The resource model is responsible to execute the SQL operations being performed on any attribute selection.
Go to file app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Attribute.php
public function applyFilterToCollection($filter, $value)
{
$collection = $filter->getLayer()->getProductCollection();
$attribute = $filter->getAttributeModel();
$connection = $this->_getReadAdapter();
$tableAlias = $attribute->getAttributeCode() . '_idx';
$conditions = array(
"{$tableAlias}.entity_id = e.entity_id",
$connection->quoteInto("{$tableAlias}.attribute_id = ?", $attribute->getAttributeId()),
$connection->quoteInto("{$tableAlias}.store_id = ?", $collection->getStoreId()),
$connection->quoteInto("{$tableAlias}.value = ?", $value)
);
$collection->getSelect()->join(
array($tableAlias => $this->getMainTable()),
implode(' AND ', $conditions),
array()
);
return $this;
}
In the above function, when you print the collection and exit it before return using,
$collection->printlogquery(true);
you will see the SQL query generated to fetch the results of filtering process.
You can modify this resource model in your local and using INNER JOIN change the SQL query to work for multiple attribute values.

list the values of a product attribute set in magento

how do I find the values of a product's attribute set?
For example, there's a product with an Attribute Set called shirts - T, with attributes of Gender, Shirt Size, and Color. Starting with a $_product object, how do I find the values of the attributes, e.g. Mens, Green, Large?
i am able to getting the attribute set value in the following way:
$product = Mage::getModel('catalog/product')->load($productId);
$prodAttributeSet = Mage::getModel('eav/entity_attribute_set')->load($product->getAttributeSetId())->getAttributeSetName();
I want to get all available attribute set values and codes for specific attribute set(i.e shirt - T)
$_product = Mage::getModel('catalog/product')->load($productId);
Now suppose you want to access value of manufacturer of this product, then consider following code.
$manufacturerValue = $_product->getAttributeText('manufacturer');
As you mention in comment for size and color here i can give you one sample code to use.
If it is a select or multiselect attribute, you still need to map the option ID's to option values. That is the case if you are getting a list of integers instead of human readable labels (e.g. for the color or manufacturer attribute).
// specify the select or multiselect attribute code
$attributeCode = 'color';
// build and filter the product collection
$products = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter($attributeCode, array('notnull' => true))
->addAttributeToFilter($attributeCode, array('neq' => ''))
->addAttributeToSelect($attributeCode);
$usedAttributeValues = array_unique($products->getColumnValues($attributeCode));
// ---- this is the different part compared to the previous example ----
// fetch the attribute model
$attributeModel = Mage::getSingleton('eav/config')
->getAttribute('catalog_product', $attributeCode);
// map the option id's to option labels
$usedAttributeValues = $attributeModel->getSource()->getOptionText(
implode(',', $usedAttributeValues)
);
Direct DB query example
Depending on where you want to do this, here is an example of fetching the values without using a product collection. It is slightly more efficient.
Only use the following code in resource models, as thats where DB related code belongs.
This is meant as an educational example to show how to work with Magento's EAV tables.
// specify the attribute code
$attributeCode = 'color';
// get attribute model by attribute code, e.g. 'color'
$attributeModel = Mage::getSingleton('eav/config')
->getAttribute('catalog_product', $attributeCode);
// build select to fetch used attribute value id's
$select = Mage::getSingleton('core/resource')
->getConnection('default_read')->select()
->from($attributeModel->getBackend()->getTable(), 'value')
->where('attribute_id=?', $attributeModel->getId())
->distinct();
// read used values from the db
$usedAttributeValues = Mage::getSingleton('core/resource')
->getConnection('default_read')
->fetchCol($select);
// map used id's to the value labels using the source model
if ($attributeModel->usesSource())
{
$usedAttributeValues = $attributeModel->getSource()->getOptionText(
implode(',', $usedAttributeValues)
);
}
If you want all the attributes of an attribute set you can do the following.
$product = Mage::getModel('catalog/product')->load($productId);
$attributes = $eavConfig->getEntityAttributeCodes( Mage_Catalog_Model_Product::ENTITY, $product );
print_r(attributes);

Magento: How to get the id of the just duplicated product programmatically

How can I get the id of the just duplicated product programmatically in Magento ?
(or the last inserted product id, if the first solution don't exits)
Thanks for help.
[EDIT]
Here is the code that I have used to duplicate my product:
$sku = '123456';
$product = Mage::getModel('catalog/product')
->loadByAttribute('sku',$sku);
$newProduct = $product->duplicate();
$newProduct->setStatus(1);
$newProduct->setSku($sku.'-v2');
$newProduct->save();
Thanks for help.
you can find the new prodect ID in:
$newProduct->getId()
This is available just after calling :
$newProduct = $product->duplicate();
FYI: to get the last insertedId (in general) you can use:
Mage::getSingleton('core/resource')->getConnection('core_read')->fetchOne('SELECT last_insert_id()')

Resources