Editable List Item Field Using System Xml


Add field in your system xml file like below

<fields>
<product_additem translate="label">
                            <label>Media Source</label>
                            <backend_model>adminhtml/system_config_backend_serialized_array</backend_model>
							<frontend_model>synchronise/adminhtml_system_config_form_field_additem</frontend_model>	
                            <sort_order>31</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <comment>Add Item</comment>
                        </product_additem>	
										</fields>

Now you need to create a file to render html that is frontend_model.create file with Additem.php in your module adminhtml folder path.and write below code in it.

<?php
class <Namespace>_<Module>_Block_Adminhtml_System_Config_Form_Field_Additem extends Mage_Adminhtml_Block_System_Config_Form_Field_Regexceptions
{
    public function __construct()
    {
        $this->addColumn('title', array(
            'label' => Mage::helper('adminhtml')->__('Title '),
            'style' => 'width:120px',
        ));
        $this->addColumn('link', array(
            'label' => Mage::helper('adminhtml')->__('Link'),
            'style' => 'width:120px',
        ));
        $this->addColumn('image', array(
            'label' => Mage::helper('adminhtml')->__('Media'),
            'style' => 'width:120px',
        ));	
        $this->addColumn('content', array(
            'label' => Mage::helper('adminhtml')->__('Content'),
            'style' => 'width:220px',
        ));			
        $this->_addAfter = false;
        $this->_addButtonLabel = Mage::helper('adminhtml')->__('Add Item');
        Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract::__construct();
    }
    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
    {
        $this->setElement($element);
        $html = $this->_toHtml();
        $this->_arrayRowsCache = null; // doh, the object is used as singleton!
        $html ='<div id="myeditableitem">'.$html.'</div>';
	return $html;
    }	
}

Now you have a editable field for your configuration setting like below images.
additem1

additem2

System configuration field dependency


Here is the xml.
system_config_source_productSources return two option i.e(product,catalog) so dependency set base on this option selection.

<product_source translate="label">
		            		<label>Product Source</label>
		            		<frontend_type>select</frontend_type>
		            		<source_model>basicproducts/system_config_source_productSources</source_model>		            		
		            		<sort_order>10</sort_order>
		            		<show_in_default>1</show_in_default>
							<show_in_website>1</show_in_website>
							<show_in_store>1</show_in_store>
						</product_source>
						<product_category translate="label">
		            		<label>Select Category</label>
		            		<frontend_type>multiselect</frontend_type>
		            		<source_model>basicproducts/system_config_source_listCategory</source_model>
		            		<sort_order>20</sort_order>
		            		<show_in_default>1</show_in_default>
							<show_in_website>1</show_in_website>
							<show_in_store>1</show_in_store>
							<depends><product_source>catalog</product_source></depends>
						</product_category>
						<product_ids translate="label">
							<label>IDs of Products</label>
		            		<frontend_type>text</frontend_type>
		            		<comment>Separator by comma (,). Eg: 1,2,3,4...</comment>
		            		<sort_order>30</sort_order>
		            		<show_in_default>1</show_in_default>
							<show_in_website>1</show_in_website>
							<show_in_store>1</show_in_store>
							<depends><product_source>product</product_source></depends>
						</product_ids>
		            	<product_order_by translate="label">
		            		<label>Product Order by</label>
		            		<frontend_type>select</frontend_type>
		            		<source_model>basicproducts/system_config_source_orderBy</source_model>
		            		<sort_order>40</sort_order>
		            		<show_in_default>1</show_in_default>
							<show_in_website>1</show_in_website>
							<show_in_store>1</show_in_store>
							<depends><product_source>catalog</product_source></depends>
						</product_order_by>
		            	<product_order_dir translate="label">
		            		<label>Product Order Dir</label>
		            		<frontend_type>select</frontend_type>
		            		<source_model>basicproducts/system_config_source_orderDirection</source_model>
		            		<sort_order>50</sort_order>
		            		<show_in_default>1</show_in_default>
							<show_in_website>1</show_in_website>
							<show_in_store>1</show_in_store>
							<depends><product_source>catalog</product_source></depends>
						</product_order_dir>

Image display problem after save in custom module


If you Save the Form for the second time without image. An empty array value will get inserted in the database, Which makes the previous image preview disappear.like below image
image-preview-disappear

To resolve this The save function of the Adminhtml Controller of the custom module must be updated as shown in the below code.

