Quantcast
Channel: MageDev » magento development
Viewing all articles
Browse latest Browse all 2

Adding custom options dynamically

$
0
0

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.


Viewing all articles
Browse latest Browse all 2

Trending Articles