LinkedIn Twitter RSS Reset

Adding custom options to a product in Magento

Adding custom option in Magento is pretty easy! You just need to know the format of an array, which is taken by catalog/product_option Model to set the custom option. I’ve deviced a simple function (setCustomOption) that just does that. The function, according to the input type and values assigned creates an array, which is then used by the catalog/product_option Model to save the option to the product.

Here is the function.

/**
	 * @param $value - Must be comma seperated options.
	 * @param $title - Title of the custom option.
	 * @param $type - Type of custom option - drop_down,radio,checkbox,multiple,area,field.
	 * @param $noOption - Specifies if the custom options has options or not.
	 */
	function setCustomOption ($value, $title, $type, $noOption = false)
	{
		$custom_options = array();
		if ($type && $value != "" && $value) {
			$values = explode(',', $value);
			if (count($values)) {
				/**If the custom option has options*/
				if (! $noOption) {
					$is_required = 0;
					$sort_order = 0;
					$custom_options[] = array(
						'is_delete' => 0 , 'title' => $title , 'previous_group' => '' , 'previous_type' => '' , 'type' => $type , 'is_require' => $is_required , 'sort_order' => $sort_order , 'values' => array()
					);
					foreach ($values as $v) {
						$titleopt = ucfirst(trim($v));
						switch ($type) {
							case 'drop_down':
							case 'radio':
							case 'checkbox':
							case 'multiple':
							default:
								$title = ucfirst(trim($v));
								$custom_options[count($custom_options) - 1]['values'][] = array(
									'is_delete' => 0 , 'title' => $titleopt , 'option_type_id' => - 1 , 'price_type' => '' , 'price' => '' , 'sku' => '' , 'sort_order' => ''
								);
							break;
						}
					}
					return $custom_options;
				}
				/**If the custom option doesn't have options | Case: area and field*/
				else {
					$is_required = 0;
					$sort_order = '';
					$custom_options[] = array(
						"is_delete" => 0 , "title" => $title , "previous_group" => "text" , "price_type" => 'fixed' , "price" => '' , "type" => $type , "is_required" => $is_required
					);
					return $custom_options;
				}
			}
		}
		return false;
	}

And to save the custom option, first get the array built by the above function and pass it to the catalog/product_option Model’s function to save. Here’s how you do it.


$arrayOption = array();
	/**
	 * For Creating dropdown,select,multiselect,radio type of custom option
	 */
	$arrayOption[] = setCustomOption("OPT1,OPT2", "Select Option", "drop_down");
	/**
	 * For Creating textfield and textarea type of custom option
	 */
	$arrayOption[] = setCustomOption("Anyvalue", "Area", "area", true);
	/**
	 * Load the product you want to assign custom option to
	 */
	$product = Mage::getModel("catalog/product")->load(167);
	foreach ($arrayOption as $options) {
		foreach ($options as $option) {
			$opt = Mage::getModel('catalog/product_option');
			$opt->setProduct($product);
			$opt->addOption($option);
			$opt->saveOptions();
		}
	}

After running the code you will get something like this.

Custom Option added to a Product

Custom Option added to a Product

Hope you like this post!

