Skip to content

Magento add front end theme for emails from admin.

Emails from Magento admin panel uses the admin theme for sending emails. But, we can set it to use front end theme for custom emails by setting ‘setDesignConfig’ method for email model as shown below:

    $mail                            = Mage::getModel('core/email_template');
    $translate                       = Mage::getSingleton('core/translate');
    $storeId                         = 1; // Use front end store ID         
    $fromName                        = Mage::getStoreConfig('trans_email/ident_general/name');
    $fromEmail                       = Mage::getStoreConfig('trans_email/ident_general/email');
    $senderArr                       = Array('email' => $fromEmail, 'name' =>$fromName );
    $ccEmail                         = 'CC EMAIL – IF ANY';
    $mail->getMail()->addCc($ccEmail);    
    $toEmail                         = 'test@test.com';
    $toName                          = 'TO NAME';   
    $templateId                      = 'ID OF THE TEMPLATE TO BE USED';
    $mail->setDesignConfig(array('area'=>'frontend', 'store'=>$storeId));
    $mail->sendTransactional($templateId, $senderArr, $toEmail,$toName,$templateVars,$storeId);
    $translate->setTranslateInline(true);
Advertisements

Magento: Get details of associated products of a configurable

Below script can be used to fetcht the details of associated simples of a configurable product, it’s options and other related data.

$configID = '34'; /* ID of the configurable product */
$product  = Mage::getModel('catalog/product')->load($configID); /* Load product by id*/
 if ($product->type_id == 'configurable') { /* Check product type is configurable*/
            $options          = array();            
            // Get any super_attribute settings we need
            $productAttributesOptions  = $product->getTypeInstance(true)->getConfigurableOptions($product);
            foreach ($productAttributesOptions as $productAttributeOption) {                
                foreach ($productAttributeOption as $optionValues) { 
                    $attrCode          = $optionValues['attribute_code'];
                    $attributeId       = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product', $attrCode);
                    $associatedProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$optionValues['sku']);
                    $stockStatus       = Mage::getModel('cataloginventory/stock_item') 
                                            ->loadByProduct($associatedProduct)
                                            ->getIsInStock(); /* Get product stock status for associated product */
                    $saleable          = $associatedProduct->isSaleable();
                    $attribute_value   = $product->getResource()->getAttribute($attrCode)->getValue($associatedProduct); 
                    if(empty($pricingValue))  $pricingValue = 0;            
                    $options[$attrCode][]           = array (
                        'attribute_id'                  => $attributeId,
                        'option_id'                     => $optionValues['option_id'],
                        'option_title'                  => $optionValues['option_title'],
                        'pricing_value'                 => $optionValues['pricing_value'],
                        'pricing_is_percent'            => $optionValues['pricing_is_percent'],
                        'simple_id'                     => $associatedProduct->getId(),
                        'saleable'                      => $saleable,
                        'stock_status'                  => $stockStatus                           
                    );
                   
            }
}} 
var_dump($options); /* List all associated options along with simple product details */

Magento theme translator for custom theme.

Magento message or text translation for a custom theme can be easily done by creating a custom CSV file. This is applicable for both Magento core texts as well as custom texts. It can be done as:
1. Create custom locale directory; such as for French language:
[Your theme location]/locale/fr_FR
2.Create custom CSV file with mapping of the translated text whichever you want. Like:
“My Cart”, “My Bag”
“Custom Message”,”Custome Message in French!”

this CSV file should be saved in the above directory as: translate.csv
Please make sure the file is UTF-8 encoded.
3.Set the translation theme location from admin panel:
System > Configuration > Themes > Translations


4. Done! You can call the translated texts just like: echo $this->__(“Custom Message”);

Magento – AJax: Product page out put as JSON

Add ajax parameter along with the page request (http://pageurl?ajax=true).Modify the controller: Mage_Catalog_ProductController by overriding it in to ‘local’ directory. Under ‘public function viewAction()’, add below code which will out put a JSON array with output HTML content along with any other relvent data as JSON content:

public function viewAction(){
        $ajax                 = Mage::app()->getRequest()->getParam('ajax');    
        if($ajax == 'true'){               
              $productId      = (int) Mage::app()->getRequest()->getParam('id');  
              $prodModel      = Mage::getModel('catalog/product')->load($productId); 
              $layout         = Mage::app()->getLayout();  
              $output         = $layout->getOutput();
              $block          = Mage::app()->getLayout()->createBlock('catalog/product_view_type_configurable');/*or any other block which is applicable here     */      
              $block->setProduct($prodModel);
              $prodConfig     = json_decode($block->getJsonConfig());
              $result         = array( 'outputHtml' => $output, 'produtId'=>$productId,'prodConfig' => $prodConfig );
              echo json_encode($result); exit;
        }
}

Programatically create order in Magento.

Below is the script for creating an order in Magento programatically. Assuming the whole input provided in JSON format. The parameters included are:

products

1 configurable product with a ‘super attribute’ along with attribute value and two simple products

email

customer email; there will be a customer account associated with the order if a customer exists with the provided email.

shipping_method

provided Flatrate shipping method.

payment_method

provided as Check/Money order.

billing_addr

Region country IDs should be the same as provided in Magento.

shipping_addr

Region country IDs should be the same as provided in Magento.

<?php
$webDocRoot = '[ YOUR DOCUMENT ROOT]';
$mageFile = $webDocRoot.'app/Mage.php';
if (!file_exists($mageFile)) {
print $mageFile . " was not found";
exit;
}
require $mageFile; 
Mage::app('default'); 
 
 $websiteId = Mage::app()->getWebsite()->getId();
 $store = Mage::app()->getStore();
 echo '<pre/>';
 

 $orderJson = '{"products":{"1":{"type_id": "configurable","product_id": 110,"qty": 3,
 "super_attribute": {"214": 81}},"2":{"type_id": "simple","product_id": 126,"qty": 3,
 "super_attribute": {}},"3":{"type_id": "simple","product_id": 129,"qty": 3,"super_attribute": {}}},
 "email":"test@test.com","payment_method":"checkmo",
 "shipping_method":"flatrate_flatrate","billing_addr":{"customer_address_id":"","prefix":"",
 "firstname":"test","middlename":"","lastname":"test","suffix":"","company":"",
 "street":["street1","street2"],"city":"New York","country_id":"US","region":"NY",
 "postcode":"10120","telephone":"78676789","fax":"gghlhu","vat_id":"",
 "save_in_address_book":1},"shipping_addr":{"customer_address_id":"","prefix":"",
 "firstname":"test","middlename":"","lastname":"test","suffix":"","company":"",
 "street":["street1","street2"],"city":"New York","country_id":"US","region":"NY",
 "postcode":"10120","telephone":"78676789","fax":"gghlhu","vat_id":"","save_in_address_book":1}}';

  $quoteArr         = json_decode($orderJson,true);
  
  $response         = getQuote($quoteArr,$websiteId,$store);
  //print_r(getShippingMethods($response['quote']));  /* For getting shipping methods if needed */
  $shipping_method  = $quoteArr['shipping_method'];
  $payment_method   = $quoteArr['payment_method'];  
  $orderDetails     = placeOrder($response['quote'],$shipping_method,$payment_method);
  print_r($orderDetails); exit;

 /*
 *Create Sales Quote object from the given items and address details
 *By: Author
 *@quote Quote Object
 *@shipping_method String
 *@payment_method String
 *@return array
 */
function placeOrder($quote,$shipping_method,$payment_method)
{   
    $response = array();
    try
    {                         
        $shippingAddress = $quote->getShippingAddress(); 
       
        $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
            ->setShippingMethod('flatrate_flatrate');

        $quote->getPayment()->importData(
        array(            'method'       => 'checkmo' ));           
         $quote->collectTotals()->save();// Collect Totals & Save Quote
         $service = Mage::getModel('sales/service_quote', $quote); // Create Order From Quote             
         $service->submitAll();
         $service->getOrder()->addStatusHistoryComment('Order Created from Mobile Application')->save();
         $increment_id = $service->getOrder()->getRealOrderId();     
         $quote = $customer = $service = null;// Resource Clean-Up
         $response['orderid'] = $increment_id;
         $response['message'] = 'success';
     }
    catch (Exception $e) 
    { 
        $response['message'] = 'Error';
        $response['error']   = serialize($e);
    }

    return $response;
    
}//function placeOrder()

 /*
 *Create Sales Quote object from the given items and address details
 *By: Author
 *@cartdetails array()
 *@$websiteId number
 *@store Number
 *@return array
 */
function getQuote($quoteArr,$websiteId,$store)
{
    $products        = $quoteArr['products']; 
    $email           = $quoteArr['email']; 
    $billing_addr    = $quoteArr['billing_addr'];
    $shipping_addr   = $quoteArr['shipping_addr'];
    $response = array();
    try
    {         
        $quote = Mage::getModel('sales/quote')->setStoreId($store->getId());// Start New Sales Order Quote        
        ///$quote->setCurrency($order->AdjustmentAmount->currencyID); // Set Sales Order Quote Currency
        $customer = Mage::getModel('customer/customer')
            ->setWebsiteId($websiteId)
            ->loadByEmail($email);
        $quote->assignCustomer($customer);     
        $quote->setSendCconfirmation(1);// Configure Notification
        foreach($products as $i=>$currentItem)
        {
            $currentId     = $currentItem['product_id'];
            $curQuantity   = $currentItem['qty'];
            $currentProduct= Mage::getModel('catalog/product')->load($currentId);
            if($currentItem['type_id'] == 'configurable' )
            {
                $params['product']         = $currentId;
                $params['qty']             = $curQuantity;
                $params['super_attribute'] = $currentItem['super_attribute'];
                $request                   = new Varien_Object(); 
                $request->setData($params);
                $quote->addProduct($currentProduct , $request);
            } 
            else if($currentItem['type_id'] == 'simple' )
            {
                $quote->addProduct($currentProduct,new Varien_Object(array('qty'=> $curQuantity)));
            }                        
        } 

        $billingAddress      = $quote->getBillingAddress()->addData($billing_addr);// Set Sales Order Billing Address
        $shippingAddress     = $quote->getShippingAddress()->addData($shipping_addr);// Set Sales Order Shipping Address
        $response['message'] = 'success';
        $response['quote']   = $quote;
    }
    catch (Exception $e) 
    { 
        $response['message'] = 'Error';
        $response['error']   = serialize($e);
    }

    return $response;
}//function getQuote($cartdetails)