public function saveAction() {
  if ($data = $this->getRequest()->getPost()) {

	if(isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
		try {
		     /* File Upload code here */
		     $uploader = new Varien_File_Uploader('filename');
		     // remaining lines
		 } catch (Exception $e) {

		 }

             //this way the name is saved in DB
   	$data['filename'] = $_FILES['filename']['name'];
      }
//--- Else Condition must be added to Prevent Image Preview Disappear ---
      else {
        unset($data['filename']);  // Unset filename part when image upload field is empty
      }
}

imageprview

Magento Tips and Tricks


How to call staic block any XML file

<reference name="left">
    <block type="cms/block" name="sample_block" before="-">
        <action method="setBlockId"><block_id>sample_block</block_id></action>
    </block>   
</reference> 

How to call staick block in your template or .phtml files

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('my_static_block_name')->toHtml() ?>

How to call static block in CMS->Pages

{{block type="cms/block" block_id="your_block_id"}}

How to call staick block in your template or .phtml files

<?php echo $this->getLayout()->createBlock('page/html')->setTemplate('page/html/homepageleft.phtml')->toHtml();?>

Filter Variable

Mage::getModel('core/email_template_filter')->filter($description); /* for filter */
Mage::getModel('core/email_template_filter')->setVariables(array('custom_url' => Mage::getUrl('*/*/custom'), 'custom_var' => 100))->filter($description); /* for adding custom variable */

Increase memory limit and execution time
Put it on your index.php file

ini_set("memory_limit","10000M");
ini_set("post_max_size","30M");
ini_set("max_execution_time",1000);
ini_set("max_input_time",1000);

Get URL by Type

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
//http://magento.demo/js/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
//http://magento.demo/index.php/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
//http://magento.demo/media/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
//http://magento.demo/skin/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
//http://magento.demo/

Add or remove css Or Js in any specific page with block class

$headBlock = $this->getLayout()->getBlock('head');
$headBlock->addJs('somefolder/yay.js');
$this->getLayout->getBlock('head')->removeItem('js', 'calendar/calendar.js');

Get Admin skin/images url in magento


Mage::getDesign()->getSkinUrl('images/success_msg_icon.gif')

Get Adminhtml url for custom module


$URL = Mage::helper("adminhtml")->getUrl("mymodule/adminhtml_mycontroller/myaction/",array("param1"=>1,"param2"=>2));

or

$URL = Mage::helper("adminhtml")->getUrl("mymodule/adminhtml_mycontroller/myaction/");

Check if customer is logged in

if(!Mage::getSingleton('customer/session')->isLoggedIn())
{
 $this->_redirect('customer/account/login/');
}

Load Database row using your custom field

 $element = Mage::getModel('module/model')
            ->load($value, $key); 

Get addition custom option for configurable product on cart

$session                    = Mage::getSingleton('checkout/session');
$helper = Mage::helper('catalog/product_configuration');
foreach ($session->getQuote()->getAllItems() as $item) {
$customOptions = $helper->getCustomOptions($item)
}

First and Last collection item in Magento


What if we need only the first or last item from the collection, Magento gives an alternate way to do this

$product_collection = Mage::getModel('catalog/product')
        ->getCollection()
        ->addAttributeToSelect('*');

echo $product_collection->getFirstItem()->getName();
 
echo $product_collection->getLastItem()->getName();

Multiple db tables in single custom module in Magento


Step 1. Create setup file of your custom module or create table from your phpMyadmin.

CREATE TABLE `test` (
`test_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 25 ) NOT NULL
) ENGINE = MYISAM 

CREATE TABLE `test2` (
`test2_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 25 ) NOT NULL
) ENGINE = MYISAM 
 

Step 2. Create module file to register your module under app/etc/modules/Mypackage_Mymodule.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Mypackage_Mymodule>
            <active>true</active>
            <codePool>local</codePool>
        </Mypackage_Mymodule>
    </modules>
</config> 
 

Step 3. Your module configuration file should looks like following

