Programmatically create Magento product - magento

I am doing a project which is add Magento products programmatically. Here is the code segment
try{
//create new product
$newProduct = new Mage_Catalog_Model_Product();
$newProduct->setAttributeSetId(9)
->setTypeId('simple')
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->setTaxClassId(2)
->setCreatedAt(strtotime('now'))
->setName($data[0])
->setSku($data[1])
->setWeight($data[2])
->setStatus($data[3])
->setPrice($data[4])
->setCategoryIds(explode(',',$data[5]))
->setWebsiteIds(explode(',',$data[6]))
->setDescription($data[7])
->setShortDescription($data[8])
....
->setFreeGroundShipping($data[18])
->setMetaTitle($data[19])
->setMetaKeyword($data[20])
->setMetaDescription($data[21])
->setStockData(array(
'manage_stock'=>0,
'min_sale_qty'=>$data[22],
'max_sale_qty'=>$data[23]))
->setSetupFee($data[24])
->setsetupCost($data[25]);
$newProduct->save();
}catch(Exception $e){
$result['status'] = 3;
$result['message'] = 'There is an ERROR happened! NOT ALL products are created! Error:'.$e->getMessage();
echo json_encode($result);
return;
}
Here comes the problem: after executing the code, I went back to magento manage products, the product has been created, but some of the "store view" attributes are empty! I went into the database and find out that all the attributes have values.
Does anybody have any idea how to make the attributs to show? Thanks a lot!

Set your Store to Admin before adding products.
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

Related

Update Magento product meta description for different store

i am trying to update meta description for different store but magento keep showing error :
Product with URL key already exist.
what i am trying to do i have two stores on one magento. so we want seprate meta information for different stores. so when i try to update meta info for specific store then shows me error. any one facing same problem :
$pid = Mage::getModel('catalog/product')->getResource()->getIdBySku($sku);
$product = Mage::getModel('catalog/product')->load($pid);
if($product)
{
$product->setStoreId(6);
$product->setmeta_keyword($newKeyWord);
$product->setmeta_description($newmeta_metadescription);
try {
$product->save();
echo 'Product Updated successfully --- '.$sku."\n";
}
catch (Exception $ex) {
echo $ex->getMessage();
}
There are lot of issue in your code:
Setter function is wrong:
$product->setMetaKeyword($newKeyWord);
$product->setMetaDescription($newmeta_metadescription);
Best way to do this:
$product = Mage::getModel('catalog/product')->load($pid);
Please use below format,which more faster then your code
$product->addAttributeUpdate($Attributecode, $value, $storeId)
then
$product->addAttributeUpdate('meta_keyword', $newKeyWord, $storeId=6);
$product->addAttributeUpdate('meta_description', $newmeta_metadescription, $storeId=6);
No need use save() function in this case.

Magento add product for different storeview in one step

currently when I add or edit products for magento via api I will do something like this for each storeview:
$product = Mage::getModel('catalog/product');
$product->setStoreId($default_store_id); // 0 = default/all store view.
// do something
try
{
$product->save();
}
catch (Exception $e)
{
echo $e->getMessage();
}
This will takes 1 second for each storeview. When I edit 1 product for 10 storeviews it will takes 10 seconds.
Is there any way to edit alle storeview data (different languages) in one step?
No is the simple answer. You can create optimised code though for editing and only save the attribute you are updating as opposed to the entire product object but this depends on the scenario you are catering for.
$product = Mage::getModel('catalog/product')->setStoreId($storeId)->load($product_id);
$product->setName('Product Name');
$product->getResource()->saveAttribute($product, 'name');
Other option is to work directly on the database for updates rather than use magento objects.

Reindex Product after Cronjob in Magento - Configurable Products showing Out Of Stock

I have written a Extension that updates some custom shipping value Attributes on save for Magento 1.7. All working fine, when saving the product all is updated as it should. However I also have the need for a cronjob to update them each night in case I need to change shipping costs throught the board.
Is all working, and is updating the attribute values correctly, however on the frontend all configurable products are showing as Out of Stock, Simple Products are fine.
If I go to the admin, just click in the master product and save it without doing anything it shows back as In Stock on the frontend. Also if I go to Indexes and reindex Product Attributes it again shows as In stock on the frontend. I presume then that my cronjob needs to update the indexer on saving each product.
Looking around I used the following code, however it doesn't seem to update the product, and wondered if anyone could help. I have tried different variations around the Mage_Catalog_Model_Product and TYPE_SAVE but can't find what I am supposed to use!
$updateProduct = Mage::getModel('catalog/product')->load($_product->getId());
$updateProduct->setShippingLabel($shippData['delivery_type']);
$updateProduct->setShippingPrice($shippData['price']);
$updateProduct->setShippingNote($shippData['notes']);
try {
$updateProduct->save();
$updateProduct->setForceReindexRequired(true);
Mage::getSingleton('index/indexer')->processEntityAction(
$updateProduct,
Mage_Catalog_Model_Product::ENTITY,
Mage_Index_Model_Event::TYPE_SAVE
);
echo $updateProduct->getId()." Successfully Updated \n";
} catch(Exception $e){
echo $e->getMessage().$updateProduct->getId()."\n";
}
Update 17/5/2013 20:28
Have been playing with the code and this amendment seems to work, if it is totally useless and a stupid way of doing it please let me know
$updateProduct = Mage::getModel('catalog/product')->load($_product->getId());
$updateProduct->setShippingLabel($shippData['delivery_type']);
$updateProduct->setShippingPrice($shippData['price']);
$updateProduct->setShippingNote($shippData['notes']);
try {
$updateProduct->save();
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product->getId());
$stockItem->setForceReindexRequired(true);
Mage::getSingleton('index/indexer')->processEntityAction(
$stockItem,
Mage_CatalogInventory_Model_Stock_Item::ENTITY,
Mage_Index_Model_Event::TYPE_SAVE
);
echo $updateProduct->getId()." Successfully Updated \n";
} catch(Exception $e){
echo $e->getMessage().$updateProduct->getId()."\n";
}
After the execution of your cron job you can update your indexer:
$indexingProcesses = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach ($indexingProcesses as $process) {
$process->reindexEverything();
}
After the execution of your cron job you can update your indexer:
$indexingProcesses = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach ($indexingProcesses as $process) {
$process->reindexEverything();
}
hello dhawal if i have to run a cron job for to re-index product on site, I have to placed the code that you have mention with this code
$updateProduct = Mage::getModel('catalog/product')->load($_product->getId());
$updateProduct->`setShippingLabel`($shippData['delivery_type']);
$updateProduct->setShippingPrice($shippData['price']);
$updateProduct->setShippingNote($shippData['notes']);
try {
$updateProduct->save();
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product->getId());
$stockItem->setForceReindexRequired(true);
Mage::getSingleton('index/indexer')->processEntityAction(
$stockItem,
Mage_CatalogInventory_Model_Stock_Item::ENTITY,
Mage_Index_Model_Event::TYPE_SAVE
);
echo $updateProduct->getId()." Successfully Updated \n";
} catch(Exception $e){
echo $e->getMessage().$updateProduct->getId()."\n";
}
at same page ??

Magento mass-assign products to category