39 Responses to “Adding custom options to a product in Magento”

  1. February 11, 2010 at 12:16 pm #

    Hey!

    Amazing thats exactly what i am looking for. Didn’t tried this code yet but if it is working then it’s great!

    Thanks for this.

  2. February 12, 2010 at 10:17 am #

    It’s me again. I must tell you that i tried this code and works great I just have one question if you or anyone else maybe know?

    I want to add product options but with different price. How can I do this? I tried to set this ‘price’ => ’50.000′ into array but it doesn’t work.

    Very informative blog about Magento by the way. Their documentation sux so that kind of blogs are really helpful.

    • Subesh Pokhrel
      February 12, 2010 at 12:40 pm #

      I think you also need to set price_type=>”fixed” for doing that..

      Thanks for the response!

      • February 15, 2010 at 11:37 am #

        Great!

        price_type=>”fixed” did the trick.

        Thanks for help. I bookmarked this blog so I will follow your posts about Magento. Continue with the great job and write something about adding external images to the products in the future :) . Enjoy!

        • Subesh Pokhrel
          February 16, 2010 at 4:13 am #

          Thanks.. Will look into that. :)

          • February 18, 2010 at 10:28 am #

            Hey! It’s me again. Just to let you know that I already solved issue with adding external images but i have another problem or issue. It’s better to ask here than on official magento forum :) .

            What’s the best way to get next product ID or product entity_id? It’s kind of strange I can add product with custom code and product is normally listed when you look at the admin panel. If I delete this product in admin panel then and tried to add another, product has the same ID (entity_id) as previous which was deleted. This is not a problem but if previous (deleted) product has custom options I then see previous product options as a options of this new product. It looks like previous product is not entirely deleted or I should give new product a new entity_id. But how I could do this?

            I tried to add product in magento admin panel and if you delete last product (for example: id:3000) and insert new one this new product will get different entity_id (3001 in that case and not 3000 even if entity_id 3000 not exist) than previous product did.

          • Subesh Pokhrel
            February 18, 2010 at 12:17 pm #

            I don’t know how you got this “situation”,!!! but I assume the when you re-create product by code, your product model already has the previous product_ID associated with it.. don’t know if its good to tell this.. or not.. but try re-creating product after you have cleared your browser cache… or load page on another browser….

            Do reply back…This should not be a problem.. must be some logical.. mistakes.. code may be up/down.. you know..those situations..I guess.. :D

          • March 25, 2010 at 6:59 pm #

            Even its strange to me..
            this shud not be happening..
            ..
            im writing this code on the catalog/product/view.phtml page after the first two lines of code
            $_helper = $this->helper(’catalog/output’);
            $_product = $this->getProduct();
            ..
            now after this
            if(!$this->hasOptions()){
            //a custom option shud be created using your script here
            // after this is added the following 2 line
            $_product->setHasOptions(1); //line 1
            $_product->save(); //line 2
            }
            after adding these 2 line i get an error for duplicate key ’4-1′…..
            and when i remove these 2 lines then nothing happens.. no option is added..
            ..

          • March 25, 2010 at 7:56 pm #

            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’ “

      • December 9, 2010 at 4:56 am #

        Hi,

        I have a problem. To where add this code? I know very little about magento. So please answer my question ASAP with the exact path to the file.

        Thank You,
        Kasun

        • admin
          December 9, 2010 at 8:48 am #

          Easiest method is to add code on class Mage_Catalog_Model_Convert_Adapter_Product, path would be app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php. But this is not recommended, please create a module that extends this class and add this code there.

          • December 10, 2010 at 2:39 am #

            Thanks for the reply. But it did not work for me. may be I put the second code snippet in the wrong place. If you can please tell me where to put the below code.

            $arrayOption = array();
            /**
            * For Creating dropdown,select,multiselect,radio type of custom option
            */
            $arrayOption[] = setCustomOption(“OPT1,OPT2″, “Select Option”, “drop_down”);
            /**
            * For Creating textfield and textarea type of custom option
            */
            $arrayOption[] = setCustomOption(“Anyvalue”, “Area”, “area”, true);
            /**
            * Load the product you want to assign custom option to
            */
            $product = Mage::getModel(“catalog/product”)->load(167);
            foreach ($arrayOption as $options) {
            foreach ($options as $option) {
            $opt = Mage::getModel(‘catalog/product_option’);
            $opt->setProduct($product);
            $opt->addOption($option);
            $opt->saveOptions();
            }
            }

            Thanks,
            Kasun Withana

  3. February 19, 2010 at 10:47 am #

    Well thanks for your fast reply as usually :)

    I use your custom options function (above) i just change it a little bit so I could also set the different prices for different options. I get last inserted product entity_id from Magento and increase it for 1 and assign this entity_id to a new product which I add it with custom script. If I do this all works fine except if I delete this product in admin panel. Then this entity_id doesnt exist and I got the same entity_id number as before. Then I get this issue with custom options which i described it in my previous post.

    I also tried not to assign entity_id for new product so magento does this automatically but then your custom option script doesn’t work. When i open product in admin panel there is no custom options.

    Don’t know where the problem is right now but will tried to figure out something. It’s not so big problem for me right now because this only happens when you delete last product in magento admin. It’s not perfect I know but this is still better way than slowly product adding in magento admin :)

    By the way thanks for all your help and tips. I really appreciate this. I will follow your blog like i said before and if i will have any problems or question I will let you know :)

    • Dimitrios Mistriotis
      July 8, 2010 at 4:15 pm #

      Dear Guys,

      I am experiencing exactly the same behaviour: The options which were added programmatically are visible only when I add another one. I tried to set the field with the following two ways:
      $editProduct->setHasOptions(1);
      $editProduct->setData(‘has_options’, 1);

      but nothing happened.
      Since your posts are a little bit old right now, has anything happened in between?

      • Banifou
        January 3, 2012 at 11:11 am #

        Same for me and I’m using Magento 1.6.1! Does anybody solved this strange behaviour?

        Thanks

  4. February 19, 2010 at 10:52 am #

    By the way I just noticed. Smileys on this blog in comments are always at the beginning of the row i guess not there where you write it :)

  5. Silverscreen
    February 20, 2010 at 4:51 pm #

    Great script, but very strange results…

    When I run the script, no errors but also no custom options in the admin and the frontend. Then I add a custom option by hand with the admin and then suddenly the custom option just created showed up AND also the custom option created with the script.

    Any suggestions? This is kinda crazy…

    • Subesh Pokhrel
      February 21, 2010 at 7:12 am #

      Yeha.. That’s Crazy indeed……..!! It should not behave in that way… but still… I think you may have misplaced something here and there…. like the product model. I’ve checked the above script before posting here.

    • February 22, 2010 at 10:11 am #

      Silverscreen: Do you assign entity_id to the product or Magento does this instead of you? I have the same results when I didn’t assign entity_id to the new product but leave it blank and then Magento did this for me. Try to get last entity_id from Magento and increase it by one and assign it to the new product. If i do this this script works nice otherwise i have the same result as you.

      • Silverscreen
        February 22, 2010 at 11:47 am #

        Hi Reviews,

        I use the API to create the products so Magento assigns a new entity_id to the product. I will look into this…

        How do you create the products Subesh?

        • Subesh Pokhrel
          February 22, 2010 at 12:16 pm #

          I’ve used this code while importing product from CSV Files, Created product and added Custom option there….Not using API’s!

    • Silverscreen
      February 22, 2010 at 12:28 pm #

      Great!

      I found the solution. Set ‘has_options’ to ’1′ when creating the product with the Magento API.

      Thanks Reviews and Subesh!

      • Subesh Pokhrel
        February 22, 2010 at 1:03 pm #

        Good For you! :D

  6. February 26, 2010 at 10:51 am #

    Hey it’s me again :) I have one more question for you regarding product images. How can i remove specific product image. Let’s say that product has 3 different images and i want to remove one of them. I tried many things but now i am stuck.
    I tried with this:
    $product->getData(“media_gallery”);
    Which returns me an array of pictures. I then try to remove one item (picture) from array and resave it with:
    $product->setData(“media_gallery”, $new_array);
    $product->save();
    But nothing happened. $new_array has the same structure as I get it with $product->getData(“media_gallery”); just with one item (picture) less.
    I also tried with this:
    $product->addImageToMediaGallery(‘FULL_IMAGE_PATH”,array(‘thumbnail’,'small_image’,'image’),false,TRUE);
    but nothing happened.
    Do you have any suggestion or any good tips?
    If I already asking you about the pictures I also don’t know how to get all thumbnail picture urls not just one (I think that just default thumbnail picture with getThumbnailUrl(); What about others if there are more than one product picture?

    I hope i am not annoying and I am pretty sure you will have any good tip for this :)

  7. March 25, 2010 at 3:41 pm #

    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.

  8. Winddancer
    April 8, 2010 at 7:49 pm #

    Dear Subesh,
    thanks a lot for this great addon! Works like a charm with a modified csv impport!

    However I am stuck on a very frustrating problem which I cannot seem to find a solution to. As I am having a Multi language store, I would like to import several languages.

    Furthermore it doesn’t seem so as if I could hand over the “store_id” to the addOption function.

    Do you have any clue or tipp for me how to handle this issue with multiple languages? I guess a lot more people will have the same problems…

    kind regards

    winddancer

    I have made an import profile for each language (english as my main) and the values are all store correctly in the db.

    However the options are not saved correctly. Either a new set for options is added to the product in the default language or it is overwritten.

    • Subesh Pokhrel
      April 9, 2010 at 12:47 pm #

      I have not worked out your situation but from the first impression I think you need to load store specific product ($product) and then set options.

      To load store specific product data you can see here: http://goo.gl/SsBM

      • Winddancer
        April 10, 2010 at 1:05 am #

        Hi again,

        I’ve spent more time on this issue.

        I can import store specific content. eg. basic import store 0 is english and store 2 is german. I normaly import Base data first and then the language specifc import. The translations are being generated and store correctly.

        When I add German option to the content. The option type titles (Let’s say they are colors red, blue, green) are store twice to the sql table. 2 x red, 2x blue and 2x green. Each color with a setting for store_id 0 and store_id 2. Furthermore magento imports this option as an additional option. so i have two option fields, whereas I only need one which has the correct translations.

        I have done some research on this an some other script deletes all previous options like this:

        foreach ($product->getOptions() as $o) {
        $o->getValueInstance()->deleteValue($o->getId());
        $o->deletePrices($o->getId());
        $o->deleteTitles($o->getId());
        $o->delete();
        }

        Which leaves me with the the german options 2x red, 2x blue and 2x green.

        Maybe I am just on the wrong track and need a new hint on how to do this. So if u have any other idea how this could work out, i’d be most happy!

        kind regards

        Winddancer

  9. April 15, 2010 at 2:31 am #

    Is there a way to replace the product price, with custom options? In fact I don’t want the price displayed I want the custom option prices displayed in the drop down

    Thanks
    Great Blog

  10. Silverscreen
    May 10, 2010 at 12:46 pm #

    Has anybody found a solutions for using this approach to a installation with multiple store views (for example multilingual shops)? Any news from Winddancer?

    The 1.4.0.1 has a new option available ‘Use Default Value’ when selecting a non default store view.

  11. Steve
    May 10, 2010 at 7:19 pm #

    I was wondering what specific files do I place these code segments in? Thanks a lot!

  12. Matte
    May 14, 2010 at 11:01 am #

    Rupesh, did you find a solution?

    I need it too…

  13. Ali
    May 18, 2010 at 1:54 pm #

    I am wondering how to retrieve the sku of a selected custom option for a product on the front-end (for example, in cart) — any ideas?

  14. October 6, 2010 at 9:23 am #

    For those who can’t see the custom options in product backend :

    instead of using this code :

    $product = Mage::getModel(“catalog/product”)->load(167);
    foreach ($arrayOption as $options) {
    foreach ($options as $option) {
    $opt = Mage::getModel(‘catalog/product_option’);
    $opt->setProduct($product);
    $opt->addOption($option);
    $opt->saveOptions();
    }
    }

    use (works in Product API in Magento 1.4.1.0)

    $product = Mage::getModel(“catalog/product”)->load(167);
    $product->setProductOptions($arrayOptions);
    // This method set ‘has_options’ = 1 to the product
    $product->save();

    Hope this can help !

  15. sonu
    November 16, 2010 at 9:44 am #

    hi subesh, it may sounds funny but am pretty new to magento. could you please tell me where to use this function, i mean do i need to create a module.

    • admin
      November 16, 2010 at 12:20 pm #

      You can add this function on core files as well but it is a better practice to make your own module and add these codes.

  16. magentokid
    December 30, 2010 at 6:53 am #

    Nice Tutorial

    I want to add custom options in my own module but i am confuse for designing the database please help me on this topic.

  17. Sumi
    March 26, 2011 at 9:09 am #

    Hi,

    When i tried this code in my custom module (magento v1.5.0.1) I’m getting this error. SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘title’ cannot be null
    Kindly advice..

  18. June 6, 2011 at 7:19 am #

    Using Magento 1.5.1.0 I found that the following needs to be added to the above scripts:

    $product->setCanSaveCustomOptions(true);
    $product->save();

Leave a Comment