1

I'm trying to create some configurable products programmatically, but I think I'm missing a step somewhere. I'm basing my code mostly off of inchoo's tutorial, but also off of about 2 dozen other questions/articles.

At this point in my code, I have all of the attributes and simple products containing each combination of variations already created. I'm just trying to create the configurable product:

// Do the normal product creating bit:
$prod = Mage::getModel('catalog/product');
$prod->setWebsiteIds([1])
    ->setAttributeSetId($set_id)        // Ex: 100
    ->setTypeId('configurable')
    ->setCreatedAt(strtotime('now'))
    ->setUpdatedAt(strtotime('now'))
    ->setSku($sku)                      // Ex: 'foo_bar'
    ->setName($name)                    // Ex: 'Foo Bar'
    ->setWeight($weight)                // Ex: 11.22
    ->setStatus(1)
    ->setTaxClassId(4)
    ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
    ->setPrice($price)                  // Ex: 19.49
    ->setDescription($description)      // Ex: 'Description Here!'
    ->setShortDescription($name)        // Ex: 'Foo Name'
    ->setCategoryIds($categories)       // Ex: [200, 201, 202, 203]
    ->setStockData([
        'use_config_manage_stock' => 0,
        'manage_stock' => 1,
        'is_in_stock' => 1,
    ]);

// This seems a bit silly to me, but it's the only way I've found to both add an image
// to a product AND give it a label at the same time.
foreach ($attributes as $attribute) {
    $prod->addImageToMediaGallery($attribute['image_url'], null, false, false);
    $gallery = $prod->getData('media_gallery');
    $lastImage = array_pop($gallery['images']);
    $lastImage['label'] = $attribute['text'] . '-swatch';
    array_push($gallery['images'], $lastImage);
    $prod->setData('media_gallery', $gallery);
}

// The main image gets added last or it messes everything up.
$prod->addImageToMediaGallery($main_image, ['image', 'small_image', 'thumbnail'], false, false);


// $attr_ids contains the attributes used in the configurable attributes from $set_id
$prod->getTypeInstance()->setUsedProductAttributeIds($attr_ids);
$config_data = $prod->getTypeInstance()->getConfigurableAttributesAsArray();
$prod->setCanSaveConfigurableAttributes(true);
$prod->setConfigurableAttributesData($config_data);
// Shown below
$prod->setConfigurableProductsData($variation_infos);
$prod->save();

The $variation_infos array looks like this: [product_id] => [ 0 => [data] ]:

Array
(
    [141] => Array
        (
            [0] => Array
                (
                    [label] => Red
                    [attribute_id] => 158
                    [value_index] => 307
                    [is_percent] => 0
                    [pricing_value] => 0
                )

        )

    [142] => Array
        (
            [0] => Array
                (
                    [label] => Green
                    [attribute_id] => 158
                    [value_index] => 308
                    [is_percent] => 0
                    [pricing_value] => 0
                )

        )
) 

Using this code, the configurable product is created, however, when logging into the back-end and clicking on the configurable product that was just made, I'm greeted with this: check things

I thought the whole $prod->getTypeInstance()->setUsedProductAttributeIds($attr_ids); line was supposed to select those attributes.

Anyways, I check color and hit continue, and everything else looks right at first glance. Going through the 'images' tab shows all of the images as being added correctly. Going to 'associated products' also shows that all of the simple products I selected are there. However, when going to the front end of the site, the default placeholder image is used and I'm not given any dropdowns to select the different attributes.

I've been stuck on this for a few days. Any help would be appreciated.

Thanks!

-1

try it

    //this $data - array
    $sku_config = $data['sku']."_config";
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    $website_ids = array(1);
    $array_category_id = Mage::helper('parser/categorylist')->getCategoryArray();

    $configProduct = Mage::getModel('catalog/product');
    try {
        $configProduct
            ->setStoreId(self::STORE_ID)//you can set data in store scope
            ->setWebsiteIds($website_ids)//website ID the product is assigned to, as an array
            ->setAttributeSetId(self::ATTRIBUTE_SET)//ID of a attribute set named 'default'
            ->setTypeId(self::PRODUCT_TYPE_CONFIGURABLE)//product type
            ->setCreatedAt(strtotime(self::PRODUCT_TIME_CREATED))//product creation time
            ->setSku($sku_config)//SKU
            ->setName($data['name'])//product name
            ->setWeight($data['characteristic']['weight'])
            ->setStatus(self::PRODUCT_STATUS_ENABLED)//product status (1 - enabled, 2 - disabled)
            ->setTaxClassId(self::PRODUCT_TAXT_CLASS_NONE)//tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
            ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)//catalog and search visibility
            ->setManufacturer($this->hasAttribute('manufacturer', $data['brand'])) //manufacturer id
            ->setPrice($data['price'])//price in form 11.22
            ->setCost($data['price'])//price in form 11.22
            ->setDescription($data['description'])
            ->setShortDescription($this->getShortDescriptions($data['description']))
            ->setCategoryIds(array($array_category_id[$name_cat]))
            ->setStockData(array(
                    'use_config_manage_stock' => 0, //'Use config settings' checkbox
                    'manage_stock' => 1, //manage stock
                    'is_in_stock' => 1 //Stock Availability
                )
            );
        if(isset($data['spec_price']) && !empty($data['spec_price'])){
            $configProduct->setSpecialPrice($data['spec_price']);
        }

        // add image to media gallery
        $importDir = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . DS;
        foreach ($data['url_img_small'] as $key => $fileName) {
            $filePath = $importDir . $fileName;
            $type = ($key == 1) ? array('image', 'thumbnail', 'small_image') : null;
            if (file_exists($filePath)) {
                try {
                    $configProduct->addImageToMediaGallery($filePath, $type, true, false);
                } catch (Exception $e) {
                    Mage::log($e->getLine()."::".$e->getMessage(), null, 'error_download_img.log');
                }
            }
        }
        //magic it's here
        if(isset($data['color']) && !isset($data['size_data'])) {
            $colorAttributeId = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', 'color');// ID = 92

            $configProduct->getTypeInstance()->setUsedProductAttributeIds(array($colorAttributeId)); //attribute ID of attribute 'color' in my store
            $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
            $configProduct->setCanSaveConfigurableAttributes(true);
            $configProduct->setConfigurableAttributesData($configurableAttributesData);

            $configurableProductsData = array();
            foreach ($data['color'] as $key => $val) {
                $simple_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $key);
                $simple_product_id = $simple_product->getId();
                $configurableProductsData[$simple_product_id] = array( //['920'] = id of a simple product associated with this configurable
                    '0' => array(
                        'label' => $simple_product->getAttributeText('color'), //attribute label
                        'attribute_id' => $colorAttributeId, //attribute ID of attribute 'color' in my store
                        'value_index' => (int)$simple_product->getColor(), //value of 'Green' index of the attribute 'color'
                        'is_percent' => '0', //fixed/percent price for this option
                        'pricing_value' => $data['price']  //value for the pricing
                    ),
                );
            }
        }

        if(isset($data['color']) && isset($data['size_data']) && isset($data['prod_id'])) {
            $sizeAttributeId   = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', 'size');
            $colorAttributeId  = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', 'color');

            $configProduct->getTypeInstance()->setUsedProductAttributeIds(array($sizeAttributeId,$colorAttributeId)); //attribute ID of attribute 'color' in my store
            $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
            $configProduct->setCanSaveConfigurableAttributes(true);
            $configProduct->setConfigurableAttributesData($configurableAttributesData);

            $configurableProductsData = array();
            $array_sku = $data['prod_id'];
            foreach ($array_sku as $key => $val) {
                $simple_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $val);
                $simple_product_id = $simple_product->getId();
                $configurableProductsData[$simple_product_id] = array( //['920'] = id of a simple product associated with this configurable
                    '0' => array(
                        'label' => $simple_product->getAttributeText('size'), //attribute label
                        'attribute_id' => $sizeAttributeId, //attribute ID of attribute 'color' in my store
                        'value_index' => (int)$simple_product->getSize(), //value of 'Green' index of the attribute 'color'
                        'is_percent' => '0', //fixed/percent price for this option
                        'pricing_value' => $data['price']  //value for the pricing
                    ),
                    '1' => array(
                        'label' => $simple_product->getAttributeText('color'), //attribute label
                        'attribute_id' => $colorAttributeId, //attribute ID of attribute 'color' in my store
                        'value_index' => (int)$simple_product->getColor(), //value of 'Green' index of the attribute 'color'
                        'is_percent' => '0', //fixed/percent price for this option
                        'pricing_value' => $data['price']  //value for the pricing
                    )
                );
            }
        }
        $configProduct->setConfigurableProductsData($configurableProductsData);
        $configProduct->save();

    } catch (Exception $e) {
        Mage::log($e->getLine()."::".$e->getMessage(),null,"error_create_config_product.log");
    }
}

also need attribute properties seting "Use To Create Configurable Product" - YES

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.