As the title says,i need to mass-assign products to a category and from the admin i can only edit one product at a time; i dont know why it just doesnt work to mass add them from the "category products" tab in the category page.
Thats why i need another method that's fast,like using phpMyAdmin or something alike.
Any help?
Thanks in advance!
I created a simple script to do this outside of Magento. Be sure to test this first on a single product and make sure it looks as you'd expect.
// Load Magento
require_once 'path/to/app/Mage.php';
Mage::app();
// $productIds is an array of the products you want to modify.
// Create it however you want, I did it like this...
$productsIds = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', array('like' => 'something'))
->getAllIds();
// Array of category_ids to add.
$newCategories = array(20);
foreach ($productIds as $id) {
$product = Mage::getModel('catalog/product')->load($id);
$product->setCategoryIds(
array_merge($product->getCategoryIds(), $newCategories)
);
$product->save();
}
If you wish to overwrite a product's existing categories, change array_merge(...) to just $newCategories.
I would shy away from tackling this problem from the database side of things. If you do go that direction make sure and take lots of backups and do it during low usage.
The following thread on the Magento forum identifies the very same problem. One poster recommends a raw sql approach with example. Again, I would be careful - make sure you take backups.
The answer I like best from the thread (posted by Magento MVP):
Go into the category you don’t want them in, find the product list.
Click the check boxes on the products you want to remove and select
delete from the little dropdown.
Now go into the category where you
do want them, go to the product list. Select the NO dropdown so it
shows items not in the category. You might have to do a selective
search to limit stuff and do it in a couple iterations. Click the
check boxes and tell it to add stuff.
You may as well do this using the magento API
This is the script I use for mass adding products. sku.txt contains one sku per line.
<?php
$wsdlUrl = "magento-root/index.php/api/soap/?wsdl";
$proxy = new SoapClient($wsdlUrl);
$sessionId = $proxy->login('apiuser', 'apipasswd');
$listOfDiscountedSKUFile = "sku.txt";
function readinFile($filePath)
{
$fp = fopen($filePath,'r') or exit("Unable to open file!");
$dataItems = array();
while(!feof($fp))
{
$dataItems[] = trim(fgets($fp));
}
fclose($fp);
var_dump($dataItems);
return $dataItems;
}
function addToCategory($sku,$categoryId)
{
global $proxy,$sessionId;
$proxy->call($sessionId, 'category.assignProduct', array($categoryId, $sku));
}
function IsNullOrEmptyString($question){
return (!isset($question) || trim($question)==='');
}
$categoryId = 82;//e.g.
$listOfSKU = readinFile($listOfDiscountedSKUFile);
foreach($listOfSKU as $sku)
{
addToCategory($sku,$category);
}
?>
I managed to resolve the problem with the following code :
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$x = 1171;
$y = 2000;
$categoryID = 4;
$productPosition = 0;
while($x <= $y) {
$write->query("REPLACE INTO `catalog_category_product` (`category_id`, `product_id`, `position`) VALUES ($categoryID, $x++, $productPosition)");
}
echo "The job is done";
?>
I hope the code is clear for everyone,if it's not,reply and i'll try to explain it.
#nachito : here it is.

Duplicating a product with Code in Magento

I am trying to write a custom module which is capable of duplicating a product into multiple products with only varying SKU. I have tried using function duplicate() under /app/code/core/Mage/Catalog/Model/Product.php in my custom module. But its not working.
I am using the below code in my custom Obesrever.php file to duplicate, but duplication is not occuring
$product = $observer->getEvent()->getProduct();
$newProduct = $product->duplicate();
can anyone suggest me any links to do this or any code format would be helpful.
Thanks
It would be great if you can post the complete function that you are trying to debug or create duplicate products and config.xml (where you are trying to call the event).
Below code works for me in CE 1.9.2.2 without any problems. This function does the following tasks:
Creates duplicate of the original product
Sets the stock to "In Stock" and Qty to "100" (hard coded for now)
Automates reindexing
public function indexAction() //change the function name
{
$productId = $observer->getEvent()->getProduct()->getId();
$productObject = Mage::getModel('catalog/product');
$_product = $productObject->load($productId);
$newProduct = $_product->duplicate();
//new product status is disabled - to view in the frontend you will need to set the status as enabled
$newProduct->setStatus(1);
$newProduct->setName('Duplicate-' . $_product->getName());
$newProduct->setSku('value-' . $productId);
$newProduct->setWebsiteIds($_product->getWebsiteIds());
//set the product stock and qty to display product in the frontend
//while creating duplicate product, it will update the new product to have qty 0 and out of stock
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($newProduct->getId());
if ($stockItem->getId() > 0 && $stockItem->getManageStock())
{
$qty = 100;
$stockItem->setQty($qty);
$stockItem->setIsInStock((int)($qty > 0));
$stockItem->save();
}
$newProduct->getResource()->save($newProduct);
//automate reindexing - to display the product in the frontend
$indexers = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach ($indexers as $indexer)
{
$indexer->reindexEverything();
}
}
Hope this helps.
Happy Coding...

Resources