app/code/local/ Mypackage/Mymodule/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Mypackage_Mymodule>
            <version>0.1.0</version>
        </Mypackage_Mymodule>
    </modules>
    <global>
        <models>
			<Mymodule>
				<class>Mypackage_Mymodule_Model</class>
				<resourceModel>mymodule_mysql4</resourceModel>
			</mymodule>
			
			<!-- model vs db table relation -->
            <mymodule_mysql4>
                <class>Mypackage_Mymodule_Model_Mysql4</class>
				<!-- db table with name test -->
                <entities>
                    <test>
                        <table>test</table>
                    </test>
		     <test2>
                        <table>test2</table>
                    </test2>

                </entities>
            </mymodule_mysql4>
        </models>
		<resources>
			<mymodule_write>
				<connection>
					<use>core_write</use>
				</connection>
			</mymodule_write>
			<mymodule_read>
				<connection>
					<use>core_read</use>
				</connection>
			</mymodule_read>
		</resources>
    </global>
</config>

 

Step 4. Now create models Test.php and Test2.php. Here we configure these model with the handler of table test and test2.

/app/code/local/Mypackage/Mymodule/Model/Test.php

<?php

class Mypackage_ Mymodule_Model_Test extends Mage_Core_Model_Abstract
{
	
	public function _construct()
    {
        parent::_construct();
        $this->_init('mymodule/test');
    }
}

/app/code/local/Mypackage/Mymodule/Model/Test2.php

<?php

class Mypackage_Mymodule_Model_Test2 extends Mage_Core_Model_Abstract
{
	
	public function _construct()
    {
        parent::_construct();
        $this->_init('mymodule/test2');
    }
}

Step 5. Now create the resource models for model test and test2. In these files we also set the primary key of both the tables test and test2.

/app/code/local/Mypackage/Mmodule/Model/Mysql4/Test.php.

<?php

class Mypackage_Mymodule_Model_Mysql4_Test extends Mage_Core_Model_Mysql4_Abstract
{
    public function _construct()
    {    
        $this->_init('mymodule/test', 'test_id');
    }
}

/app/code/local/Mypackage/Mmodule/Model/Mysql4/Test2.php.

<?php

class Mypackage_Mymodule_Model_Mysql4_Test2 extends Mage_Core_Model_Mysql4_Abstract
{
    public function _construct()
    {    
        $this->_init('mymodule/test2', 'test2_id');
    }
}

Step 6. Create a collection classes so that we can retrieve data from table test and test2.

/local/Mypackage/Mymodule/Model/Mysql4/Test/Collection.php

<?php

class Mypackage_Mymodule_Model_Mysql4_Test_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('mymodule/test');
    }
}

/local/Mypackage/Mymodule/Model/Mysql4/Test2/Collection.php

<?php

class Mypackage_Mymodule_Model_Mysql4_Test2_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('mymodule/test2');
    }
}

So, now you have a custom module with two tables. Your module can interact with these tables with their models and respective collections as follows

$testModel = Mage::getModel('mymodule/test')
	->setName("abcd")
	->save();

$test2Model = Mage::getModel('mymodule/test2')
	->setName("abcd")
	->save();

How to remove test data from Magento?


Before going live, you might need to empty your testing data from your webshop. We will explain in this post, how to remove products, categories, orders and customers with a simple sql query (use PhpMyAdmin for that). Note that we work on Magento 1.7. Every time make a backup before executing such query.

Remove All Test Products

 
SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_link_type`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_product_entity`;
     
TRUNCATE TABLE `cataloginventory_stock`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;
     
INSERT  INTO `catalog_product_link_type`(`link_type_id`,`code`) VALUES (1,'relation'),(2,'bundle'),(3,'super'),(4,'up_sell'),(5,'cross_sell');
INSERT  INTO `catalog_product_link_attribute`(`product_link_attribute_id`,`link_type_id`,`product_link_attribute_code`,`data_type`) VALUES (1,2,'qty','decimal'),(2,1,'position','int'),(3,4,'position','int'),(4,5,'position','int'),(6,1,'qty','decimal'),(7,3,'position','int'),(8,3,'qty','decimal');
INSERT  INTO `cataloginventory_stock`(`stock_id`,`stock_name`) VALUES (1,'Default');
SET FOREIGN_KEY_CHECKS=1;

Remove test categories

TRUNCATE TABLE `catalog_category_entity`;
TRUNCATE TABLE `catalog_category_entity_datetime`;
TRUNCATE TABLE `catalog_category_entity_decimal`;
TRUNCATE TABLE `catalog_category_entity_int`;
TRUNCATE TABLE `catalog_category_entity_text`;
TRUNCATE TABLE `catalog_category_entity_varchar`;
TRUNCATE TABLE `catalog_category_product`;
TRUNCATE TABLE `catalog_category_product_index`;
 
