Magento set product image for multistore view programatically - image

There i am creating a product dynamically from a Helper function. this creates fine. and set image work fine for default store view. but for multistore view, image not selected as 'thumbnail', 'small_image' or 'image'.
$product = new Mage_Catalog_Model_Product();
// Build the product
//$product->setSku('pkg-sku-1');
$product->setAttributeSetId(4); //default attribute-set
$product->setTypeId('simple');
$product->setName($pkg_data['pkg_name']);
$product->setCategoryIds(array(7)); # some cat id's, my is 7
$product->setWebsiteIDs(array(1)); # Website id, my is 1 (default frontend)
$product->setDescription('EventPackageForOrder');
$product->setShortDescription($pkg_id);
$product->setPrice($pkg_data['pkg_price']); # Set some price
//Default Magento attribute
$product->setWeight(4.0000);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
$product->setStatus(1);
$product->setTaxClassId(2); # Taxable goods
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 5
));
$im_url_path = Mage::getBaseUrl('media').'eventdiscpkgs/event_logo.jpeg';
$im_absolute_path = Mage::getBaseDir('media') . DS . 'eventdiscpkgs/event_logo.jpeg';
$product->setMediaGallery (array('images'=>array (), 'values'=>array ()));
$product->addImageToMediaGallery($im_absolute_path, array ('thumbnail'), false, false);
$product->addImageToMediaGallery($im_absolute_path, array ('small_image'), false, false);
$product->addImageToMediaGallery($im_absolute_path, array ('image'), false, false);
$product->setHasOptions(true);
$product->setCreatedAt(strtotime('now'));
try {
$product->save();
}
catch (Exception $ex) {
$ex->getMessage();
}
ANY Idea where i can change.

Try to assign image for each store id:
foreach($product->getStoreIds() as $storeId) {
$product->setStoreId($storeId)
->setImage($im_absolute_path)
->setSmallImage($im_absolute_path)
->setThumbnail($im_absolute_path);
$product->save()
}

Related

Magento2 product import pragmatically i want skip images if not present on csv?

I am trying to upload product pragmatically through CSV all script run well but i have only 1 issue i have 3 column of images in my CSV 1st images are available but in 2nd and 3rd column some images are missing name are present but images are not found in directory but when i run script only one images are save rest of present images are not saved
My Code is
<?php
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$objectManager1 = Magento\Framework\App\ObjectManager::getInstance();
$directoryList = $objectManager1->get('\Magento\Framework\App\Filesystem\DirectoryList');
$path = $directoryList->getPath('media');
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$myarray = glob("test.csv");
usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));
if(count($myarray)){
$csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1]));
array_walk($csv_map, function(&$a) use ($csv_map) {
$a = array_combine($csv_map[0], $a);
});
array_shift($csv_map);
$message = '';
$count = 1;
foreach($csv_map as $data){
//echo '<pre>';print_r($data);exit;
$product = $objectManager->create('Magento\Catalog\Model\Product');
$product->setName(trim($data['NAME']));
$product->setTypeId('simple');
$product->setAttributeSetId(4);
$product->setSku(trim($data['MODEL NUMBER']));
$product->setUrlPath(trim($data['url']).trim($data['MODEL NUMBER']).('zenith'));
$product->setWebsiteIds(array(1));
$product->setVisibility(4);
$product->setBrand(trim($data['BRAND']));
$product->setFunctions(trim($data['FUNCTIONS']));
$product->setPowerReserve(trim($data['POWER RESERVE']));
$product->setStrapType(trim($data['STRAP TYPE']));
$product->setWarranty(trim($data['WARRANTY']));
$product->setFamily(trim($data['FAMILY']));
$product->setWaterResistance(trim($data['WATER RESISTANCE']));
$product->setCreatedAt(strtotime('now'));
$product->setPrice(trim($data['PRICE']));
$product->setcaseSize(trim($data['CASE SIZE']));
//$product->setColor(trim($data['dial_colour']));
$product->setMovement(trim($data['MOVEMENT']));
$product->setCaseShape(trim($data['CASE SHAPE']));
//$product->setGender(trim($data['gender']));
$product->setCaseMaterial(trim($data['CASE MATERIAL']));
//$_product->setShortDescription(trim($data['Short Description'])); // add text attribute
//$_product->setDescription(trim($data['Long Description'])); // add text attribute
$img_url = trim($data['IMAGE1']);
$img_url1=trim($data['IMAGE2']);
$img_url2=trim($data['IMAGE3']);
$dir = $directoryList->getPath('media').'/big/';
$imgpath = $dir.$img_url;
$imgpath1 = $dir.$img_url1;
$imgpath2 = $dir.$img_url2;
$product->addImageToMediaGallery($imgpath, array('image'), false, false);
if (file_exists($dir.$img_url1)) {
$product->addImageToMediaGallery($imgpath1, array('thumbnail'), false, false);
}
if (file_exists($dir.$img_url2)) {
$product->addImageToMediaGallery($imgpath2, array('small_image'), false, false);
}
$product->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 100 //qty
)
);
$product->save();
}
echo'sucess';
}
?>
please suggest what i am doing wrong in image section
Check the image existence By
#exif_imagetype($image_path).
Thank you

