Subesh Pokhrel's Blog – Magento Development Tips,PHP,Google Maps
PHP & Magento Tips & Tutorials
Share

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!

  • Share/Bookmark

You may also be interested

Comments

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

  1. 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. 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 says:

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

      Thanks for the response!

      • 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 says:

          Thanks.. Will look into that. :)

          • 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.

  3. 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 :)

  4. 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 says:

    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 says:

      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.

    • 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 says:

        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 says:

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

    • Silverscreen says:

      Great!

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

      Thanks Reviews and Subesh!

  6. 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. Subesh Pokhrel says:

    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

Write a Comment

Search engine optimization by SEO Design Solutions