/*
*Collect availabe shipping rates for a quote
*By: Author
*@quote Quote Object
*@return Array
*/
function getShippingMethods($quote)
{   
    $response      = array();
    $allowed_rates = array();
    try
    {  
        $quote->getShippingAddress()->setCollectShippingRates(true);
        $quote->getShippingAddress()->collectShippingRates();
        $rates = $quote->getShippingAddress()->getAllShippingRates();  
        foreach ($rates as $rate) 
        { 
            array_push($allowed_rates,$rate->getCode()); 
        }
        $response['message'] = 'Success';
        $response['rates']   = $allowed_rates;
    }
    catch (Exception $e) 
    { 
        $response['message'] = 'Error';
        $response['error']   = serialize($e);
    }
    return $response;
}//functin getShippingMethods()

Magento Newsletter Subscribers – website wide list in custom table

By default Magento does not allow to create website/store wise list of email subscribers.Here, is a module to store email subscribers list along with website,store and custom region attribute. This data are stored in a custom database table; this module includes front end form and admin view of the emails list along with CSV export. Please note that this custom list is not linked with Magento default news letter functionality; so, additional coding needs to be done to send emails using this list.

Follow below steps:
1)Create file:

app/etc/Mynamespace_Newssubscription.xml
<config>
    <modules>
        <Mynamespace_Newssubscription>
            <codePool>local</codePool>
            <active>true</active>
        </Mynamespace_Newssubscription>
    </modules>
</config>

2)Create module configuration file :

 app\code\local\Mynamespace\Newssubscription\etc\config.xml
 
<config>
    <modules>
        <Mynamespace_Newssubscription>
            <version>0.1.0</version>
        </Mynamespace_Newssubscription>
    </modules>
    <global>
        <models>
            <newssubscription>
                <class>Mynamespace_Newssubscription_Model</class>
                <resourceModel>newssubscription_mysql4</resourceModel>
            </newssubscription>
            <newssubscription_mysql4>
                <class>Mynamespace_Newssubscription_Model_Mysql4</class>
                <entities>
                    <newssubscription>
                        <table>newssubscription</table>
                    </newssubscription>
                </entities>
            </newssubscription_mysql4>
        </models>
        <resources>
            <newssubscription_setup>
                <setup>
                    <module>Mynamespace_Newssubscription</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </newssubscription_setup>
            <newssubscription_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </newssubscription_read>
            <newssubscription_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </newssubscription_write>
        </resources>
        <!-- start of block -->
        <blocks>
            <newssubscription>
                <class>Mynamespace_Newssubscription_Block</class>
            </newssubscription>
        </blocks>
          <helpers>
            <mynamespace_newssubscription>
                <class>Mynamespace_Newssubscription_Helper</class>
            </mynamespace_newssubscription>
        </helpers>
    </global>
 
    <!-- start of routers
    -->
    <frontend>
        <routers>
            <newssubscription>
                <use>standard</use>
                <args>
                    <module>Mynamespace_Newssubscription</module>
                    <frontName>newssubscription</frontName>
                </args>
            </newssubscription>
        </routers>
        <layout>
            <updates>
                <newssubscription>
                    <file>newssubscription.xml</file>
                </newssubscription>
            </updates>
        </layout>
    </frontend>
     <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <Mynamespace_Newssubscription before="Mage_Adminhtml">Mynamespace_Newssubscription_Adminhtml</Mynamespace_Newssubscription>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
    <adminhtml>
        <layout>
            <updates>
                <mynamespace_newssubscription>
                    <file>mynamespace/newssubscription.xml</file>
                </mynamespace_newssubscription>
            </updates>
        </layout>
    </adminhtml>
</config>

3)Create admin configuration file:

