I use cron to import products in the database. Products are imported but the association between configurable products and simple products is not done correctly. The association is done every new product but at the end, only the last product imported remains. Please find the function I use below.
==EDIT==
This function is under community>Bmservices>Polaris>Model>Observer
It is called by a cron defined in config.xml that work. I am sure that the function is called as I am logging in it and the log is filling with the proper information.
==END OF EDIT==
I get the $line from csv.
private function _importProduct($line){
$utf8bom = "\xef\xbb\xbf";
$rayon = $this->_checkCategory($line[21]+2, $line[22]);
$famille = $this->_checkCategory($line[23], $line[24], $rayon);
$sousfamille = $this->_checkCategory($line[25], $line[26], $famille);
$idManu = $this->_checkAttribute($line[5], $line[27], $this->_attributManufacturer);
$idSais = $this->_checkAttribute($line[15], $line[28], $this->_attributSaison);
$idColl = $this->_checkAttribute($line[16], $line[29], $this->_attributCollection);
$idMati = $this->_checkAttribute($line[11], $line[35], $this->_attributMatiere);
$idCoul = $this->_checkAttribute($line[3], $line[20], $this->_attributCouleur);
$idTail = $this->_checkAttribute($line[4], $line[42], $this->_attributTaille, $line[43]);
$idAttS = $this->_checkAttributeSet($line[49], $line[50]);
$product = Mage::getModel('catalog/product');
$sku = trim($line[0], $utf8bom);
$sku = trim($sku, '"');
$product->loadByAttribute('sku',$sku);
$id = $product->getId();
if (empty($id)){
Mage::log("nouveau produit avec le sku $sku");
$product->setStoreId(1);
$product->setSku($sku);
$product->setAttributeSetId($idAttS);
$product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
}
if ($line!=''){
$product->setName($line[18]);
} else {
$product->setName($line[17]);
}
$product->setDescription($line[19]);
$product->setCreatedAt($line[41]);
$product->setShortDescription($line[19]);
$product->setData('collecannee', $idColl);
$product->setData('matiere', $idMati);
$product->setData('manufacturer', $idManu);
$product->setData('saison', $idSais);
$product->setMetaKeyword($line[22].','.$line[24].','.$line[26].','.$line[27].','.$line[28]);
$product->setMetaTitle($line[18]);
$product->setMetaDescription($line[19]);
$product->setWeight(0);
$product->setData('price',$line[47]);
$product->setCategoryIds(array($rayon, $famille, $sousfamille));
$product->setFinalPrice($line[47])
->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
->setMsrpEnabled(0) //enable MAP
->setMsrpDisplayActualPriceType(4) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
->setMsrp($line[47]); //Manufacturer's Suggested Retail Price
if ($line[48]!=''){
$product->setSpecialPrice($line[48]);
$product->setSpecialFromDate('2014-08-01');
$product->setSpecialFromDateIsFormated(true);
$product->setSpecialToDate('2014-08-30');
$product->setSpecialToDateIsFormated(true);
} else {
$product->setSpecialPrice(null);
}
$product->setTaxClassId(2);
if ((!isset($this->_productConf))||($this->_productConf->getSku()!='C-'.$line[2])){
if ((isset($this->_productConf))&&($this->_productConf->getSku()!='C-'.$line[2])){
$this->_productConf->setConfigurableProductsData($this->_configurableProductsData);
$this->_productConf->save();
}
$this->_productConf = Mage::getModel('catalog/product');
$skuConf = 'C-'.$line[2];
$this->_productConf->loadByAttribute('sku',$skuConf);
$this->_configurableProductsData = array();
$idConf = $this->_productConf->getId();
if (empty($idConf)){
Mage::log('Création d\'un produit configurable : '.$skuConf);
$this->_productConf->setData($product->getData());
$this->_productConf->setTypeId('configurable');
$this->_productConf->setData('size', NULL);
$this->_productConf->setData('color', NULL);
$attribute_ids = array($this->_attributTaille, $this->_attributCouleur);
$this->_productConf->getTypeInstance()->setUsedProductAttributeIds($attribute_ids);
$configurableAttributesData = $this->_productConf->getTypeInstance()->getConfigurableAttributesAsArray();
$this->_productConf->setCanSaveConfigurableAttributes(true);
$this->_productConf->setConfigurableAttributesData($configurableAttributesData);
$StockData['manage_stock'] = 1;
$StockData['is_in_stock'] = 1;
$StockData['use_config_manage_stock'] = 0;
$StockData['use_config_min_qty'] = 0;
$this->_productConf->setStockData($StockData);
$this->_productConf->setCanSaveConfigurableAttributes(true);
$this->_productConf->setCanSaveCustomOptions(true);
$this->_productConf->setSku($skuConf);
$this->_productConf->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
}
}
$StockData['qty'] = floatval($line[46]);
$StockData['is_in_stock'] = ($StockData['qty']>0) ? 1 : 0;
$StockData['manage_stock'] = 1;
$StockData['use_config_manage_stock'] = 0;
$StockData['use_config_min_qty'] = 0;
$product->setStockData($StockData);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
$product->setData('size', $idTail);
$product->setData('color', $idCoul);
Mage::log("sauvegarde du produit");
$product->validate();
$product->save();
/**
* mise à jour du prix et de la classe de taxe
*/
Mage::getSingleton('catalog/product_action')->updateAttributes(
array($product->getId()),
array(121 => 2, 75 => $line[47]),
0
);
/**
* gestion du stock
*/
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
$stockItemId = $stockItem->getId();
$stock = array();
if (!$stockItemId) {
$stockItem->setData('product_id', $product->getId());
$stockItem->setData('stock_id', 1);
} else {
$stock = $stockItem->getData();
}
foreach($StockData as $field => $value) {
$stockItem->setData($field, $value?$value:0);
}
$stockItem->save();
$this->_configurableProductsData[$product->getId()] = array( //['920'] = id of a simple product associated with this configurable
'0' => array(
'label' => $line[20], //attribute label
'attribute_id' => $this->_attributCouleur, //attribute ID of attribute 'color' in my store
'value_index' => $idCoul, //value of 'Green' index of the attribute 'color'
'is_percent' => '0', //fixed/percent price for this option
'pricing_value' => $line[47] //value for the pricing
),
'1' => array(
'label' => $line[42], //attribute label
'attribute_id' => $this->_attributTaille, //attribute ID of attribute 'color' in my store
'value_index' => $idTail, //value of 'Green' index of the attribute 'color'
'is_percent' => '0', //fixed/percent price for this option
'pricing_value' => $line[47] //value for the pricing
)
);
}
Is there something I miss.
I found my mistake and I could not believe it got me stuck for more than a week. In case somebody encounter the same issue, the answer lies in the website ids. I did not affect any so the product did not exist in any store so it was affected but not visible on the product page. I can not explain why I had it on admin and in the database but now everything is ok.
Related
I am using below piece of code
$configurable= Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$simpleCollection = $configurable->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
$productAttributeOptions = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);
$attributeOptions = array();
foreach ($productAttributeOptions as $productAttribute) {
foreach ($productAttribute['values'] as $attribute) {
$attributeOptions[$productAttribute['label']][] =
array('id' => $attribute['value_index'],
'label' => $attribute['label'],
'mainId' => $productAttribute['attribute_id'] );
}
}
return $attributeOptions;
but it gives me list of all simple product even those are not available in stock.
I just want list of simple product of a configurable product those are in stock.
How can i get only in stock products of a configurable product
You can check product stock status 0- not in stock or 1 - in stock
$configurable= Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$simpleCollection = $configurable->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
/* -------- Add this ------- */
$simpleCollection->getSelect()->join('cataloginventory_stock_status', 'cataloginventory_stock_status.product_id = e.entity_id', array('stock_status'));
$simpleCollection->getSelect()->where("`cataloginventory_stock_status`.`stock_status` = 1");
$productAttributeOptions = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);
$attributeOptions = array();
foreach ($productAttributeOptions as $productAttribute) {
foreach ($productAttribute['values'] as $attribute) {
$attributeOptions[$productAttribute['label']][] =
array('id' => $attribute['value_index'],
'label' => $attribute['label'],
'mainId' => $productAttribute['attribute_id'] );
}
}
return $attributeOptions;
I facing issue while creating configurable product in Magento 2.1 programmatically. I'm reading products from xml and save. The issue is when i associate simple product with configurable product. Products are created successfully. But configurable product associated products are not shown on backend. Here is my code:
<?php
/**
* Created by PhpStorm.
* User: Muhammad Noman Rauf
* Date: 15/12/2016
* Time: 1:15 AM
*/
use Magento\Framework\App\Bootstrap;
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (file_exists('Export_Products_20170104_152014.xml')) {
$content = simplexml_load_file('Export_Products_20170104_152014.xml', 'SimpleXMLElement', LIBXML_NOCDATA);
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$_categoryFactory = $objectManager->get('Magento\Catalog\Model\CategoryFactory');
$url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');
$mediaurl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
/// Get Website ID
$websiteId = $storeManager->getWebsite()->getWebsiteId();
/// Get Store ID
$store = $storeManager->getStore();
$storeId = $store->getStoreId();
/// Get Root Category ID
$rootNodeId = $store->getRootCategoryId();
/// Get Root Category
$rootCat = $objectManager->get('Magento\Catalog\Model\Category');
$cat_info = $rootCat->load($rootNodeId);
$product = $objectManager->get('Magento\Catalog\Model\Product');
foreach ($content as $key => $value) {
echo "<pre>";
$_product = $objectManager->create('Magento\Catalog\Model\Product');
//print_r($value->images);
$sku = $value->ID;
$name = $value->name;
$description = $value->commercial_desc;
$catgory = $value->category;
$color = array();
if (isset($value->prices) && !empty($value->prices)) {
foreach ($value->prices->pricelist as $k => $v):
$vn = (array)$v;
ksort($vn);
if ($vn['currency'] == 'EUR') {
$price = $vn['price'];
}
endforeach;
}
if (isset($value->images) && !empty($value->images)) {
foreach ($value->images->img_url as $k => $v):
$v;
endforeach;
}
if (isset($value->colors) && !empty($value->colors)) {
foreach ($value->colors->color as $k => $v):
$color[] = $v->Description;
foreach ($v->sizes->size as $sizes => $size) {
$s = $size->ID;
}
if (isset($v->images) && !empty($v->images->img_url)) {
foreach ($v->images->img_url as $imgs => $img) {
$color_img = $img;
}
}
endforeach;
}
$collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name', $catgory);
if ($collection->getSize()) {
$categoryId = $collection->getFirstItem()->getId();
$categoryId;
} else {
$name = ucfirst($catgory);
$url = strtolower($catgory);
$cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
/// Add a new sub category under root category
$categoryTmp = $_categoryFactory->create();
$categoryTmp->setName($name);
$categoryTmp->setIsActive(true);
$categoryTmp->setUrlKey($cleanurl);
$categoryTmp->setData('description', $catgory);
$categoryTmp->setParentId(2);
$categoryTmp->setStoreId($storeId);
$categoryTmp->setPath($rootCat->getPath());
$categoryTmp->save();
$categoryId = $categoryTmp->getId();
}
if ($product->getIdBySku($sku)) {
echo "already in database " . $sku . " Please change name and sku in xml file.";
continue;
} else {
/** #var \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepo */
$attributeRepo = $objectManager->get(\Magento\Catalog\Api\ProductAttributeRepositoryInterface::class);
$attribute = $attributeRepo->get('color'); // color should be in default attribute set
$ids = [];
$values = [];
$_product->setName($name);
$_product->setTypeId('configurable');
$_product->setAttributeSetId(4);
$_product->setSku($sku);
$_product->setDescription($description);
$_product->setShortDescription($description);
$_product->setWebsiteIds(array($websiteId));
$_product->setVisibility(4);
$_product->setPrice($price);
$_product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$_product->setCategoryIds(array($categoryId));
$_product->setImage('img1.jpg');
$_product->setSmallImage('img1.jpg');
$_product->setThumbnail('img1.jpg');
$_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();
foreach ($attribute->getOptions() as $option) {
$label = $option->getLabel();
if (in_array($label, $color)) {
$id = $option->getValue();
/** #var \Magento\Catalog\Api\Data\ProductInterface $p */
$p = $objectManager->create('Magento\Catalog\Model\Product');
$p->setSku($sku . '-' . $option->getLabel());
$p->setName($sku . '-' . $option->getLabel());
$p->setPrice($price);
$p->setTypeId('virtual');
$p->setColor($option->getValue());
$p->setWebsiteIds(array($websiteId));
$p->setCategoryIds(array($categoryId));
$p->setAttributeSetID($id);
$p->setVisibility(Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE);
$p->setAttributeSetId(4);
$p->save();
$ids[] = $p->getId();
/** #var \Magento\ConfigurableProduct\Api\Data\OptionValueInterface $opVal */
$opVal = $objectManager->create(\Magento\ConfigurableProduct\Api\Data\OptionValueInterface::class);
$opVal->setValueIndex($id);
$values[] = $opVal;
}
}
/* IF CODE NOT WORKED PLEASE REMOVE THIS CODE : START REMOVE*/
$pro = $objectManager->create('Magento\Catalog\Model\Product')->load($_product->getId()); // Load Configurable Product
$attributeModel = $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute');
$position = 0;
$attributes = array($attribute->getAttributeId()); // Super Attribute Ids Used To Create Configurable Product
foreach ($attributes as $attributeId) {
$data = array('attribute_id' => $attributeId, 'product_id' => $_product->getId(), 'position' => $position);
$position++;
$attributeModel->setData($data)->save();
}
$pro->setTypeId("configurable"); // Setting Product Type As Configurable
$pro->setAffectConfigurableProductAttributes(4);
$objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->setUsedProductAttributeIds($attributes, $pro);
$pro->setNewVariationsAttributeSetId(4); // Setting Attribute Set Id
$pro->setAssociatedProductIds($ids);// Setting Associated Products
$pro->setCanSaveConfigurableAttributes(true);
$pro->save();
/* IF CODE NOT WORKED PLEASE REMOVE THIS CODE : END REMOVE*/
echo "New Product id:" . $_product->getId() . '<br>';
}
//print_r($_product->getData());
}
} else {
exit('Failed to open xml.');
}
I also followed other solution but can't find any solution.
link 1
link2
link3
Do not forget to use store id in your import.
Set store ID "0".
public function setConfigurable_oldfunc($config_id,$simple_prod_id){
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$store = $storeManager->getStore(0);
$storeManager->setCurrentStore($store->getCode());
$productId = $config_id; // Configurable Product Id
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId); // Load Configurable Product
$attributeModel = $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute');
$position = 0;
$attributes = array(160); // Super Attribute Ids Used To Create Configurable Product
$associatedProductIds = array($simple_prod_id);
$optionsData = $product->getTypeInstance(true)->getUsedProducts($product);
$array_ids = array();
if(is_array($array_ids) && !empty($array_ids)){
}else{
foreach ($attributes as $attributeId) {
$data = array('attribute_id' => $attributeId, 'product_id' => $productId, 'position' => $position);
$position++;
$attributeModel->setData($data)->save();
}
}
$objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->setUsedProductAttributeIds($attributes, $product);
$product->setTypeId("configurable"); // Setting Product Type As Configurable
$product->setAffectConfigurableProductAttributes(4);
$product->setNewVariationsAttributeSetId(4); // Setting Attribute Set Id
$product->setAssociatedProductIds($associatedProductIds);// Setting Associated Products
$product->setCanSaveConfigurableAttributes(true);
$product->setStoreId(0);
$product->save();
}
<?php
/**
* #author stw
* #website http://stw-services.com/
*
*/
header('Content-Type: text/csv; charset=utf-8');
require_once("app/Mage.php");
Mage::app('default');
/*$csv_file = "juliajune_erp/import/products/products.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
*/
$row = 0;
$simple_product_counter=0;
$simple_product_sku[]=array();
$simple_product_color[]=array();
$simple_product_size[]=array();
$path = "juliajune_erp/import/products/export/";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
$latestpath = $path.$latest_filename;
if (($handle = fopen($latestpath, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) {
$num = count($data);
$row++;
if($data[3] == 'simple')
{
$simpleProduct = Mage::getModel('catalog/product');
try {
//echo "set attribute:-".$data[2];echo "<br>";
//$simpleProduct->setAttributeSetId(4); //ID of a attribute set named 'default'
if($data[2]=='Default'){$attribute_set_id=4;}
$simpleProduct->setAttributeSetId($attribute_set_id); //ID of a attribute set named 'default'
//echo "product type:-".$data[3];echo "<br>";
$simpleProduct->setTypeId($data[3]); //product type
//echo "created time:-".$data[11];echo "<br>";
$simpleProduct->setCreatedAt($data[11]); //product creation time
//echo "sku:-".$data[0];echo "<br>";
$simpleProduct->setSku($data[0]); //SKU
//echo "name:-".$data[36];echo "<br>";
$simpleProduct->setName($data[36]); //product name
//echo "weight:-".$data[59];echo "<br>";
$simpleProduct->setWeight($data[59]);
//echo "status:-".$data[50];echo "<br>";
$simpleProduct->setStatus($data[50]); //product status (1 - enabled, 2 - disabled)
//echo "tax class id:-".$data[51];echo "<br>";
$simpleProduct->setTaxClassId($data[51]); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
//echo "visibility :-".$data[58];echo "<br>";
$simpleProduct->setVisibility($data[58]); //catalog and search visibility
/*----------color------------*/
$attributeColorCode = 'color';
$_product = Mage::getModel('catalog/product');
$attr = $_product->getResource()->getAttribute($attributeColorCode);
if ($attr->usesSource()) { $color_id = $attr->getSource()->getOptionId($data[8]); }
//echo "color :-".$color_id;echo "<br>";
$simpleProduct->setColor($color_id);
/*----------size------------*/
$attributeSizeCode = 'size';
$_product = Mage::getModel('catalog/product');
$attr = $_product->getResource()->getAttribute($attributeSizeCode);
if ($attr->usesSource()) { $size_id = $attr->getSource()->getOptionId($data[44]); }
//echo "size :-".$size_id;echo "<br>";
$simpleProduct->setSize($size_id);
//echo "price:-".$data[41]; echo "<br>";
$simpleProduct->setPrice($data[41]); //price in form 11.22
//echo "msrp enable:-".$data[35];echo "<br>";
$simpleProduct->setMsrpEnabled(2); //enable MAP
//echo "msrp display actual price type:-".$data[34];echo "<br>";
$simpleProduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
//echo "description:-".$data[20];echo "<br>";
$simpleProduct->setDescription($data[20]);
//echo "short description:-".$data[43];echo "<br>";
$simpleProduct->setShortDescription($data[43]);
$mediaArray_simple = array('thumbnail' => $data[52],'small_image' => $data[45],'image' => $data[25]);
$importDir_images = Mage::getBaseDir('media') . DS . 'import/';
//foreach ( $mediaArray_simple as $imageType => $fileName ) {
$fileName = $data[25];
$filePath = $importDir_images.$fileName;
if ( file_exists($filePath) ) {
//$simpleProduct->addImageToMediaGallery($filePath, $imageType, false);
$simpleProduct->addImageToMediaGallery($filePath, array('image','thumbnail','small_image'), false, false);
}
//}
$stockData = $simpleProduct->setStockData(array(
'use_config_manage_stock' => $data[74], //'Use config settings' checkbox
'manage_stock' => $data[73], //manage stock
'is_in_stock' => $data[70], //Stock Availability
'qty' => $data[60] //qty
)
);
//echo "category id:-".$data[4];echo "<br>----------------<br>";
$simpleProduct->setCategoryIds(array('')); //assign product to categories
$simpleProduct->save();
/* using for configurable product */
$simple_product_sku[$simple_product_counter]=$data[0];
$simple_product_color[$simple_product_counter]=$data[8];
$simple_product_size[$simple_product_counter]=$data[44];
$simple_product_counter++;
} catch (Exception $e) {
Mage::log($e->getMessage());
//echo $e->getMessage();
}
}elseif($data[3] == 'configurable'){
$configProduct = Mage::getModel('catalog/product');
try {
//echo "set attribute:-".$data[2];echo "<br>";
//$configProduct->setAttributeSetId(4); //ID of a attribute set named 'default'
if($data[2]=='Default'){$attribute_set_id=4;}
$configProduct->setAttributeSetId($attribute_set_id); //ID of a attribute set named 'default'
//echo "product type:-".$data[3];echo "<br>";
$configProduct->setTypeId($data[3]); //product type
//echo "created time:-".$data[11];echo "<br>";
$configProduct->setCreatedAt($data[11]); //product creation time
//echo "sku:-".$data[0];echo "<br>";
$configProduct->setSku($data[0]); //SKU
//echo "name:-".$data[36];echo "<br>";
$configProduct->setName($data[36]); //product name
//echo "weight:-".$data[59];echo "<br>";
$configProduct->setWeight($data[59]);
//echo "status:-".$data[50];echo "<br>";
$configProduct->setStatus($data[50]); //product status (1 - enabled, 2 - disabled)
//echo "tax class id:-".$data[51];echo "<br>";
$configProduct->setTaxClassId($data[51]); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
//echo "visibility :-".$data[58];echo "<br>";
$configProduct->setVisibility($data[58]); //catalog and search visibility
//echo "price:-".$data[41]; echo "<br>";
$configProduct->setPrice($data[41]); //price in form 11.22
//echo "msrp enable:-".$data[35];echo "<br>";
$configProduct->setMsrpEnabled(2); //enable MAP
//echo "msrp display actual price type:-".$data[34];echo "<br>";
$configProduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
//echo "description:-".$data[20];echo "<br>";
$configProduct->setDescription($data[20]);
//echo "short description:-".$data[43];echo "<br>";
$configProduct->setShortDescription($data[43]);
$mediaArray = array('thumbnail' => $data[52],'small_image' => $data[45],'image' => $data[25]);
$importDir_images = Mage::getBaseDir('media') . DS . 'import/product_images/';
$fileName = $data[36];
$filePath = $importDir_images.$fileName.'.jpg';
if ( file_exists($filePath) ) {
$configProduct->addImageToMediaGallery($filePath, array('image','thumbnail','small_image'), false, false);
}
for($img_i=1;$img_i<=4;$img_i++)
{
$importDir_images = Mage::getBaseDir('media') . DS . 'import/product_images/';
$fileName = $data[36];
$filePath = $importDir_images.$fileName.'_'.$img_i.'.jpg';
if ( file_exists($filePath) ) {
$configProduct->addImageToMediaGallery( $filePath , null, false, false );
}
}
$stockData = $configProduct->setStockData(array(
'use_config_manage_stock' => $data[74], //'Use config settings' checkbox
'manage_stock' => $data[73], //manage stock
'is_in_stock' => $data[70], //Stock Availability
)
);
//echo "category id:-".$data[4];echo "<br>----------------<br>";
$cat_name = substr($data[4], strpos($data[4],'/')+strlen('/'));
$category = Mage::getResourceModel('catalog/category_collection')
->addFieldToFilter('name', $cat_name);
//print_r($category->getData());
$cat_id = $category->getFirstItem()->getEntityId();
$configProduct->setCategoryIds(array(2, 5, $cat_id)); //assign product to categories
/**/
/** assigning associated product to configurable */
/**/
$count_loop = $simple_product_counter;
$config_color_count=0;
$config_size_count=0;
$configurableProductsData=array();
$configurableProductsData_new=array();
$configurableProductsDataSize=array();
$attribute_colorid ="";
for($i=0;$i<$count_loop;$i++)
{
$attributeColorCode = 'color';
$attribute_details = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attributeColorCode);
$attribute = $attribute_details->getData();
$attribute_colorid = $attribute['attribute_id'];
$_product = Mage::getModel('catalog/product');
$attr = $_product->getResource()->getAttribute($attributeColorCode);
if ($attr->usesSource()) { $color_id = $attr->getSource()->getOptionId($simple_product_color[$config_color_count]); }
$current_product_id = Mage::getModel("catalog/product")->getIdBySku( $simple_product_sku[$config_color_count] );
$configurableProductsData[$current_product_id] = array( //['product_id'] = id of a simple product associated with this configurable
'0' => array(
'label' => $simple_product_color[$config_color_count], //attribute label
'attribute_id' => $attribute_colorid, //attribute ID of attribute 'color' in my store
'value_index' => $color_id, //value of 'Green' index of the attribute 'color'
'is_percent' => '0', //fixed/percent price for this option
'pricing_value' => '0' //value for the pricing
)
);
$config_color_count++;
}
for($i=0;$i<$count_loop;$i++)
{
/*color */
$attributeColorCode = 'color';
$attribute_details_color = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attributeColorCode);
$attribute_color = $attribute_details_color->getData();
$attribute_colorid = $attribute_color['attribute_id'];
/*---*/
$attributesizeCode = 'size';
$attribute_details = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attributesizeCode);
$attribute = $attribute_details->getData();
$attribute_sizeid = $attribute['attribute_id'];
$_product = Mage::getModel('catalog/product');
$attr = $_product->getResource()->getAttribute($attributesizeCode);
if ($attr->usesSource()) { $size_id = $attr->getSource()->getOptionId($simple_product_size[$config_size_count]); }
$current_product_id = Mage::getModel("catalog/product")->getIdBySku( $simple_product_sku[$config_size_count] );
$configProduct->getTypeInstance()->setUsedProductAttributeIds(array($attribute_sizeid,$attribute_colorid)); //attribute ID of attribute 'size' in my store
$configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
//$configurableAttributesData[0]['id']=$current_product_id;
//$configurableAttributesData[1]['id']=$current_product_id;
echo "<pre>";print_r($configurableAttributesData);
$configProduct->setCanSaveConfigurableAttributes(true);
$configProduct->setConfigurableAttributesData($configurableAttributesData);
$configurableProductsData_new[$current_product_id] = array( //['920'] = id of a simple product associated with this configurable
'1' => array(
'label' => $simple_product_size[$config_size_count], //attribute label
'attribute_id' => $attribute_sizeid, //attribute ID of attribute 'size' in my store
'value_index' => $size_id, //value of 'Green' index of the attribute 'size'
'is_percent' => '0', //fixed/percent price for this option
'pricing_value' => '0' //value for the pricing
)
);
$config_size_count++;
}
//echo "<pre>";print_r($configurableProductsData_new);
$configProduct->setConfigurableProductsData($configurableProductsData_new);
//echo "<pre>";print_r($configurableProductsData);
$configProduct->setConfigurableProductsData($configurableProductsData);
$configProduct->save();
$simple_product_counter=0;
unset($simple_product_sku);
unset($simple_product_color);
unset($simple_product_size);
echo 'success<br>';
} catch (Exception $e) {
Mage::log($e->getMessage());
echo $e->getMessage();
}
}
}
fclose($handle);
}
/* #var $indexCollection Mage_Index_Model_Resource_Process_Collection */
/*
$indexCollection = Mage::getModel('index/process')->getCollection();
foreach ($indexCollection as $index) {
$index->reindexAll();
}
*/
?>
I have already done importing product pro grammatically and it is display properly with associated product on admin panel of magneto. Also, I have already done re indexing and clear cache but now, I am fetching problem with display product on frontend. If I am just save and continue edit of associated product of configurable product then after re indexing it is display on frontend. please help me to solve this problem
Hi,
I am facing a problem in storing values, at a time in a loop in magento front-end product upload.Values remain same for all stores.Can't figure out how it can be recovered.Please help.
Thanks
$xlsx = new SimpleXLSX($path . DS.$fileName );
list($cols,) = $xlsx->dimension();
foreach( $xlsx->rows() as $k => $r) {
if ($k == 0) continue;//Ingnoring first column of excel file
try{
//grabbing categories for en
$key=array_search($r[55],$cat_arr);
$key2=array_search($r[56],$cat_arr);
$key3=array_search($r[57],$cat_arr);
//grabbing categories for de
$keyde=array_search($r[52],$cat_arr);
$key2de=array_search($r[53],$cat_arr);
$key3de=array_search($r[54],$cat_arr);
//grabbing categories for nl
$keynl=array_search($r[49],$cat_arr);
$key2nl=array_search($r[50],$cat_arr);
$key3nl=array_search($r[51],$cat_arr);
//Set the path of image folder
$imgpath_total="D:\wamp\www\liquor\media\proimg/adidas.jpg";//.$r[59]
$newProduct = new Mage_Catalog_Model_Product();
$newProduct->setAttributeSetId(4)
->setTypeId('simple')
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->setTaxClassId(2)
->setCreatedAt(strtotime('now'))
->setSku($r[39])
->setWeight($r[40])
->setBrand($r[5])
->setTags($r[58])
->setAlc_percentage($r[42])
->setWeight('10')
->setEan($r[37])
->setStatus(1)
->setPrice($r[22])
->setWebsiteIds(array(1))
->setStockData(array('is_in_stock' => 1, 'qty' => 99999 ))
->setSetupFee(522)
->addImageToMediaGallery($imgpath_total,array('image','small_image','thumbnail'),false,false)
->setsetupCost(100)
########En DATA##########
->setName($r[17])
->setTitle_long($r[18])
->setGoogle($r[64])
->setDescription($r[20])
->setShort_description($r[19])
->setCategoryIds(array(2,$key,$key2,$key3))
->setStoreId(1)
########En DATA##########
########de DATA##########
->setName($r[12])
->setTitle_long($r[13])
->setGoogle($r[63])
->setDescription($r[15])
->setShort_description($r[14])
->setCategoryIds(array(2,$keyde,$key2de,$key3de))
->setStoreId(7)
########de DATA##########
########nl DATA##########
->setName($r[7])
->setTitle_long($r[8])
->setGoogle($r[62])
->setDescription($r[10])
->setShort_description($r[9])
->setCategoryIds(array(2,$keynl,$key2nl,$key3nl))
->setStoreId(8);
########nl DATA##########
$newProduct->save();
#####save your product###################
}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;
}
}
Code is here
Found the solution , first I inserted value in default store then by getting the last inserted product id I added rest data for all other available stores.
Sample code:
$insertId=Mage::getSingleton('core/resource')->getConnection('core_read')->fetchOne('SELECT last_insert_id()'); // last inserted product id stored here.
$product = Mage::getModel('catalog/product')->load($insertId);
$product->setStoreId(STORE_ID)->setName('new_name')->save();//storing data by this way
Full code:
foreach( $xlsx->rows() as $k => $r) {
if ($k == 0) continue;//Ingnoring first column of excel file
try{
//grabbing categories for en
$key=array_search($r[55],$cat_arr);
$key2=array_search($r[56],$cat_arr);
$key3=array_search($r[57],$cat_arr);
//grabbing categories for de
$keyde=array_search($r[52],$cat_arr);
$key2de=array_search($r[53],$cat_arr);
$key3de=array_search($r[54],$cat_arr);
//grabbing categories for nl
$keynl=array_search($r[49],$cat_arr);
$key2nl=array_search($r[50],$cat_arr);
$key3nl=array_search($r[51],$cat_arr);
//Set the path of image folder
$imgpath_total=Mage::getBaseDir()."\media\proimg/12001.jpg";//.$r[59]
$newProduct = new Mage_Catalog_Model_Product();
$newProduct->setAttributeSetId(4)
->setTypeId('simple')
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->setTaxClassId(2)
->setCreatedAt(strtotime('now'))
->setSku($r[39])
->setWeight($r[40])
->setBrand($r[5])
->setTags($r[58])
->setAlc_percentage($r[42])
->setWeight('10')
->setEan($r[37])
->setStatus(1)
->setPrice($r[22])
->setWebsiteIds(array(1))
->setStockData(array('is_in_stock' => 1, 'qty' => 99999 ))
->setSetupFee(522)
//->addImageToMediaGallery($imgpath_total,array('image','small_image','thumbnail'),false,false)
->setsetupCost(100)
->setName($r[17])
->setTitle_long($r[18])
->setGoogle($r[64])
->setDescription($r[20])
->setShort_description($r[19])
->setCategoryIds(array(2,$key,$key2,$key3));
$newProduct->save();
$insertId= Mage::getSingleton('core/resource')->getConnection('core_read')->fetchOne('SELECT last_insert_id()');
$product = Mage::getModel('catalog/product')->load($insertId);
#################Dutch###############
$product->setStoreId(7)
->setName($r[12])
->setTitle_long($r[13])
->setGoogle($r[63])
->setDescription($r[15])
->setShort_description($r[14])
->save();
################End Dutch#############
#############Netherland ################
$product->setStoreId(8)
->setName($r[7])
->setTitle_long($r[8])
->setGoogle($r[62])
->setDescription($r[10])
->setShort_description($r[9])
->save();
#############End Netherland##########
#####save your product###################
}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;
}
exit;
}
I am using "ajaxSubmitButton" to send some values of 3 fields: registrant, product id and quantity to controller (controller name: actionCart). After submitting the button I receive those values in session array what I did successfully. At this point, if I submit same product id but different quantity, I want to update the quantity key with new value. I have done this by php global $_SESSION but can't using Yii session variable.
public function actionCart()
{
if(isset($_POST["Order"])){
$item = $_POST["Order"];
$registration_id = $item["registration_id"];
$this->productId = $item["item"];
$quantity = $item["quantity"];
$quantity = $item["quantity"]=='' ? 1 : $item["quantity"];
$productInfo = Products::model()->findByPk(array('id'=>$this->productId));
$totalPrice = $productInfo->price * $quantity;
$newItem = array("product_id" => $this->productId , "product_name" => $productInfo->name, "quantity" => $quantity,"price" => $productInfo->price,"totalPrice" => $totalPrice);
$session = Yii::app()->session;
$cartArray = $session['cart'];
$searchArrResult = $this->searchSubArray($session['cart'],'product_id',$this->productId);
if (!empty($searchArrResult)) {
/***** this works *****/
foreach ( $_SESSION['cart'] as $key=>$cart ) {
if ( $cart["product_id"] == $this->productId ) {
$_SESSION['cart'][$key]['quantity']=$quantity;
$_SESSION['cart'][$key]['totalPrice']=$totalPrice;
}
}
/***** following commented code does not work *****
*
foreach($session['cart'] as $key=>$cart){
if ($cart["product_id"] == $this->productId){
$session['cart'][$key]['quantity'] == $quantity;
$session['cart'][$key]['totalPrice'] == $totalPrice;
}
}*/
}
else {
$cartArray[] = $newItem;
$session['cart'] = $cartArray;
}
print_r($session['cart']);
//unset(Yii::app()->session['cart']);
}
}
In the above code I marked by commenting where I want to update session values. Please help me someone if it is possible do in yii.
Try this:
$carts = $session['cart'];
foreach($carts as $key=>&$cart){
if ($cart["product_id"] == $this->productId){
$cart['quantity'] == $quantity;
$cart['totalPrice'] == $totalPrice;
}
}
$session['cart'] = $carts;
Yii::app()->session return object of CHttpSession, not reference to $_SESSION.
$carts = $session['cart'] equals operation $carts = $session->get('cart'); (by means magic method __get in CHttpSession) and $session['cart'] = $carts; equals to $session->set('cart', $carts); (by __set)
That's why you can't setting by $session['cart'][$key]['quantity'] = $quantity;
UPDATED full solution (I change logic of saving products - $key = product_id)
public function actionCart()
{
if(isset($_POST["Order"])){
$item = $_POST["Order"];
$registration_id = $item["registration_id"];
$this->productId = $item["item"];
$quantity = empty(intval($item["quantity"])) ? 1 : intval($item["quantity"]);
$productInfo = Products::model()->findByPk(array('id'=>$this->productId));.
if(empty($productInfo))
return false; // or other action
$newItem = array(
"product_id" => $this->productId ,
"product_name" => $productInfo->name,
"quantity" => $quantity,
"price" => $productInfo->price,
"totalPrice" => ($productInfo->price * $quantity)
);
$cartArray = Yii::app()->session['cart'];
$cartArray[$this->productId] = $newItem;
Yii::app()->session['cart'] = $cartArray;
}
}