Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- * Links
- *
- * Configurable Products in Magento
- * http://blog.omnisubsole.com/2009/07/01/configurable-products-in-magento/
- *
- * Create configurable product in Magento programmatically
- * http://www.codetweet.com/magento/create-configurable-product-magento-programmatically/
- *
- * http://www.jackecommerce.com/magento-programmatically-create-configurable-product-and-assgin-simple-product/
- */
- /*
- * TODO
- * Load all attribute sets and their attributes on load (a bit of optimisation)
- * Perform actions with AJAX (timeLimit and user sees process progress)
- * Categories
- * Images
- */
- class SpartakusMd_CustomProductImporter_Adminhtml_MainformController extends Mage_Adminhtml_Controller_Action
- {
- private $_fieldNames = array();
- private $_fileData = array();
- public function indexAction()
- {
- $this->loadLayout()->renderLayout();
- }
- public function postAction()
- {
- echo '<pre>';
- $this->importFromXML();
- echo '</pre>';
- }
- private function createSimpleProduct($args) {
- $defaults = array(
- 'TypeId' => Mage_Catalog_Model_Product_Type::TYPE_SIMPLE,
- 'TaxClassId' => 0,
- 'WebsiteIds' => array(1),
- 'AttributeSetId' => $this->getAttributeSetId('Default'),
- 'Description' => '',
- 'ShortDescription' => '',
- 'Weight' => 0,
- 'Status' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED,
- 'Visibility' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE, //1 - Not Visible Individually
- 'StockQty' => '99',
- 'MetaTitle' => '',
- 'MetaDescription' => '',
- 'MetaKeywords' => '',
- );
- $o = array_merge($defaults, $args);
- //create product
- $product = Mage::getModel('catalog/product');
- $product->setTypeId($o['TypeId']);
- $product->setTaxClassId($o['TaxClassId']); //none
- $product->setWebsiteIds($o['WebsiteIds']); // store id
- //setting product attributes
- $productAttributes = array();
- $attributesData = array();
- $_attributes = array();
- $product->setAttributeSetId($o['AttributeSetId']);
- // echo '$o = '; print_r($o);
- // die;
- foreach( $o['Attributes'] as $key=>$value ) {
- $attrID = $this->getAttributeId($key);
- $_attributes[$key] = $attrID;
- $this->addAttributeValue($key, $value);
- $value_index = $this->attributeValueExists($key, $value);
- $product->setData($key, $value);
- $productAttributes[] = array(
- 'attribute_id' => $attrID,
- 'label' => $value,
- 'value_index' => $value_index,
- 'is_percent' => 0,
- 'pricing_value' => 0
- );
- $attributesData[$key][$attrID . '-' . $value . '-' . $value_index] = array(
- 'attribute_id' => $attrID,
- 'label' => $value,
- 'value_index' => $value_index,
- 'is_percent' => 0,
- 'pricing_value' => 0
- );
- }
- $product->setSku($o['Sku']);
- $product->setName($o['Name']);
- $product->setPrice(sprintf("%0.2f", floatval($o['Price'])));
- $product->setDescription($o['Description']);
- $product->setShortDescription($o['ShortDescription']);
- $product->setInDepth($o['Description']);
- $product->setWeight($o['Weight']);
- $product->setStatus($o['Status']); //enabled
- $product->setVisibility($o['Visibility']);
- $product->setStockData(
- array(
- 'use_config_manage_stock' => 1,
- 'is_in_stock' => 1,
- 'is_salable' => 1,
- 'qty' => $o['StockQty']
- )
- );
- $product->setMetaTitle($o['MetaTitle']);
- $product->setMetaDescription($o['MetaDescription']);
- $product->setMetaKeywords($o['MetaKeywords']);
- $product->setCategoryIds($o['categoryids']);
- echo 'Simple[o] = '; print_r($o);
- /*
- // use the directory path to images you want to save for the product
- $mode = array("image");
- $img = 'full_directory_path_to_image_stored_img_0001.jpg';
- $sProduct->addImageToMediaGallery($img, $mode, false, false);
- $mode = array("small_image", "thumbnail", "image");
- $img = 'full_directory_path_to_image_stored_img_0002.jpg';
- $sProduct->addImageToMediaGallery($img, $mode, false, false);
- */
- try{
- $product->save();
- echo 'Simple product ' . $product->getId() . '(' . $o['Name'] . '), successfully added!<br />';
- $ret = array();
- $ret['product'] = array($product->getId() => $productAttributes);
- $ret['_attributes'] = $_attributes;
- $ret['attributesData'] = $attributesData;
- echo '$simple_ret = '; print_r($ret);
- echo '<hr>';
- return $ret;
- }
- catch (Exception $e){
- echo 'Error! Product not added!';
- echo 'Exception: ' . $e;
- }
- return false;
- }
- private function createConfigurableProduct($args) {
- $defaults = array(
- '_typeId' => Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE,
- '_taxClassId' => 0,
- '_websiteIds' => array(1),
- 'AttributeSetId' => $this->getAttributeSetId('Default'),
- 'Description' => '',
- 'ShortDescription' => '',
- 'Weight' => 0,
- 'Status' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED,
- 'Visibility' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH, //4 - Catalog, Search
- 'StockQty' => '99',
- 'MetaTitle' => '',
- 'MetaDescription' => '',
- 'MetaKeywords' => '',
- );
- $o = array_merge($defaults, $args);
- //get combinations of attributes
- $setOfAttributes = $this->cartesianProduct($args['attributes']);
- //create simple products
- $configurableProductsData = array();
- $_attributeIds = array();
- $attributesData = array();
- $i=0;
- foreach( $setOfAttributes as $attrs ) {
- $simpleArgs = $o;
- $simpleArgs['Attributes'] = $attrs;
- unset($simpleArgs['Visibility']);
- foreach( $attrs as $value ) {
- $simpleArgs['Name'] .= '-' . $value;
- $simpleArgs['Sku'] .= '-' . $value;
- }
- $sp = $this->createSimpleProduct($simpleArgs);
- if( $sp !== false ) {
- foreach( $sp['product'] as $key=>$value ) {
- $configurableProductsData[$key] = $value;
- }
- $_attributeIds = array_merge($_attributeIds, $sp['_attributes']);
- foreach( $sp['attributesData'] as $key=>$value ) {
- if( !isset($attributesData[$key]) ) $attributesData[$key] = array();
- $attributesData[$key] = array_merge($attributesData[$key], $value);
- }
- //$attributesData = array_merge_recursive($attributesData, $sp['attributesData']); //TODO
- echo '$configurableProductsData = '; print_r($sp['product']);
- }
- if($i++ == 2) break; //TODO Limit 2
- }
- //create product
- $product = Mage::getModel('catalog/product');
- $product->setTypeId($o['_typeId']);
- $product->setTaxClassId($o['_taxClassId']); //none
- $product->setWebsiteIds($o['_websiteIds']); // store id
- $product->setAttributeSetId($o['AttributeSetId']); //Default Attribute Set
- // foreach( $o['Attributes'] as $key=>$value ) {
- // $product->setData($key, $value);
- // }
- $product->setSku($o['Sku']);
- $product->setName($o['Name']);
- $product->setPrice(sprintf("%0.2f", floatval($o['Price'])));
- $product->setDescription($o['Description']);
- $product->setShortDescription($o['ShortDescription']);
- $product->setInDepth($o['Description']);
- $product->setWeight($o['Weight']);
- $product->setStatus($o['Status']); //enabled
- $product->setVisibility($o['Visibility']);
- $product->setStockData(
- array(
- 'use_config_manage_stock' => 1,
- 'is_in_stock' => 1,
- 'is_salable' => 1,
- 'qty' => $o['StockQty']
- )
- );
- $product->setMetaTitle($o['MetaTitle']);
- $product->setMetaDescription($o['MetaDescription']);
- $product->setMetaKeywords($o['MetaKeywords']);
- $product->setCategoryIds($o['categoryids']);
- echo 'Configurable[o] = '; print_r($o);
- echo '#categoryids = '; print_r($o['categoryids']);
- // Set configurable info
- $cProductTypeInstance = $product->getTypeInstance();
- $cProductTypeInstance->setUsedProductAttributeIds($_attributeIds);
- // Now we need to get the information back in Magento's own format, and add bits of data to what it gives us..
- $attributes_array = $cProductTypeInstance->getConfigurableAttributesAsArray();
- $i = 0;
- foreach($attributes_array as $key => $attribute_array) {
- $attributes_array[$key]['use_default'] = 1;
- $attributes_array[$key]['position'] = $i++;
- $attributes_array[$key]['html_id'] = 'config_super_product__attribute_' . $attributes_array[$key]['position'];
- if (isset($attribute_array['frontend_label'])) {
- $attributes_array[$key]['label'] = $attribute_array['frontend_label'];
- } else {
- $attributes_array[$key]['label'] = $attribute_array['attribute_code'];
- }
- if( isset($attributesData[$attribute_array['attribute_code']]) ) {
- foreach( $attributesData[$attribute_array['attribute_code']] as $value ) {
- $attributes_array[$key]['values'][] = $value;
- }
- }
- }
- echo '$_attributeIds = '; print_r($_attributeIds);
- echo '$attributes_array = '; print_r($attributes_array);
- echo '$attributesData = '; print_r($attributesData);
- echo '$configurableProductsData = '; print_r($configurableProductsData);
- // die;
- $product->setConfigurableProductsData($configurableProductsData);
- $product->setConfigurableAttributesData($attributes_array);
- $product->setCanSaveConfigurableAttributes(true);
- $product->setCanSaveCustomOptions(true);
- /* TODO
- $configurableProductsData = array(
- '5791' => array(
- '0' => array('attribute_id' => '491', 'label' => 'vhs', 'value_index' => '5', 'is_percent' => 0, 'pricing_value' => ''),
- '1' => array('attribute_id' => '500', 'label' => 'English', 'value_index' => '9', 'is_percent' => 0, 'pricing_value' => '')
- ),
- '5792' => array(
- '0' => array('attribute_id' => '491', 'label' => 'dvd', 'value_index' => '6', 'is_percent' => 0, 'pricing_value' => ''),
- '1' => array('attribute_id' => '500', 'label' => 'English', 'value_index' => '9', 'is_percent' => 0, 'pricing_value' => '')
- ),
- '5807' => array(
- '0' => array('attribute_id' => '491', 'label' => 'dvd', 'value_index' => '6', 'is_percent' => 0, 'pricing_value' => ''),
- '1' => array('attribute_id' => '500', 'label' => 'Spanish', 'value_index' => '8', 'is_percent' => 0, 'pricing_value' => '')
- ),
- '5808' => array(
- '0' => array('attribute_id' => '491', 'label' => 'vhs', 'value_index' => '6', 'is_percent' => 0, 'pricing_value' => ''),
- '1' => array('attribute_id' => '500', 'label' => 'Spanish', 'value_index' => '8', 'is_percent' => 0, 'pricing_value' => '')
- )
- );
- $configurableAttributesData = array(
- '0' => array(
- 'id' => NULL,
- 'label' => 'Media Format',
- 'position' => NULL,
- 'values' => array(
- '0' =>
- array(
- 'value_index' => 5,
- 'label' => 'vhs',
- 'is_percent' => 0,
- 'pricing_value' => '0',
- 'attribute_id' => '491'
- ),
- '1' =>
- array(
- 'value_index' => 6,
- 'label' => 'dvd',
- 'is_percent' => 0,
- 'pricing_value' => '0',
- 'attribute_id' => '491'
- )
- ),
- 'attribute_id' => 491, 'attribute_code' => 'media_format', 'frontend_label' => 'Media Format', 'html_id' => 'config_super_product__attribute_0'
- ),
- '1' => array(
- 'id' => NULL,
- 'label' => 'Language',
- 'position' => NULL,
- 'values' => array(
- '0' => array(
- 'value_index' => 8,
- 'label' => 'Spanish',
- 'is_percent' => 0,
- 'pricing_value' => '0',
- 'attribute_id' => '500'
- ),
- '1' => array(
- 'value_index' => 9,
- 'label' => 'English',
- 'is_percent' => 0,
- 'pricing_value' => '0',
- 'attribute_id' => '500'
- )
- ),
- 'attribute_id' => 500, 'attribute_code' => 'media_format', 'frontend_label' => 'Language', 'html_id' => 'config_super_product__attribute_1')
- );
- $product->setConfigurableProductsData($configurableProductsData);
- $product->getTypeInstance()->setUsedProductAttributeIds(array(491,500));
- $product->setConfigurableAttributesData($configurableAttributesData);
- $product->setCanSaveConfigurableAttributes(1);
- */
- try{
- $product->save();
- echo 'Configurable Product ' . $product->getId() . '(' . $o['Name'] . '), successfully added!';
- echo '<hr><hr><hr>';
- return $product;
- }
- catch (Exception $e){
- echo 'Error! Configurable Product not added!';
- echo 'Exception: ' . $e;
- }
- }
- /**
- * Retrive an attribute set ID based on it's name
- *
- * @param string $attributeSetName
- * @return mixed
- */
- private function getAttributeSetId($attributeSetName = 'Default') {
- $entityTypeId = Mage::getModel('eav/entity')
- ->setType('catalog_product')
- ->getTypeId();
- $attributeSetId = Mage::getModel('eav/entity_attribute_set')
- ->getCollection()
- ->setEntityTypeFilter($entityTypeId)
- ->addFieldToFilter('attribute_set_name', $attributeSetName)
- ->getFirstItem()
- ->getAttributeSetId();
- return $attributeSetId;
- }
- /**
- * Retrieve the attribute id by code
- *
- * @param $attributeCode
- * @return int
- */
- private function getAttributeId($attributeCode) {
- $attributeModel = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', $attributeCode);
- return $attributeModel->getAttributeId();
- }
- /**
- * Retrieve attributes from a set
- *
- * @param int|string $attributeSetId Attribute Set ID or Name
- * @return Array|false Array of attributes
- */
- private function getAttributesFromSet($attributeSetId) {
- if( is_string($attributeSetId) ) {
- $attributeSetId = $this->getAttributeSetId($attributeSetId);
- }
- $attributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);
- return $attributes;
- }
- /**
- * Get individual attribute from array based on it's code
- *
- * @param $attributeCode
- * @param $attributeSet
- * @return Array|bool
- */
- private function getAttributeFromAttributesSetArray($attributeCode, $attributeSet) {
- foreach($attributeSet as $attribute) {
- if( $attribute['code'] == $attributeCode ) {
- return $attribute;
- }
- }
- return false;
- }
- /**
- * Retrieve dropdown attribute options
- *
- * @param $attributeCode
- * @return Array|bool
- */
- private function getAttributeOptions($attributeCode) {
- $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attributeCode);
- return $attribute->getSource()->getAllOptions(true, true);
- }
- /**
- * Check whether given attribute value exists
- *
- * @param $arg_attribute
- * @param $arg_value
- * @return bool
- */
- public function attributeValueExists($arg_attribute, $arg_value)
- {
- $attribute_model = Mage::getModel('eav/entity_attribute');
- $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
- $attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
- $attribute = $attribute_model->load($attribute_code);
- $attribute_table = $attribute_options_model->setAttribute($attribute);
- $options = $attribute_options_model->getAllOptions(false);
- foreach($options as $option)
- {
- if ($option['label'] == $arg_value)
- {
- return $option['value'];
- }
- }
- return false;
- }
- /**
- * Add attribute option to magento
- *
- * @param $arg_attribute
- * @param $arg_value
- * @return int|bool Id of value
- */
- public function addAttributeValue($arg_attribute, $arg_value)
- {
- $attribute_model = Mage::getModel('eav/entity_attribute');
- $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
- $attribute_code = $attribute_model->getIdByCode(1, $arg_attribute);
- $attribute = $attribute_model->load($attribute_code);
- $attribute_table = $attribute_options_model->setAttribute($attribute);
- $options = $attribute_options_model->getAllOptions(false);
- if(!$this->attributeValueExists($arg_attribute, $arg_value))
- {
- $value['option'] = array($arg_value,$arg_value);
- $result = array('value' => $value);
- $attribute->setData('option',$result);
- $attribute->save();
- }
- foreach($options as $option)
- {
- if ($option['label'] == $arg_value)
- {
- return $option['value'];
- }
- }
- return true;
- }
- /**
- * Get individual attribute option from array based on it's label
- *
- * @param $optionLabel
- * @param $options
- * @return Array|bool
- */
- private function getAttributeOptionByLabel($optionLabel, $options) {
- foreach($options as $option) {
- if( $option['label'] == $optionLabel ) {
- return $option;
- }
- }
- return false;
- }
- /**
- * Retrieve store category id based on the one from XML
- *
- * @param $id
- * @return Array|bool array with the category, or false if not mapped
- */
- private function getStoreCategory( $id ) {
- $categoryRelations = array(
- '59229' => array(187),
- '59296' => array(190),
- '59297' => array(193),
- '73050' => array(190),
- '68406' => array(194),
- '68407' => array(193),
- '59207' => array(187),
- '60569' => array(190),
- '59203' => array(190),
- '59204' => array(190),
- '65397' => array(187),
- '59211' => array(190),
- '59214' => array(198),
- '61471' => array(198),
- '59217' => array(187),
- '68445' => array(194),
- '68446' => array(193),
- '59257' => array(186),
- '69611' => array(190),
- '60175' => array(187),
- '59264' => array(190),
- '59228' => array(209),
- '59219' => array(209),
- '68816' => array(195),
- '67653' => array(195),
- '59213' => array(195),
- '67650' => array(202),
- '69572' => array(200),
- '70018' => array(202),
- '70994' => array(210, 204),
- '70989' => array(210, 204),
- '70991' => array(210, 204),
- '70995' => array(210, 204),
- '70987' => array(210, 204),
- '70848' => array(210, 204),
- '70990' => array(210, 204),
- '70996' => array(210, 204),
- '70993' => array(210, 204),
- '70847' => array(210, 204),
- '70844' => array(210, 204),
- '70998' => array(206),
- '68151' => array(206),
- '59397' => array(206),
- '68165' => array(206),
- '72076' => array(206),
- '70722' => array(206),
- '71109' => array(206),
- '70721' => array(206),
- '71116' => array(206),
- '70740' => array(206),
- '70723' => array(206),
- '70720' => array(206),
- '71003' => array(206),
- '71028' => array(206),
- '71117' => array(206),
- '59401' => array(206),
- '70043' => array(205),
- '70044' => array(205),
- '70045' => array(205),
- '70049' => array(205),
- '71496' => array(205),
- '70048' => array(205),
- '70047' => array(205),
- '70050' => array(205)
- );
- if( isset($categoryRelations[(string) $id]) ) return $categoryRelations[(string) $id];
- return false;
- }
- /**
- * Parse and import products from an XML file
- */
- private function importFromXML() {
- $categoryProducts = $this->getProductsArrayFromXML();
- $prodCountByCatID = array();
- foreach( $categoryProducts as $products ) {
- foreach( $products as $product ) {
- //count products per category
- if( !isset($prodCountByCatID[$product['catid']]) ) $prodCountByCatID[$product['catid']] = 1;
- else $prodCountByCatID[$product['catid']]++;
- //if limit reached skip the product
- if( $prodCountByCatID[$product['catid']] >= 20 ) continue;
- //create the product
- $this->createConfigurableProduct($product);
- break; //TODO remove limit 1
- }
- break; //TODO remove limit 1
- }
- }
- /**
- * Get products from the XML file
- *
- * @return array Products info array from XML
- */
- private function getProductsArrayFromXML() {
- //Parse XML
- $data = trim(file_get_contents('http://feed485.efashioncentral.com/df/feed.php'));
- $XML = new SimpleXmlElement($data);
- $productsToImport = array();
- if( isset($XML->product) ) {
- foreach ( $XML->product as $product ) {
- $p = array(); //new array
- $attributes = $product->attributes();
- $p['id'] = (int) $attributes['id'];
- $p['catid'] = (int) $product->catid;
- $p['categoryids'] = $this->getStoreCategory($product->catid); //TODO: get correct category
- $p['Sku'] = (string) $product->stylenum;
- $p['Price'] = (float) $product->price;
- $p['StockQty'] = 99;
- $p['Name'] = (string) $product->name;
- $p['ShortDescription'] = (string) $product->shortdesc;
- $p['Description'] = (string) $product->desc;
- $p['Keywords'] = (string) $product->keywords;
- $p['images'] = array();
- if( isset($product->images) && isset($product->images->image) ) {
- foreach( $product->images->image as $image ) {
- $p['images'][] = (string) $image->bigimage;
- }
- }
- $p['attributes'] = array();
- $p['attributes']['size'] = array();
- if( isset($product->sizes) && isset($product->sizes->size) ) {
- foreach( $product->sizes->size as $size ) {
- $p['attributes']['size'][] = (string) $size;
- }
- }
- $p['attributes']['color'] = array();
- if( isset($product->colors) && isset($product->colors->color) ) {
- foreach( $product->colors->color as $color ) {
- $p['attributes']['color'][] = (string) $color->colorname;
- }
- }
- //skip if store hasn't such category
- if( !isset($p['categoryids']) || $p['categoryids'] === false ) continue;
- //store import cat num as array index
- $productsToImport[$p['catid']][$p['id']] = $p;
- }
- }
- return $productsToImport;
- }
- /**
- * Generate cartesian product for configurable products
- *
- * @param $input
- * @return array
- */
- public function cartesianProduct( $input ) {
- $result = array();
- while (list($key, $values) = each($input)) {
- // If a sub-array is empty, it doesn't affect the cartesian product
- if (empty($values)) {
- continue;
- }
- // Seeding the product array with the values from the first sub-array
- if (empty($result)) {
- foreach($values as $value) {
- $result[] = array($key => $value);
- }
- }
- else {
- // Second and subsequent input sub-arrays work like this:
- // 1. In each existing array inside $product, add an item with
- // key == $key and value == first item in input sub-array
- // 2. Then, for each remaining item in current input sub-array,
- // add a copy of each existing array inside $product with
- // key == $key and value == first item of input sub-array
- // Store all items to be added to $product here; adding them
- // inside the foreach will result in an infinite loop
- $append = array();
- foreach($result as &$product) {
- // Do step 1 above. array_shift is not the most efficient, but
- // it allows us to iterate over the rest of the items with a
- // simple foreach, making the code short and easy to read.
- $product[$key] = array_shift($values);
- // $product is by reference (that's why the key we added above
- // will appear in the end result), so make a copy of it here
- $copy = $product;
- // Do step 2 above.
- foreach($values as $item) {
- $copy[$key] = $item;
- $append[] = $copy;
- }
- // Undo the side effecst of array_shift
- array_unshift($values, $product[$key]);
- }
- // Out of the foreach, we can add to $results now
- $result = array_merge($result, $append);
- }
- }
- return $result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement