How to add custom options to a product in magento.

Posted by Damodar Bashyal on February 05, 2012

 

Adding custom options to a product automatically while importing CSV in Magento is quite easy after all.

extend this file: app\code\core\Mage\Catalog\Model\Convert\Adapter\Product.php

look for: public function saveRow(array $importData)

Look for this:

if (!$attribute) {
    continue;
}

and change to this: [you can change to your requirement]

if (!$attribute)
{
    if($field == 'embroidery')
    {
        $custom_options[] = array(
            'is_delete' => 0,
            'title' => 'embroidery',
            'previous_group' => '',
            'previous_type' => '',
            'type' => 'area',
            'is_require' => 0,
            'sort_order' => 0,
            'price' => 0,
            'price_type' => 'fixed',
            'max_characters' => 0,
            'values' => array(),
        );
    }
    continue;
}

Here i am adding empty textarea option for embroidery required for one of our websites. Also, as it is empty and no need to add to csv i added below code, so it's added to every single product.

just before: foreach ($importData as $field => $value) {

i added this:

        
if(!isset($importData['embroidery']))
{
    $importData['embroidery'] = '';
}

so, after saving all product data here:

$product->save();

add below code:

/* Skip existing custom options attached to the product */
$_options = array();
foreach ($product->getOptions() as $o)
{
    if($o->getTitle() == 'embroidery')
    {
        $_options['embroidery'] = 'embroidery';
    }
}
    
    /* Add the custom options specified in the CSV import file   */
    if (isset($custom_options))
    {
        if (count($custom_options))
        {
            foreach ($custom_options as $option)
            {
                if (in_array($option['title'], $_options))
                {
                    continue;
                }
                else
                {
                    try
                    {
                        $opt = Mage::getModel('catalog/product_option');
                        $opt->setProduct($product);
                        $opt->addOption($option);
                        $opt->saveOptions();
                    }
                    catch (Exception $e)
                    {
                        $message = Mage::helper('catalog')->__('Skip import row, Error in custom options: "%s"', $e);
                        Mage::throwException($message);
                    }
                }
            }
        }
    }
    return true;
}

Now upload csv with or without column 'embroidery' you will find custom option embroidery added to the product.

 
not published on website


QR Code: How to add custom options to a product in magento.