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();
}
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;
<?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
How to echo all custom options with all the values by product id for Magento?
If i am using this code...
public function ws_productdetail($store_id, $service, $productid)
{
$res=array();
$productsCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('entity_id', array('in' => $productid))
->addAttributeToSelect('*');
$all_product_images = array();
$product = Mage::getModel('catalog/product')->load($productid);
foreach ($product->getMediaGalleryImages() as $image) {
$all_product_images[] = $image->getUrl();
}
foreach($productsCollection as $product)
{
$res["id"] = $product->getId();
$res["name"] = $product->getName();
$res["price"] = number_format($product->getPrice(),2);
}
return($res);
}
... how can I get the custom options?
For example say for a product JEANS, COLOR with various values {blue,black,brown} and every option will have different prices, then how i get all this information as output.
According to my understanding, you want to show the all DROPDOWN custom option on view page then try this.
$productid = $_product->getId(); //PLEASE ENTER THE PRODUCT ID HERE
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
foreach($attVal as $optionKey => $optionVal)
{
$optStr.='<dl><div class="custom_select_css">
<dt><label>'.$optionVal->getTitle().'</label></dt>
<dd class="last">
<div class="input-box">';
$optStr.= "<select id='".$optionVal->getId()."' name='options[".$optionVal->getId()."]'>";
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$price = number_format($valuesVal->getPrice(),0);
$optStr.= "<option price='".number_format($valuesVal->getPrice(),0)."' data-label='".$colorarray[$valuesVal->getTitle()]."' value='".$valuesVal->getId()."'>".$valuesVal->getTitle(); if($price != '0'){$optStr.=" +$".number_format($valuesVal->getPrice(),2);}$optStr.=" </option>";
}
$optStr.= "</select></div></dd><div></dl>";
}
echo $optStr;
------------------------------ UPDATED CODE -------------------------------
public function ws_customdetail ($productid)
{
$all_custom_option_array = array();
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
$inc=0;
foreach($attVal as $optionKey => $optionVal)
{
$all_custom_option_array[$inc]['custom_option_name']=$optionVal->getTitle();
$all_custom_option_array[$inc]['custom_option_id']=$optionVal->getId();
$inner_inc =0;
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['title'] = $valuesVal->getTitle();
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['price'] = number_format($valuesVal->getPrice(),0);
$inner_inc++;
}
$inc++;
}
return $all_custom_option_array;
}
Use ws_customdetail function and pass the product id in it.
THIS IS THE EXACT CODE THAT WORKED FOR ME.
public function customdetail($productid){
$all_custom_option_array = array();
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
$inc=0;
foreach($attVal as $optionKey => $optionVal){
$all_custom_option_array[$inc]['custom_option_name']=$optionVal->getTitle();
$all_custom_option_array[$inc]['custom_option_id']=$optionVal->getId();
$all_custom_option_array[$inc]['custom_option_type']=$optionVal->getType();
$all_custom_option_array[$inc]['custom_option_value_array'];
$inner_inc =0;
foreach($optionVal->getValues() as $valuesKey => $valuesVal){
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['title'] = $valuesVal->getTitle();
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['price'] = number_format($valuesVal->getPrice(),0);
$inner_inc++;}
$inc++;}
return $all_custom_option_array;}
HOPE THIS WILL HELP SOMEONE :)
THANX
i am adding products to session as array but before adding that product to session how to check that product is present in session array or not.
If the product is present i want to increase the count of that product, if not add that product to session array. My php code is given below.
session_start();
if(empty( $_SESSION['fields1'] )) {
$_SESSION['fields1'] = array();
}
$qty = 1;
$id = $_POST['id'];
$name = $_POST['name'];
$description = $_POST['description'];
$cnt = 0;
print_r($_SESSION['fields1']);
if (! empty($_SESSION['fields1'])){
foreach ($_SESSION['fields1'] as $key=>$val){
if ($id == $val['id']){
$qty = $val['qty']++;
//echo "qty ===".$qty;
$_SESSION['fields1'][$cnt]['qty'] = $val['qty']++;
}
else
{
$arrayval = array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
array_push($_SESSION['fields1'] ,$arrayval );
}
$cnt++;
}
}else{
$arrayval = array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
array_push($_SESSION['fields1'] ,$arrayval );
}
//print_r($_SESSION['fields1']);
echo json_encode($_SESSION['fields1']);
If $id is ID of product and fields is array of products, try something like this:
if(empty($_SESSION['fields'][$id]))
$_SESSION['fields'][$id]['qty'] = 1;
else
$_SESSION['fields'][$id]['qty']++;
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;
}
}