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;
Related
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();
}
Hello please help with this code... I don't know what I am doing wrong....anyways I am new to codeigniter
I am trying to less the quantity of a product instock everytime the product is entered into the damaged-products table
Please check the code i have, it works adding the damaged product but the quantity in the product table remain unchanged.... Help please
public function addDamaged($data = array()) {
if($this->db->insert('damaged', $data)) {
$dam_id = $this->db->insert_id();
foreach ($data as $da) {
$da['dam_id'] = $dam_id;
$product = $this->site->getProductByID($id);
$this->db->update('products',
array('quantity' => ($product->quantity - $da['dam_qty'])),
array('id' => $product->id)
);
return $dam_id;
}
return false;
}
}
public function addDamaged($data = array()) {
if($this->db->insert('damaged', $data)) {
$product = $this->site->getProductByID($data['product_id']);
$this->db->update('products',
array('quantity' => ($product->quantity - $da['dam_qty'])),
array('id' => $product->id)
);
return $dam_id;
}
return false;
}
}
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 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.
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']++;