Programatically duplicated product not displayed on frontend in magento (ver 1.9.0.1)

I use the following script (inside a controller - action for now) for duplicating a product programatically.
public function indexAction()
{
$data = $this->getRequest()->getParams();
$product = Mage::getModel('catalog/product');
$_product = $product->loadByAttribute('sku',$data['prod_sku']);
$clone = $_product->duplicate();
$clone->setSku($data['new_sku']);
$clone->setUrlKey('foo-bar-1');
$qty = 99;
$is_in_stock = 1;
$stockArray = array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'qty' => $qty,
'is_in_stock' => $is_in_stock,
);
$storeid=0; // your store id 0 is for default store id
Mage::getModel('catalog/product_status')->updateProductStatus($clone->getId(), $storeid, Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
$clone->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
try{
$clone->getResource()->save($clone);
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($clone->getId());
foreach($stockArray as $key => $val){
$stockItem->setData($key, $val);
}
$stockItem->save();
} catch(Exception $e){
Mage::log($e->getMessage());
}
echo "new product ID is ".$clone->getId();
}
This works well and the product gets duplicated with supplied SKU and overwritten prices from a form.
I can see the product in product grid in admin panel.
Visibility is set to Catalog, Search
Product is in stock
Enabled and tagged to correct category and website.
Most probably, you can not see product on frontend, because it is not available in needed website. Provided code can be executed correctly only in admin area (in frontend controller "Warning: Invalid argument supplied for foreach() in app/code/core/Mage/Eav/Model/Entity/Abstract.php on line 1180" will be generated), so code: Mage::app()->getStore(true)->getWebsite()->getId() returned 0, that can not be correct website for frontend.
You should replace line:
$clone->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
with
$clone->setWebsiteIds($_product->getWebsiteIds());

Adding magento product from frontend with attributes

How to add product from frontend with custom attributes ?
I have this code form another stack question
//$product = Mage::getModel('catalog/product');
$product = new Mage_Catalog_Model_Product();
echo time();
// Build the product
$product->setAttributeSetId(9);// #4 is for default
$product->setTypeId('simple');
$product->setName('Some cool product name');
$product->setDescription('Full description here');
$product->setShortDescription('Short description here');
$product->setSku(time());
$product->setWeight(4.0000);
$product->setStatus(1);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);//4
print_r(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$product->setPrice(39.99);// # Set some price
$product->setTaxClassId(0);// # default tax class
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));
$product->setCategoryIds(array(27));// # some cat id's,
$product->setWebsiteIDs(array(1));// # Website id, 1 is default
//Default Magento attribute
$product->setCreatedAt(strtotime('now'));
//print_r($product);
try {
$product->save();
echo "Product Created";
}
catch (Exception $ex) {
//Handle the error
echo "Product Creation Failed";
}
But i have custom attributes also , and how to add them from that code.
For each attribute you have you need to call:
$product->setData('attribute_code_here', 'Value here');
[Edit]
For yes/no attributes do it like this:
$product->setData('attribute_code_here', 1); //1 for Yes, 0 for No
For multiple selects
$product->setData('attribute_code_here', "4,6,12"); //the ids of the values concatenated by comma.
First add a product with all attributes per hand into your Magento, so that you can figure out how Magento uses them. Load that Product and print_r all variables, then use them to save a new product.
$_product = Mage::getModel('catalog/product')->load('PRODUCT ID');
Zend_Debug::dump($_product);
Get All the Attributes you need to save a new Product and do that:
$_product = Mage::getModel('catalog/product');
$_product->setYourAttribute('...');
$_product->save();

Set product gallery images to base , thumbnail and small image Magento