INSERT  INTO `catalog_category_entity`(`entity_id`,`entity_type_id`,`attribute_set_id`,`parent_id`,`created_at`,`updated_at`,`path`,`POSITION`,`level`,`children_count`) VALUES (1,3,0,0,'0000-00-00 00:00:00','0000-00-00 00:00:00','1',1,0,1), (2,3,3,1,'0000-00-00 00:00:00','0000-00-00 00:00:00','1/2','1','1','0');
INSERT  INTO `catalog_category_entity_int`(`value_id`,`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`) VALUES (1,3,32,0,2,1),(2,3,36,0,2,1),(3,3,61,0,2,1),(4,3,44,0,2,NULL),(5,3,45,0,2,1),(6,3,62,0,2,1),(7,3,63,0,2,1),(8,3,64,0,2,NULL);
INSERT  INTO `catalog_category_entity_varchar`(`value_id`,`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`) VALUES (1,3,31,0,1,'Root Catalog'),(2,3,35,0,2,'Default Category'),(3,3,37,0,2,'default-category'),(4,3,40,0,2,NULL),(5,3,43,0,2,'PRODUCTS'),(6,3,52,0,2,NULL),(7,3,55,0,2,NULL);  

Remove test customers

TRUNCATE TABLE `customer_address_entity`;
TRUNCATE TABLE `customer_address_entity_datetime`;
TRUNCATE TABLE `customer_address_entity_decimal`;
TRUNCATE TABLE `customer_address_entity_int`;
TRUNCATE TABLE `customer_address_entity_text`;
TRUNCATE TABLE `customer_address_entity_varchar`;
TRUNCATE TABLE `customer_entity`;
TRUNCATE TABLE `customer_entity_datetime`;
TRUNCATE TABLE `customer_entity_decimal`;
TRUNCATE TABLE `customer_entity_int`;
TRUNCATE TABLE `customer_entity_text`;
TRUNCATE TABLE `customer_entity_varchar`;

Remove test orders

SET FOREIGN_KEY_CHECKS=0;

TRUNCATE `sales_flat_creditmemo`;
TRUNCATE `sales_flat_creditmemo_comment`;
TRUNCATE `sales_flat_creditmemo_grid`;
TRUNCATE `sales_flat_creditmemo_item`;
TRUNCATE `sales_flat_invoice`;
TRUNCATE `sales_flat_invoice_comment`;
TRUNCATE `sales_flat_invoice_grid`;
TRUNCATE `sales_flat_invoice_item`;
TRUNCATE `sales_flat_order`;
TRUNCATE `sales_flat_order_address`;
TRUNCATE `sales_flat_order_grid`;
TRUNCATE `sales_flat_order_item`;
TRUNCATE `sales_flat_order_payment`;
TRUNCATE `sales_flat_order_status_history`;
TRUNCATE `sales_flat_quote`;
TRUNCATE `sales_flat_quote_address`;
TRUNCATE `sales_flat_quote_address_item`;
TRUNCATE `sales_flat_quote_item`;
TRUNCATE `sales_flat_quote_item_option`;
TRUNCATE `sales_flat_quote_payment`;
TRUNCATE `sales_flat_quote_shipping_rate`;
TRUNCATE `sales_flat_shipment`;
TRUNCATE `sales_flat_shipment_comment`;
TRUNCATE `sales_flat_shipment_grid`;
TRUNCATE `sales_flat_shipment_item`;
TRUNCATE `sales_flat_shipment_track`;
TRUNCATE `sales_invoiced_aggregated`;
TRUNCATE `sales_invoiced_aggregated_order`;
TRUNCATE `log_quote`;
 
