Hire Magento Developer - I am available now
03
Nov

Although Magento comes with variety of product types out-of-the-box, sometimes it’s convenient to store specific product information with order data instead of product itself. For this purpose you can use Custom Options – after assigning options to specific product they will be displayed as a form. Customer might fill this form and after adding product to cart its content will be stored together with product details. The form is quite flexible and easy to create from admin area. Development of dynamically generated options is not complex as well. There are many ways to attach custom options to product automatically, below is simple helper that makes the task easier.

app/code/local/MageDev/CustomOptions/etc/config.xml

<?xml version="1.0"?>
<config>
	<modules>
		<MageDev_CustomOptions>
			<version>0.0.1</version>
		</MageDev_CustomOptions>
	</modules>
	<global>
		<helpers>
			<custom_options>
				<class>MageDev_CustomOptions_Helper</class>
			</custom_options>
		</helpers>
	</global>
</config>

app/code/local/MageDev/CustomOptions/Helper/Data.php

<?php
class MageDev_CustomOptions_Helper_Data extends Mage_Core_Helper_Abstract
{
	public function setCustomOption($productId, $title, array $optionData, array $values = array())
	{
		Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
		if (!$product = Mage::getModel('catalog/product')->load($productId)) {
			throw new Exception('Can not find product: ' . $productId);
		}
 
		$defaultData = array(
			'type'			=> 'field',
			'is_require'	=> 0,
			'price'			=> 0,
			'price_type'	=> 'fixed',
		);
 
		$data = array_merge($defaultData, $optionData, array(
													'product_id' 	=> (int)$productId,
													'title'			=> $title,
													'values'		=> $values,
												));
 
		$product->setHasOptions(1)->save();										
		$option = Mage::getModel('catalog/product_option')->setData($data)->setProduct($product)->save();
 
		return $option;
	}
}

And here’s sample usage:

<?php
$options = 	array(
			'type'		=> 'radio',
			'is_require'	=> 1,
			'price'		=> 0,
			'price_type'	=> 'fixed'
		  );
 
$values = array(
			array(
				'title'		=> 'Magento Development Basics',
				'price'		=> 10,
				'price_type'	=> 'fixed',
			),
 
			array(
				'title'		=> 'Intermediate Magento Development',
				'price'		=> 20,
				'price_type'	=> 'fixed',
			),
 
			array(
				'title'		=> 'Advanced Magento Development',
				'price'		=> 40,
				'price_type'	=> 'fixed'
			)
		 );
 
try {
	$helper = Mage::helper('custom_options')->setCustomOption(7, 'Magento Development Tutorial', $options, $values);
} catch (Exception $e) {
	echo $e->getMessage();
}

Hope this helper make development of your custom solution a bit easier.

,

19 Responses to “Adding custom options dynamically”

  • Very useful idea – add a little bit of ‘does this already exist on the product’ validation, hook it to the product_save_after event and whenever you save a product within the admin area you can automatically add a custom option.

    This has just saved me hours, thanks!

  • Same here, saved me hours! Thanks!

  • Nice tips there.. I do have more helpful..resource on this.. on
    http://subesh.com.np/2009/12/adding-custom-options-product-magento/

  • Omer

    Could you please explain a little more, i have no clue where to put the sample usage you provided

    thanx in advance

  • admin

    Omer,

    There are many different scenarios where you can use custom options helper. For example when creating new product you can automatically add custom options if say the product has specific attribute values. Hope that helps.

  • Lorenzo

    Hello,
    I try to use your code, when i place your sample usage code in app/design/frontend/default/default/template/checkout/cart/item/default.phtml i’ve got this error :

    SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`mybase/catalog_product_option`, CONSTRAINT `FK_CATALOG_PRODUCT_OPTION_PRODUCT` FOREIGN KEY (`product_id`) REFERENCES `catalog_product_entity` (`entity_id`) ON DELETE CASCADE ON UPDATE CASCA)

    How can i fix this ?
    Thanks for help

  • admin

    Lorenzo – it probably means that you’re trying to add an option referencing non existent product. Please make sure the product is already saved in database.

  • szotyi

    I am getting the following error:
    Fatal error: Class ‘Mage_Custom_Options_Helper_Data’ not found in …

    why? thanks!

  • Laurent

    Hello,
    can we use your code to dynamically add custom options to products in the cart page ?
    Thanks

  • admin

    Laurent,
    the tutorial is focused on attaching custom options to the product just like you do it in the admin area, however if you could send me more detailed specification of your requirements I might be able to help…

  • nice tutorial. thanks for sharing! great information for magento developers.

  • Laurent

    …thanks for you help, I’d like to add new fields (besides the name of the product) for each products in the cart where the customer could enter personal information …how to add editable option product in the cart ?

  • zmove

    Hello,

    It would be great to have an extension that allow to add some custom option automatically when you create a product.

    The best way to do that is probably to use the event catalog_product_save_before, but your code does not work in that case, because calling ->save() function will trigger an infinite loop. (Save -> call before_save -> save -> call before_save -> etc…)

  • This did not work for me.
    I added this script on the product view page to add a custom option.
    if(!$this->hasOptions())
    {
    //your script goes here
    }

    I added this script at the begining of the catalog/product/view.phtml page after the first two lines of code
    $_helper = $this->helper(‘catalog/output’);
    $_product = $this->getProduct();

    I want that a custom option is added directly, if not present, for every product.
    ……………………

    There is no error displayed but this does not shows any option. Neither in the frontend nor in the admin panel.
    I tried setting the has_options to 1.
    $_product->setHasOptions(1);
    $_product->save();
    But this give me error.
    …………………….

    I think we are very near to achieving this. Could you help me out.? I hope i am very clear on my requirement.

  • I am giving you the exact code used on the catalog/product/view.phtml page
    $_helper = $this->helper(‘catalog/output’);
    $_product = $this->getProduct();

    if(!$this->hasOptions()){ Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
    $custom_options = array(
    “is_delete” => 0 , “title” => “Measurement Details” , “previous_group” => “text” , “price_type” => “fixed” , “price” => “” , “type” => “area” , “is_required” => 1
    );
    $opt = Mage::getModel(‘catalog/product_option’);
    $opt->setProduct($_product);
    $opt->addOption($custom_options);
    $opt->saveOptions();
    $_product->setData(‘has_options’,1);
    $_product->save();
    }

    executing this give an error report saying
    ” SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ’4-2′ for key ‘UNQ_CATEGORY_PRODUCT’ “

  • @Rupesh I think you can delete the same record from database and give a try, kindly backup first. it seems problem with db only

  • nadshez

    This is Exactly what I am looking for .. but I have no idea how to use it. I basically want to hook this up to the product_save_before event, so that whenever a new product is going to be created, the custom option are added to the data to be created .. just like in admin.

    But I don’t know how I can do that. How & where exactly do you hook this method to the event? Can anyone please guide me? Thanks.

  • Great post!

    Works like charm, thanks!

    Serg

Add reply