Hi i am working on the site in which i need to add the products from the frontend , for that i am using the following code
<?php //$product = Mage::getModel('catalog/product');
$product = new Mage_Catalog_Model_Product();
echo time();
// Build the product
$product->setAttributeSetId(4);// #4 is for default
$product->setTypeId('simple');
$product->setName('Some cool product name');
$product->setDescription('Full description here');
$product->setShortDescription('Short description here');
$product->setSku(2);
$product->setWeight(4.0000);
$product->setStatus(1);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);//4
print_r(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$product->setPrice(39.99);// # Set some price
$product->setTaxClassId(0);// # default tax class
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));
$product->setCategoryIds(array(3));// # some cat id's,
$product->setWebsiteIDs(array(1));// # Website id, 1 is default
//Default Magento attribute
$product->setCreatedAt(strtotime('now'));
// Add three image sizes to media gallery
$mediaArray = array(
'thumbnail' => "me.jpg",
'small_image' => "me.jpg",
'image' => "me.jpg",
);
// Remove unset images, add image to gallery if exists
$importDir = Mage::getBaseDir('media') . DS . 'import/';
foreach($mediaArray as $imageType => $fileName) {
$filePath = $importDir.$fileName;
if ( file_exists($filePath) ) {
try {
$product->addImageToMediaGallery($filePath, $imageType, false);
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
echo "Product does not have an image or the path is incorrect. Path was: {$filePath}<br/>";
}
}
//print_r($product);
try {
$product->save();
echo "Product Created";
}
catch (Exception $ex) {
//Handle the error
echo "Product Creation Failed";
}
?>
this is working fine , but there is one problem
it doesn’t set the image to base default and small image.
It Added the images for the product but the checkbox in front of image
is not selected . I need to check the boxes .Please suggest where i am doing mistake.
thanks
Add
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
before
foreach($mediaArray as $imageType => $fileName) {

Update products programmatically in Magento

I'm working on a script that will create or update products in my catalog.
The script works fine when the product needs to be created, but it fails when the product already exists in the database giving me (many times) the following messages :
2011-09-30T08:00:53+00:00 ERR (3): Recoverable Error: Argument 3
passed to
Mage_Catalog_Model_Resource_Eav_Mysql4_Abstract::_canUpdateAttribute()
must be an array, null given, called in ...
2011-09-30T08:00:53+00:00
ERR (3): Recoverable Error: Argument 3 passed to
Mage_Eav_Model_Entity_Abstract::_canUpdateAttribute() must be an
array, null given, called in ...
2011-09-30T08:00:53+00:00 ERR (3):
Warning: array_key_exists() [function.array-key-exists]: The
second argument should be either an array or an object in ...
I've been looking at the method quoted in the message, but I can't find any reason why the script fails.
The script first try to load a product using :
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
and then test if the product was retrieved using a simple if(!$product) { //creation }.
All the code that follow the if statement is shared for creation or update and consists of setter calls on product object.
Here is the code I use :
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
if(!$product) {
// the product doesn't exist yet
$product = new Mage_Catalog_Model_Product();
$product->setSku($sku);
$product->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE);
$product->setCreatedAt(strtotime('now'));
}
// setters calls
$product->setTeinte(trim((string)$record->web_teinte));
// ...
// finally save the product
$product->save();
Maybe someone has already faced the same problem.
Any help is welcome ! Thank you.
Chances are, in your "setter calls" you are trying to set something that cannot be directly set on $product. It could even be the "setTeinte" as I am not sure what that is trying to set. But as we cannot see all your code, it is a little difficult to say, so as I guide, take a look at the code below, which sets some information directly on the product and then stock levels. It does therefore, illustrate how certain data has to be set. I hope it helps.
$SKU = (string)$XMLproduct->Sku;
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$SKU);
if ($product) {
//Product found, so we need to update it in Magento.
$product->setName((string)$XMLproduct->Name);
$product->setPrice((real)$XMLproduct->SalePrice);
//$product->setDescription((string)$XMLproduct->LongDescription);
//$product->setShortDescription((string)$XMLproduct->Description);
$product->save();
$productId = $product->getId();
$stockItem =Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$stockItemId = $stockItem->getId();
$stockItem->setData('manage_stock', 1);
$stockItem->setData('qty', (integer)$XMLproduct->QtyInStock);
$stockItem->save();
echo $SKU," Updated: Name: '",(string)$XMLproduct->Name,"', Price: ",(real)$XMLproduct->SalePrice,", Stock level: ",$XMLproduct->QtyInStock,PHP_EOL;
$updated++;
}
Adding Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); before saving product solves the error. The sample code below updates product's cost.
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$productId = 160;
$newCost = 80;
$product = Mage::getModel('catalog/product')->load($productId);
$product->setCost($newCost)->save();
//here what i use in codeigniter
function updateProducts(){
$params = array('name' => 'adminhtml'); // frontend or adminhtml
$this->load->library('magento', $params);
error_reporting(E_ALL | E_STRICT);
//$mageFilename = 'app/Mage.php';
//require_once $mageFilename;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$obj = new stdClass();
$obj->Sku = '25484684';
$obj->Name = 'test product 2';
$obj->SalePrice = 55;
$obj->LongDescription = 'test product long decription.test product long decription.test product long decription.';
$obj->Description = 'short descrption';
$res = $this->updateMagentoProduct($obj);
//dumb($res);
}
function updateMagentoProduct($XMLproduct){
$SKU = (string)$XMLproduct->Sku;
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$SKU);
if (!$product) {//insert new product
$product = Mage::getModel('catalog/product');
$product->setSku($SKU);
}
//$product = new Mage_Catalog_Model_Product();
// Build the product
$product->setAttributeSetId(4); // 4 means Default AttributeSet
$product->setTypeId('simple');
$product->setName((string)$XMLproduct->Name);
$product->setCategoryIds(array(2,3,4,5,6,7));
$product->setWebsiteIDs(array(1)); # Website id, 1 is default
//$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
//$product->setWebsiteIDs(array(1)); # Website id, my is 1 (default frontend)
$product->setDescription((string)$XMLproduct->LongDescription);
$product->setShortDescription((string)$XMLproduct->Description);
$product->setPrice((real)$XMLproduct->SalePrice);
# Custom created and assigned attributes
//$product->setHeight('my_custom_attribute1_val');
//$product->setWidth('my_custom_attribute2_val');
//$product->setDepth('my_custom_attribute3_val');
//$product->setType('my_custom_attribute4_val');
//Default Magento attribute
$product->setWeight(1.0);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$product->setStatus(1);
$product->setTaxClassId(0); # My default tax class
/*$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));*/
$product->setCreatedAt(strtotime('now'));
try {
$product->save();
$productId = $product->getId();
$stockItem =Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$stockItemId = $stockItem->getId();
$stockItem->setData('manage_stock', 1);
$stockItem->setData('qty', 99999);//(integer)$XMLproduct->QtyInStock
$stockItem->save();
echo '<h5>'.$SKU," Updated: Name: '",(string)$XMLproduct->Name,"', Price: ",(real)$XMLproduct->SalePrice,", Stock level: ",PHP_EOL.'</h5>';
}
catch (Exception $ex) {
//Handle the error
echo '<h5>'.$ex->getMessage().'</h5>';
}
// assign product to the default website
return $product->save();
}
Easy with Magento API,
also can use methods....
example
$data = array('qty'=>1, 'is_in_stock'=>1)
$stockModel = new Mage_CatalogInventory_Model_Stock_Item_Api;
$stockModel->update($product_id, $data);
Also can set Admin mode
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
<?php
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
$product
// ->setStoreId(1) //you can set data in store scope
->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
->setAttributeSetId(9) //ID of a attribute set named 'default'
->setTypeId('simple') //product type
->setCreatedAt(strtotime('now')) //product creation time
// ->setUpdatedAt(strtotime('now')) //product update time
->setSku('testsku61') //SKU
->setName('test product21') //product name
->setWeight(4.0000)
->setStatus(1) //product status (1 - enabled, 2 - disabled)
->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
->setManufacturer(28) //manufacturer id
->setColor(24)
->setNewsFromDate('06/26/2014') //product set as new from
->setNewsToDate('06/30/2014') //product set as new to
->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
->setPrice(11.22) //price in form 11.22
->setCost(22.33) //price in form 11.22
->setSpecialPrice(00.44) //special price in form 11.22
->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
->setMsrpEnabled(1) //enable MAP
->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
->setMsrp(99.99) //Manufacturer's Suggested Retail Price
->setMetaTitle('test meta title 2')
->setMetaKeyword('test meta keyword 2')
->setMetaDescription('test meta description 2')
->setDescription('This is a long description')
->setShortDescription('This is a short description')
->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
->addImageToMediaGallery('media/catalog/product/1/0/10243-1.png', array('image','thumbnail','small_image'), false, false) //assigning image, thumb and small image to media gallery
->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock'=>1, //manage stock
'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 999 //qty
)
)
->setCategoryIds(array(3, 10)); //assign product to categories
$product->save();

Resources