ALTER TABLE `sales_flat_creditmemo_comment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_creditmemo_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_creditmemo_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice_comment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_address` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_payment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_status_history` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_payment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_shipping_rate` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_comment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_track` AUTO_INCREMENT=1;
ALTER TABLE `sales_invoiced_aggregated` AUTO_INCREMENT=1;
ALTER TABLE `sales_invoiced_aggregated_order` AUTO_INCREMENT=1;
ALTER TABLE `log_quote` AUTO_INCREMENT=1;
 
TRUNCATE `downloadable_link_purchased`;
TRUNCATE `downloadable_link_purchased_item`;
 
ALTER TABLE `downloadable_link_purchased` AUTO_INCREMENT=1;
ALTER TABLE `downloadable_link_purchased_item` AUTO_INCREMENT=1;
 
TRUNCATE `eav_entity_store`;
ALTER TABLE  `eav_entity_store` AUTO_INCREMENT=1;

SET FOREIGN_KEY_CHECKS=1;

Create custom option programatically magento


If you want to create product custom option dynamically using observer when creating product just follow the steps.

Add below code in you module etc file.

<events>
	  <catalog_product_save_before> <!-- identifier of the event we want to catch -->
        <observers>
          <catalog_product_save_before_handler> <!-- identifier of the event handler -->
            <type>singleton</type> <!-- class method call type; valid are model, object and singleton -->
            <class>customoptioncreater/observer</class> <!-- observers class alias -->
            <method>createMyCustomOption</method>  <!-- observer's method to be called -->
           </catalog_product_save_before_handler>
        </observers>
</event

Create observer for listen event

public function createMyCustomOption(Varien_Event_Observer $observer)
    {
        $product = $observer->getProduct();
        
        if ($product->getAdult() != '' && $product->getChild() != '') {
            
            
            $options = $product->getProductOptions();
            if ($options) {
                foreach ($options as $option) {
                    
                    if ($option['title'] == 'Adult' || $option['title'] == 'Child') {
                        //we've already added the option
                        return;
                    }
                    
                }
            }
            $adult         = $product->getAdult(); /* this is my custom attribute to get value */
            $adultPrice    = $product->getAdultPrice();  /* this is my custom attribute to get value */
            $child         = $product->getChild();  /* this is my custom attribute to get value */
            $childPrice    = $product->getChildPrice();  /* this is my custom attribute to get value */
            $isRequired    = array(
                1,
                0
            );
            $optionTitle   = array(
                'Adult',
                'Child'
            );
            $optionPrice   = array(
                $adultPrice,
                $childPrice
            );
            $adultchildFor = array(
                $adult,
                $child
            );
            $optionsArray  = $this->getOptions($optionTitle, 'drop_down', $adultchildFor, $optionPrice, $isRequired);
            try {
                $product->setCanSaveCustomOptions(true);
                foreach ($optionsArray as $option) {
                    $product->getOptionInstance()->addOption($option);
                }
                
                $product->setHasOptions(true);
            }
            catch (Exception $e) {
                Mage::Log($e->getMessage());
            }
            //echo '<pre>';
            
            //print_r($options);
            //exit;
            //$productmo = Mage::getModel('catalog/product')->load($product->getId());
            //$productmo->setProductOptions($options);
            //$productmo->setCanSaveCustomOptions(true);
            //$productmo->setHasOptions(1)->save();
            //return;
        }
        
    }
    
    protected function getOptions($title = '', $type = '', $adultchildFor, $optionPrice, $isRequired)
    {
        
        if (is_array($title)) {
            $j = 0;
            foreach ($title as $ttl) {
                $option[$j]               = array();
                $optionvalue              = array();
                $option[$j]['title']      = $ttl;
                $option[$j]['type']       = $type;
                $option[$j]['is_require'] = $isRequired[$j];
                $option[$j]['sort_order'] = $j;
                for ($i = 1; $i <= $adultchildFor[$j]; $i++) {
                    $optionvalue[$i]['title']      = $i;
                    $optionvalue[$i]['price']      = $i * $optionPrice[$j];
                    $optionvalue[$i]['price_type'] = 'fixed';
                    $optionvalue[$i]['sku']        = '';
                    $optionvalue[$i]['sort_order'] = $i;
                    
                }
                $option[$j]['values'] = $optionvalue;
                $j++;
            }
        } else {
            $optionvalue = array();
            for ($i = 1; $i <= $for; $i++) {
                $optionvalue[$i]['title']      = $i;
                $optionvalue[$i]['price']      = $i * $price;
                $optionvalue[$i]['price_type'] = 'fixed';
                $optionvalue[$i]['sku']        = '';
                $optionvalue[$i]['sort_order'] = $i;
            }
            $option = array(
                'title' => (string) $title,
                'type' => $type, // could be drop_down ,checkbox , multiple
                'is_require' => $isrequired,
                'sort_order' => 0,
                'values' => $optionvalue
            );
            
            
        }
        return $option;
    }

and you are done.Happy Codding 🙂