app\code\local\Mynamespace\Newssubscription\etc\adminhtml.xml
<?xml version="1.0"?> 
<config>
    <menu>
        <newsletter>
            <children>
                <mynamespace_newssubscription_newssubscription translate="title" module="mynamespace_newssubscription">
                    <sort_order>10</sort_order>
                    <title>Mynamespace Newsletters Subcription</title>
                    <action>adminhtml/newssubscription/</action>
                </mynamespace_newssubscription_newssubscription>
            </children>
        </newsletter>
    </menu>
    <acl>
        <resources>
            <admin>
                <children>
                    <newsletter>
                        <children>
                            <mynamespace_newssubscription_newssubscription>
                                <title>Mynamespace Newsletters Subcription</title>
                            </mynamespace_newssubscription_newssubscription>
                        </children>
                    </newsletter>
                </children>
            </admin>
        </resources>
    </acl>
</config>

4)Create databse table using installer file; if there are any issues in table creation, please execute below query directly in databse after replacing the table name to ‘newssubscription’:

app\code\local\Mynamespace\Newssubscription\sql\newssubscription_setup\install.php
<?php
$installer=$this;
$installer->startSetup();
 
$installer->run("
-- DROP TABLE IF EXISTS {$this->getTable('newssubscription')};
  CREATE TABLE {$this->getTable('newssubscription')} (
 `newssubscription_id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Q&A ID',
 `website_id` int(11) NOT NULL COMMENT 'Website Id',
 `store_id` int(11) NOT NULL COMMENT 'Store Id',
 `email` varchar(255) NOT NULL COMMENT 'Customer Name',
 `region` varchar(255) NOT NULL COMMENT 'Customer Email',
 `created_time` datetime DEFAULT NULL,
 `update_time` datetime DEFAULT NULL,
 PRIMARY KEY (`newssubscription_id`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8
 
    ");
$installer->endSetup();
?>

5)Create front end controller; ajax is used for form submittion:

app\code\local\Mynamespace\Newssubscription\controllers\IndexController.php
<?php
class Mynamespace_Newssubscription_IndexController extends Mage_Core_Controller_Front_Action{
 
    public function indexAction(){ 
    	$this->loadLayout(); //Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles()); exit;
	$this->renderLayout();
    }
    public function postAction(){
	$data = $this->getRequest()->getParams(); 
	$model = Mage::getModel('newssubscription/newssubscription')->setData($data);
	try {
	$insertId = $model->save()->getId();
	$response = array();
	if($insertId)
		$response['status'] = '1';
	else
		$response['status'] = '0';
	$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
    return;	
	} catch (Exception $e){
	echo $e->getMessage();  
	}
	    }
}

6)Create admin controller:

app\code\local\Mynamespace\Newssubscription\controllers\Adminhtml\NewssubscriptionController.php
<?php
 
class Mynamespace_Newssubscription_adminhtml_NewssubscriptionController extends Mage_adminhtml_Controller_Action
{
    public function indexAction()
    {  
        $this->_title($this->__('newssubscription'))->_title($this->__('Newssubscription Mynamespace'));
        $this->loadLayout();
        $this->_setActiveMenu('newsletter/newssubscription');        
        $this->renderLayout();
    }
 
    public function gridAction()
    { 
        $this->loadLayout();
        $this->getResponse()->setBody(
            $this->getLayout()->createBlock('newssubscription/adminhtml_newssubscription_grid')->toHtml()
        );
    }
 
    public function exportMynamespaceCsvAction()
    {
        $fileName = 'orders_Mynamespace.csv';
        $grid = $this->getLayout()->createBlock('newssubscription/adminhtml_newssubscription_grid');
        $this->_prepareDownloadResponse($fileName, $grid->getCsvFile());
    }
 
    public function exportMynamespaceExcelAction()
    {
        $fileName = 'orders_Mynamespace.xml';
        $grid = $this->getLayout()->createBlock('newssubscription/adminhtml_newssubscription_grid');
        $this->_prepareDownloadResponse($fileName, $grid->getExcelFile($fileName));
    }

    public function newAction()
    {  
        
        $this->_forward('edit');
    }  
     
    public function editAction()
    {  
        $this->_initAction();     
       
        $id  = $this->getRequest()->getParam('id');
        $model = Mage::getModel('Mynamespace_Newssubscription_Model_Newssubscription');
     
        if ($id) {
            
            $model->load($id);
     
            
            if (!$model->getId()) {
                Mage::getSingleton('adminhtml/session')->addError($this->__('This newssubscription no longer exists.'));
                $this->_redirect('*/*/');
     
                return;
            }  
        }  
     
        $this->_title($model->getId() ? $model->getName() : $this->__('New newssubscription'));
     
        $data = Mage::getSingleton('adminhtml/session')->getNewssubscriptionData(true);
        if (!empty($data)) {
            $model->setData($data);
        }  
     
        Mage::register('mynamespace_newssubscription', $model);
     
        $this->_initAction()
            ->_addBreadcrumb($id ? $this->__('Edit Newssubscription') : $this->__('New Newssubscription'), $id ? $this->__('Edit newssubscription') : $this->__('New newssubscription'))
            ->_addContent($this->getLayout()->createBlock('Mynamespace_Newssubscription_Block_Adminhtml_Newssubscription_Edit')->setData('action', $this->getUrl('*/*/save')))
            ->renderLayout();
    }
     
    public function saveAction()
    {
        if ($postData = $this->getRequest()->getPost()) {
            $model = Mage::getSingleton('Mynamespace_Newssubscription_Model_Newssubscription');
            $model->setData($postData);
 
            try {
                $model->save();
 
                Mage::getSingleton('adminhtml/session')->addSuccess($this->__('The newssubscription has been saved.'));
                $this->_redirect('*/*/');
 
                return;
            }  
            catch (Mage_Core_Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
            catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($this->__('An error occurred while saving this newssubscription.'));
            }
 
            Mage::getSingleton('adminhtml/session')->setNewssubscriptionData($postData);
            $this->_redirectReferer();
        }
    }
     
    public function messageAction()
    {
        $data = Mage::getModel('mynamespace_newssubscription/newssubscription')->load($this->getRequest()->getParam('id'));
        echo $data->getContent();
    }
     
    
    protected function _initAction()
    {
        $this->loadLayout()
            // Make the active menu match the menu config nodes (without 'children' inbetween)
            ->_setActiveMenu('newsletter/mynamespace_newssubscription_newssubscription')
            ->_title($this->__('Newsletter'))->_title($this->__('newssubscription'))
            ->_addBreadcrumb($this->__('Newsletter'), $this->__('Newsletter'))
            ->_addBreadcrumb($this->__('newssubscription'), $this->__('newssubscription'));
         
        return $this;
    }
     
   
    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('newsletter/mynamespace_newssubscription_newssubscription');
    }
}

7)Create Model:

local\Mynamespace\Newssubscription\Model\Newssubscription.php
<?php
class Mynamespace_Newssubscription_Model_Newssubscription extends Mage_Core_Model_Abstract
{
    public function _construct()
    { 
        $this->_init('newssubscription/newssubscription');
    }
 
}

8)Create model resource files:

app\code\local\Mynamespace\Newssubscription\Model\Mysql4\Newssubscription.php
<?php
class Mynamespace_Newssubscription_Model_Mysql4_Newssubscription extends Mage_Core_Model_Mysql4_Abstract
{
    
    public function _construct()
    { 
        $this->_init('newssubscription/newssubscription', 'newssubscription_id');
    }
}

9)Create collection:

app\code\local\Mynamespace\Newssubscription\Model\Mysql4\Newssubscription\Collection.php
<?php 
class Mynamespace_Newssubscription_Model_Mysql4_Newssubscription_Collection 
extends Mage_Core_Model_Mysql4_Collection_Abstract{
	protected function _constuct(){ 
		$this->_init('mynamespace_newssubscription/newssubscription');	
	}
}

10)Create front end block file:

app\code\local\Mynamespace\Newssubscription\Block\Newssubscription.php
<?php
class Mynamespace_Newssubscription_Block_Newssubscription extends Mage_Core_Block_Template{	
     public function _prepareLayout()
    {
    	$this->current_store   = Mage::app()->getStore()->getStoreId();
        $this->current_website = Mage::app()->getStore()->getWebsiteId();        
        $helper  = Mage::helper('mynamespace_newssubscription');
        $this->regins   = $helper->getRegions();
        return parent::_prepareLayout();
    }
	public function getCollection(){
		if(is_null($this->_Collection)){
			$this->_Collection=Mage::getModel('newssubscription/newssubscription')->getCollection();
		}
		return $this->_Collection;
	} 
}

11)Admin block file:

app\code\local\Mynamespace\Newssubscription\Block\Adminhtml\Newssubscription.php
<?php
 
class Mynamespace_Newssubscription_Block_Adminhtml_Newssubscription extends Mage_Adminhtml_Block_Widget_Grid_Container
{
    public function __construct()
    { 
        $this->_blockGroup = 'newssubscription';
        $this->_controller = 'adminhtml_newssubscription';
        $this->_headerText = Mage::helper('mynamespace_newssubscription')->__('Newssubscription - Mynamespace');
 
        parent::__construct();
        $this->_removeButton('add');
    }
}

12)Define admin grid:

app\code\local\Mynamespace\Newssubscription\Block\Adminhtml\Newssubscription\Grid.php
<?php
 
class Mynamespace_Newssubscription_Block_Adminhtml_Newssubscription_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    public function __construct()
    {   
        parent::__construct();
        $this->setId('mynamespace_newssubscription_grid');
        $this->setDefaultSort('newssubscription_id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
    }
 
    protected function _prepareCollection()
    {             
        
        $collection = Mage::getModel('newssubscription/newssubscription')->getCollection();
        $this->setCollection($collection); 
        parent::_prepareCollection();
        return $this;
    }
 
    protected function _prepareColumns()
    { 
        $helper    = Mage::helper('mynamespace_newssubscription');
        $currency  = (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE);
        $helper  = Mage::helper('mynamespace_newssubscription');
        $regions   = $helper->getRegions();
        $storesArr = array();
        $allStores = Mage::app()->getStores();
        foreach ($allStores as $_eachStoreId => $val)
        {
           $_storeName           = Mage::app()->getStore($_eachStoreId)->getName(); 
           $storesArr[$_eachStoreId] = $_storeName;
        }

        $websitesArr = array();
        $allWebsites  = Mage::app()->getWebsites();
        foreach ($allWebsites as $_eachWebid => $val)
        {
           $_webName                 = Mage::app()->getWebsite($_eachWebid)->getName();           
           $websitesArr[$_eachWebid] = $_webName;
        }

        $this->addColumn('newssubscription_id', array(
            'header' => $helper->__('newssubscription_id'),
            'index'  => 'newssubscription_id'
        ));

        $this->addColumn('website_id', array(
            'header'  => $helper->__('Website'),
            'index'   => 'website_id',
            'type'    => 'options',
            'options' => $websitesArr
        ));

         $this->addColumn('store_id', array(
            'header' => $helper->__('Store'),
            'index'  => 'store_id',
            'type'   => 'options',
            'options' => $storesArr,
        ));

          $this->addColumn('region', array(
            'header' => $helper->__('Region'),
            'index'  => 'region',            
            'type'  => 'options',
            'options' => $regions,
        ));

        $this->addColumn('email', array(
            'header' => $helper->__('email'),
             'index'  => 'email', 
            'type'   => 'text'            
        ));
        
         $this->addColumn('action',
            array(
            'header'    =>  Mage::helper('mynamespace_newssubscription')->__('Action'),
            'width'     => '100',
            'type'      => 'action',
            'getter'    => 'getNewssubscriptionId',
            'actions'   => array(
                    array(
                            'caption'   => Mage::helper('mynamespace_newssubscription')->__('Edit'),
                            'url'       => array('base'=> '*/*/edit'),
                            'field'     => 'id'
                    )
            ),
            'filter'    => false,
            'sortable'  => false,
            'index'     => 'stores',
            'is_system' => true,
    ));

      
        $this->addExportType('*/*/exportMynamespaceCsv', $helper->__('CSV'));
        $this->addExportType('*/*/exportMynamespaceExcel', $helper->__('Excel XML'));
 
        return parent::_prepareColumns();
    }

    public function getRowUrl($row)
    {
        
        return $this->getUrl('*/*/edit', array('id' => $row->getId()));
    }
    
    protected function _getCollectionClass()
    {
        
        return 'Mynamespace_Newssubscription_Model_Mysql4';
    }

    public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', array('_current'=>true));
    }
}

13)Define Helper class:

app\code\local\Mynamespace\Newssubscription\Helper\Data.php
<?php
 
class Mynamespace_Newssubscription_Helper_Data extends Mage_Core_Helper_Abstract
{
   public function getRegions(){
        return array(1=>'Norhtern',2=>'Western');
   }
}

14)define front end layout:

\app\design\frontend\<namespace>\<theme>\layout\newssubscription.xml
<?xml version="1.0"?>
<layout version="0.1.0">
	<newssubscription_index_index>   
<reference name="content">
			<block type="newssubscription/newssubscription" name="newssubscription_front" template="newssubscription/newssubscription.phtml" />
		</reference>
</newssubscription_index_index>	
</layout>

14)Front end template:

app\design\frontend\<yourpackage>\<yourtheme>\template\newssubscription\newssubscription.phtml
 <h2 style="display:none;" id="newsusccess">   You Have Successfully Subscribed to the Newsletter</h2>
 <h2 style="display:none;" id="newsusloader">   Processing Request</h2>
<form name="frmnewssubscription" id="frmnewssubscription" action="<?php echo $this->getUrl("newssubscription/index/post") ?>" method="post">   
    <input type ="hidden" id="website_id" name="website_id"  value="<?php echo $this->current_website; ?>" />
     <input type ="hidden" id="store_id" name="store_id"  value="<?php echo $this->current_store; ?>" />   
    <label for="email"><?php echo $this->__('email') ?> <span class="required">*</span></label><br />
    <input type="text" name="email" id="email" class="input-text required-entry validate-email" />
    <label for="region"><?php echo $this->__('region') ?> <span class="required">*</span></label><br />
    <select name="region" id="region" class="required-entry" >
    <option></option>
    <?php foreach($this->regins as $key => $value): ?>
    <option value="<?php echo $key ?>" ><?php echo $value  ?></option>
    <?php endforeach; ?>
    </select>
    <input type="submit" name="submit" value="<?php echo $this->__('Submit') ?>" />
</form>
<script type="text/javascript">
//<![CDATA[
    var formId = 'frmnewssubscription';
    var newsForm = new VarienForm(formId, true);
    var postUrl = '<?php echo $this->getUrl("newssubscription/index/post") ?>';
    function doAjax() {
        if (newsForm.validator.validate()) {
            new Ajax.Request( postUrl, {
                    method:'post',
                    asynchronous:true,
                    evalScripts:false,
                    onComplete:function(request, json) { 
                        Element.hide(formId);                       
                    },
                    onLoading:function(request, json){
                        Element.show('newsusloader');
                    },
                   onSuccess: function(response) { 
                        responseObj = response.responseText.evalJSON();
                        if(responseObj.status == 1)
                        {
                            Element.show('newsusccess');
                            Element.hide('newsusloader');
                        }
                    },
                    parameters: $(formId).serialize(true),
                }
            );
        }
    }
    
    new Event.observe(formId, 'submit', function(e){
        e.stop();
        doAjax();
    });
//]]>
</script>

15)Admin layout:

app\design\adminhtml\default\default\layout\mynamespace\newssubscription.xml
<?xml version="1.0"?>
<layout>  
    <adminhtml_newssubscription_index>
        <reference name="content">           
            <block type="Mynamespace_Newssubscription_Block_Adminhtml_Newssubscription" name="mynamespace_newssubscription_newssubscription" />
        </reference>
    </adminhtml_newssubscription_index>
</layout>

16)Create admin edit form:

app\code\local\Mynamespace\Newssubscription\Block\Adminhtml\Newssubscription\Edit\Form.php
<?php
class Mynamespace_Newssubscription_Block_Adminhtml_Newssubscription_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
 
    public function __construct()
    {  
        parent::__construct();
     
        $this->setId('mynamespace_newssubscription_newssubscription_form');
        $this->setTitle($this->__('Newssubscription Information'));
    }  
     
   
    protected function _prepareForm()
    {  
        $model   = Mage::registry('mynamespace_newssubscription');
        $helper  = Mage::helper('mynamespace_newssubscription');
        $regions   = $helper->getRegions();

         $storesArr = array();
        $allStores = Mage::app()->getStores();
        foreach ($allStores as $_eachStoreId => $val)
        {
           $_storeName           = Mage::app()->getStore($_eachStoreId)->getName(); 
           $storesArr[$_eachStoreId] = $_storeName;
        }

        $websitesArr = array();
        $allWebsites  = Mage::app()->getWebsites();
        foreach ($allWebsites as $_eachWebid => $val)
        {
           $_webName                 = Mage::app()->getWebsite($_eachWebid)->getName();           
           $websitesArr[$_eachWebid] = $_webName;
        }
         
     
        $form = new Varien_Data_Form(array(
            'id'        => 'edit_form',
            'action'    => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
            'method'    => 'post'
        ));
     
        $fieldset = $form->addFieldset('base_fieldset', array(
            'legend'    => Mage::helper('checkout')->__('Newssubscription Information'),
            'class'     => 'fieldset-wide',
        ));
     
        if ($model->getId()) {
            $fieldset->addField('newssubscription_id', 'hidden', array(
                'name' => 'newssubscription_id',
            ));
        }  
     
        $fieldset->addField('email', 'text', array(
            'name'      => 'email',
            'label'     => Mage::helper('mynamespace_newssubscription')->__('email'),
            'title'     => Mage::helper('mynamespace_newssubscription')->__('email'),
            'required'  => true,
        ));
     
         $fieldset->addField('website_id', 'select', array(
            'name'      => 'website_id',
            'label'     => Mage::helper('mynamespace_newssubscription')->__('website_id'),
            'title'     => Mage::helper('mynamespace_newssubscription')->__('website_id'),
            'required'  => true,
            'values' => $websitesArr
        ));

         $fieldset->addField('store_id', 'select', array(
            'name'      => 'store_id',
            'label'     => Mage::helper('mynamespace_newssubscription')->__('store_id'),
            'title'     => Mage::helper('mynamespace_newssubscription')->__('store_id'),
            'required'  => true,
            'values' => $storesArr
        ));
        
        $fieldset->addField('region', 'select', array(
            'name'      => 'region',
            'label'     => Mage::helper('mynamespace_newssubscription')->__('region'),
            'title'     => Mage::helper('mynamespace_newssubscription')->__('region'),
            'required'  => true,
            'values' => $regions
        ));

        $form->setValues($model->getData());
        $form->setUseContainer(true);
        $this->setForm($form);
     
        return parent::_prepareForm();
    }   
}

17)Created edit.php:

app\code\local\Mynamespace\Newssubscription\Block\Adminhtml\Newssubscription\Edit.php
<?php
class Mynamespace_Newssubscription_Block_Adminhtml_Newssubscription_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{

  
    public function __construct()
    {  
        $this->_blockGroup = 'newssubscription';
        $this->_controller = 'adminhtml_newssubscription';
     
        parent::__construct();
     
        $this->_updateButton('save', 'label', $this->__('Save Newssubscription'));
        $this->_updateButton('delete', 'label', $this->__('Delete Newssubsubscription'));
    }  
     
   
    public function getHeaderText()
    {  
        if (Mage::registry('mynamespace_newssubscription')->getId()) {
            return $this->__('Edit Newssubsubscription');
        }  
        else {
            return $this->__('New Newssubsubscription');
        }  
    }   
}

18)Create container.php :

app\code\core\Mage\Adminhtml\Block\Widget\Form\Container.php
<?php
class Mage_Adminhtml_Block_Widget_Form_Container extends Mage_Adminhtml_Block_Widget_Container
{
    protected $_objectId = 'id';
    protected $_formScripts = array();
    protected $_formInitScripts = array();
    protected $_mode = 'edit';
    protected $_blockGroup = 'adminhtml';

    public function __construct()
    {
        parent::__construct();

        if (!$this->hasData('template')) {
            $this->setTemplate('widget/form/container.phtml');
        }

        $this->_addButton('back', array(
            'label'     => Mage::helper('adminhtml')->__('Back'),
            'onclick'   => 'setLocation(\'' . $this->getBackUrl() . '\')',
            'class'     => 'back',
        ), -1);
        $this->_addButton('reset', array(
            'label'     => Mage::helper('adminhtml')->__('Reset'),
            'onclick'   => 'setLocation(window.location.href)',
        ), -1);

        $objId = $this->getRequest()->getParam($this->_objectId);

        if (! empty($objId)) {
            $this->_addButton('delete', array(
                'label'     => Mage::helper('adminhtml')->__('Delete'),
                'class'     => 'delete',
                'onclick'   => 'deleteConfirm(\''. Mage::helper('adminhtml')->__('Are you sure you want to do this?')
                    .'\', \'' . $this->getDeleteUrl() . '\')',
            ));
        }

        $this->_addButton('save', array(
            'label'     => Mage::helper('adminhtml')->__('Save'),
            'onclick'   => 'editForm.submit();',
            'class'     => 'save',
        ), 1);
    }

    protected function _prepareLayout()
    {
        if ($this->_blockGroup && $this->_controller && $this->_mode) {
            $this->setChild('form', $this->getLayout()->createBlock($this->_blockGroup . '/' . $this->_controller . '_' . $this->_mode . '_form'));
        }
        return parent::_prepareLayout();
    }

   
    public function getBackUrl()
    {
        return $this->getUrl('*/*/');
    }

    public function getDeleteUrl()
    {
        return $this->getUrl('*/*/delete', array($this->_objectId => $this->getRequest()->getParam($this->_objectId)));
    }

    
    public function getSaveUrl()
    {
        return $this->getFormActionUrl();
    }

    
    public function getFormActionUrl()
    {
        if ($this->hasFormActionUrl()) {
            return $this->getData('form_action_url');
        }
        return $this->getUrl('*/' . $this->_controller . '/save');
    }

    public function getFormHtml()
    {
        $this->getChild('form')->setData('action', $this->getSaveUrl());
        return $this->getChildHtml('form');
    }

    public function getFormInitScripts()
    {
        if ( !empty($this->_formInitScripts) && is_array($this->_formInitScripts) ) {
            return '<script type="text/javascript">' . implode("\n", $this->_formInitScripts) . '</script>';
        }
        return '';
    }

    public function getFormScripts()
    {
        if ( !empty($this->_formScripts) && is_array($this->_formScripts) ) {
            return '<script type="text/javascript">' . implode("\n", $this->_formScripts) . '</script>';
        }
        return '';
    }

    public function getHeaderWidth()
    {
        return '';
    }

    public function getHeaderCssClass()
    {
        return 'icon-head head-' . strtr($this->_controller, '_', '-');
    }

    public function getHeaderHtml()
    {
        return '<h3 class="' . $this->getHeaderCssClass() . '">' . $this->getHeaderText() . '</h3>';
    }

   
    public function setDataObject($object)
    {
        $this->getChild('form')->setDataObject($object);
        return $this->setData('data_object', $object);
    }

}

Front end: http://yourhost/magento/index.php/newssubscription/
Admin menu: Newsletter >Newssubscription – Mynamespace
In later versions, replace ‘Mysql4’ with ‘Resource’ in folder name, file name and class name.

Magento: Enable template path hints in admin panel

To view template hints in amdin panel; follow below steps:
1)Copy file from app/code/core/Mage/Core/etc/system.xml to app/code/local/Mage/Core/etc/system.xml
2) Set show in default to : 1
c

…..............................
 <template_hints translate="label">
                            …...............
                            <show_in_default>0</show_in_default>
                           …..............
                        </template_hints>
…...........................

3)Go to : Admin> system >configuration > advanced > developers; set ‘Enable Template Path Hints’ to ‘Yes’ after selecting ‘default config’ from top left drop down.