Models, Resource Models And Collections In Magento

All Magento Models inherit from the Mage_Core_Model_Abstract.Magento splits the model layer up into two parts as you’ve recognised, with the Model handling the business-logic, and the Resource part only dealing with talking to the database .The Resource also has two different types one is Entity and other is Mysql4. We will discuss differences between Models, Resource models and Collections in Magento later on.

To build a model with proper collection object in Magento you need 4 things:

1 – model class
2 – resource class
3 – collection class
4 – install script( Mysql4)

Basic concepts of models, resource models, and collections are follwoing:

model :

Magento Models is handle all logical operation with database.Its ActiveRecord-like/one-object-one-table Model, and there’s also an Entity Attribute Value (EAV) Model. Each Model also gets a Model Collection. .

resource model

Magento’s resource simply connect with the database and performs the CRUD operations. Actually they manage the different reading/writing connections.Its another layer beetween model and database when you intracting with database.

collection model:

Collection referes the collection of models.it contains many models.When we want results based on diffrent model then we need to create collection or we can use existing collection.
It gives us a whole load of convenience methods, making it easier to manipulate lists of entities and reducing the need to write complex sql.

Available customer API Methods in magento

Now i am describing How to get customer information from magento database through API.normally when we are talking about webservice then first we should know about resource name and method name of webservice with request and response parameters before call web service methods.

For handling of customer information in Magento’s database, the following methods are available:

Customer API

Resource name: customer
customer.list—Retrieve customers
customer.create—Create customer
customer.info—Retrieve customer data
customer.update—Update customer data
customer.delete—Delete customer

Customer Groups API

Resource name: customer_group
customer_group.list—Retrieve
customer’s groups

Customer Address API

Resource name: customer_address
customer_address.list—Retrieve
customer addresses
customer_address.create—Create
customer address
customer_address.info—Retrieve
customer address
customer_address.update—Update
customer address
customer_address.delete—Delete
customer address

Magento: How to find user is logged in or Not

Now we discuss snippet of code to identify user is logged in or not in Magento.

Example :To Check user is logged-in or Not
  1. if ($this->helper(‘customer’)->isLoggedIn()) {  
  2. echo “Guest”;  
  3. else {  
  4. echo “Register User”;  
  5. }  

How to set,get and unset session value in Magento

setting session variables in Magento is very easy.We set session variable name in customer session object. Look at the following code:

How to set session value in customer object.

Mage::getSingleton(‘customer/session’)->setMyValue(“variable”);

How to set session value in core session object.

Mage::getSingleton(‘core/session’)->setMyValue(“variable”);

This piece of code sets the session variable setMyValue to the value of “variable”.

How to get session value back.

Mage::getSingleton(‘customer/session’)->getMyValue(“variable”);

How to get session value in core session object.

Mage::getSingleton(‘core/session’)->getMyValue(“variable”);

How to unset session value

Mage::getSingleton(‘customer/session’)->unsMyValue();

How to unset session value in core session object.

Mage::getSingleton(‘core/session’)->unsMyValue();

How to create another controller under controller folder in Magento

Like we want to create a new group of controller class under a module controller folder.
mymudle/controllers/indexControler.php
We want to create another folder iunder controller ‘render’ and create new controller class under newly created folder.
mymudle/controllers/rednder/carusalController.php
then url would be
mywebsite/module_name/controller_render/action

Step 1: First we will create a controller file under controllers folder.

mymudle/controllers/renderContrioller.php

  1. <?php  
  2. class NS_MN_RenderController extends Mage_Core_Controller_Front_Action  
  3. {  
  4.       
  5. }  
  6. ?>  

Step 2: We will create folder same name as above controller file crearted.

mymudle/controllers/rednder

Step 3: We will create Carousel controller under render folder.
  1. <?php  
  2. class NS_MN _Render_CarouselController extends Mage_Core_Controller_Front_Action  
  3. {  
  4.      /** 
  5.      * Get test of particular static block 
  6.      */  
  7.     public function indexAction()  
  8.     {  
  9.         $this->loadLayout();  
  10.         $this->renderLayout();  
  11.     }  
  12. }   

add js/css file for a particular page in magento

I normally programmer putting inline code in template files to load css or javascript only on one specific page, instead of on all pages. There’s no need for that. You can add js/css file to a specific page simply by putting following lines in layout.xml file:

  1. <action method=“addJs”><script>yourpath/yourfile.js</script></action>  
  2. <action method=“addCss”><stylesheet>css/yourstyle.css</stylesheet></action>  

How to upgrade Magento

Upgrading Magento with a full package or via SVN

Here are the steps for upgrading Magento with a full package or via SVN. Steps for upgrading with the MagentoConnect Manager are below.

Backup your database
- In Magento go to Admin, System → Tools → Backups
- You can use PHPMyAdmin (but this may fail due to time-limits on php scripts)
- You can export in SSH by typing…
- mysqldump -u USER -p DBNAME > dump.sql
- Reimport using mysql -u USER -p DBNAME < dump.sql
Backup all the code you modified yourself, and don’t forget to keep the original installation archive
Take care of saving the media directory that contains all the uploaded product/category images
Create a backup copy of app/etc/local.xml file
Download a new installation archive or run SVN update if you checked it out from the Magento repository
Extract and upload all the files it contains to your server
Delete var/cache and var/session directories
Point your browser to any Magento page
Database upgrades should happen automatically
You are done!

Upgrading Magento using the MagentoConnect Manager

Go to http:///downloader
Log in using a user who has full permissions
Make sure to select “Clear all sessions after successful install or upgrade”
Source taken from Here

Magento- Create a Drop-Down list of Countries

For getting countries data, We first needed to access a collection of countries in Magento,there are some simple functions that we can use to access country names and codes in Magento.

Get An Array of Country Names/Codes in Magento

  1. <?php  
  2. $countryList = Mage::getResourceModel(‘directory/country_collection’)  
  3. ->loadData()  
  4. ->toOptionArray(false);  
  5. echo ‘<pre>’;  
  6. print_r( $countryList);  
  7. exit(‘</pre>’);  
  8. ?>  

The above code will print out an array containing every country code and country name known to Magento.

To get Drop Downs and Country Information

Create a Country Drop Down in the Frontend of Magento

Add the following code to any template file in the frontend of Magento and you will get a drop down box using the country name as the label and the country code as the value.

  1. <?php $_countries = Mage::getResourceModel(‘directory/country_collection’)  
  2. ->loadData()  
  3. ->toOptionArray(false) ?>  
  4. <?php if (count($_countries) > 0): ?>  
  5. <select name=“country” id=“country”>  
  6. <option value=“”>– Please Select –</option>  
  7. <?php foreach($_countries as $_country): ?>  
  8. <option value=“<?php echo $_country['value'] ?>”>  
  9. <?php echo $_country['label'] ?>  
  10. </option>  
  11. <?php endforeach; ?>  
  12. </select>  
  13. <?php endif; ?>  

Create a Country Drop Down in the Magento Admin

When creating forms in the Magento Admin area, it is very very just create control on form.php.

  1. <?php  
  2. $fieldset->addField(‘country’, ‘select’, array(  
  3. ‘name’ => ‘country’,  
  4. ‘label’ => ‘Country’,  
  5. ‘values’ => Mage::getModel(‘adminhtml/system_config_source_country’)->toOptionArray(),  
  6. ));  
  7. ?>  

how to define custom event in magento

First we we register the module in magento.
we put the below file in app/etc/namespace_modulename.xml

  1. <?xml version=“1.0″ encoding=“UTF-8″?>  
  2. <config>  
  3.     <modules>  
  4.         <Boom_Order>  
  5.             <codepool>local</codepool>  
  6.             <active>true</active>  
  7.         </Boom_Order>  
  8.     </modules>  
  9. </config>  

we define the event in module config file.Here class name is boom_order_model_observer and method is myOrderProcess.We have defined all logic in method.

  1. <?xml version=“1.0″ encoding=“UTF-8″?>  
  2. <config>  
  3.     <global>  
  4.         <models>  
  5.             <boomorder>  
  6.                 <class>Boom_Order_Model</class>  
  7.             </boomorder>  
  8.         </models>  
  9.     </global>  
  10.     <frontend>  
  11.         <events>  
  12.             <checkout_onepage_controller_success_action>  
  13.                 <observers>  
  14.                     <boom_order_observer>  
  15.                         <type>singleton</type>  
  16.                         <class>boom_order_model_observer</class>  
  17.                         <method>myOrderProcess</method>  
  18.                     </boom_order_observer>  
  19.                 </observers>  
  20.             </checkout_onepage_controller_success_action>  
  21.         </events>  
  22.     </frontend>  
  23. </config>  

we dine class with method definitions.

  1. <?php  
  2.   
  3. class Boom_Order_Model_Observer  
  4. {  
  5.     /** 
  6.      * Event Hook: checkout_onepage_controller_success_action 
  7.      * @param $observer Varien_Event_Observer 
  8.      */  
  9.   
  10.     public function myOrderProcess($observer)  
  11.     {  
  12.         Mage::log(“Enter myOrderProcess”);  
  13.   
  14.         $order = new Mage_Sales_Model_Order();  
  15.         $incrementId = Mage::getSingleton(‘checkout/session’)->getLastRealOrderId();  
  16.   
  17.         $order->loadByIncrementId($incrementId);  
  18.   
  19.         Mage::log(“Exit myOrderProcess”);  
  20.         }  
  21. }  

Opps based module in magento

Hi,
Now i am creating a sub module(banner) under a module.The sub module would have functionally adding new banner,edit new banner,delete banner and listing with ajax pagination.
Step 1- First we have register action into the layout/module.xml file.

  1. <!– Banner list –>  
  2.     <module_banner_list>  
  3.         <reference name=“root”>  
  4.             <action method=“setTemplate”>  
  5.                 <template>page/module.phtml</template>  
  6.             </action>  
  7.         </reference>  
  8.         <reference name=“content”>  
  9.             <block type=“module/banner_list” name=“module_banner_list” template=“module/banner/list.phtml” />  
  10.         </reference>  
  11.     </module_banner_list>  
  12.       
  13.     <!– Banner list for ajax –>  
  14.     <module_banner_listajax>  
  15.         <reference name=“root”>  
  16.             <action method=“setTemplate”>  
  17.                 <template>page/ajaxblank.phtml</template>  
  18.             </action>  
  19.         </reference>  
  20.         <reference name=“content”>  
  21.             <block type=“module/banner_list” name=“module_banner_list” template=“module/banner/ajaxlist.phtml” />  
  22.         </reference>  
  23.     </module_banner_listajax>  
  24.       
  25.     <!– Banner console for add/edit –>  
  26.     <module_banner_edit>  
  27.         <reference name=“root”>  
  28.             <action method=“setTemplate”>  
  29.                 <template>page/module.phtml</template>  
  30.             </action>  
  31.         </reference>  
  32.         <reference name=“content”>  
  33.             <block type=“module/banner_edit” name=“module_banner_edit” template=“module/banner/edit.phtml” />  
  34.         </reference>  
  35.     </module_banner_edit>  

step 2- creating a class under jquery js file for listing with pagination and toggle of div.

  1. /** 
  2.  * for banner 
  3.  */  
  4. Module.Banner = function() {  
  5.       
  6.     var that = {};  
  7.       
  8.     params = {  
  9.         ‘url’‘/module/banner/listAjax/’,           
  10.         ‘containerId’‘banners-container’  
  11.     };  
  12.     
  13.     jQuery(document).ready(function() {  
  14.         that.displayControl(jQuery(‘#type’).val());  
  15.     });  
  16.       
  17.     jQuery(‘#type’).live(‘change’function() {  
  18.         that.displayControl(jQuery(‘#type’).val());  
  19.     });   
  20.       
  21.     jQuery(‘a.banners-list-page’).live(‘click’function() {  
  22.         params['url'] = jQuery(this).attr(‘data-url’);  
  23.         params['containerId'] = jQuery(this).attr(‘data-active’);  
  24.         namespace.Class.Pagination().getPageData(params);  
  25.         namespace.Loader.show();  
  26.     });  
  27.       
  28.     that.displayControl = function(type) {   
  29.         var data = jQuery(‘#data’).val();  
  30.         if(type == ‘image’) {  
  31.             jQuery(‘#image-div’).css(‘display’‘block’);   
  32.         } else {  
  33.            jQuery(‘#image-div’).css(‘display’‘none’);  
  34.         }  
  35.         that.addControl(type);  
  36.         jQuery(‘#data’).val(data);  
  37.     }  
  38.       
  39.     that.addControl = function(type) {  
  40.         controlType = type == ‘image’ ? ‘input’ : ‘textarea’;  
  41.         var element = document.createElement(controlType);  
  42.         element.setAttribute(“name”‘data’);  
  43.         element.setAttribute(“id”‘data’);  
  44.         if(type == ‘image’) {  
  45.             element.setAttribute(“type”‘text’);  
  46.             element.setAttribute(“class”‘xlarge’);  
  47.         } else {  
  48.              element.setAttribute(“class”‘xxlarge’);  
  49.              element.setAttribute(“rows”’9′);  
  50.              element.setAttribute(“cols”’45′);  
  51.         }  
  52.         jQuery(‘.data’).html(element);  
  53.     }       
  54.     Module.Pagination().getPageData(params);  

Step 3- creating a class pagination common in js file.\

  1. /** 
  2.  * Pagination 
  3.  */  
  4. Module.Pagination = function() {  
  5.   
  6.     var that = {};  
  7.      
  8.     /** 
  9.      * ajax function to bind page data for current page using pagination. 
  10.      */  
  11.     that.getPageData = function(params) {  
  12.         Loader.show();  
  13.         params = params ? params : ;  
  14.         url = params['url'];  
  15.         containerId = params['containerId'] ? params['containerId'] : ;     
  16.         if (url == ) {  
  17.             jQuery(‘#’ + containerId).html(‘<span class=”empty”>Invalid URL found.</span>’);  
  18.         } else {  
  19.             jQuery(‘#’ + containerId).empty();  
  20.             that.ajax = jQuery.ajax({  
  21.                 url: url,  
  22.                 dataType: ‘html’,  
  23.                 type: ‘post’,  
  24.                 data: params,  
  25.                 success: function(response) {  
  26.                     if (response == ) {  
  27.                         response = ‘<span class=”empty”>No record(s) found.</span>’;  
  28.                     }  
  29.                     jQuery(‘#’ + containerId).html(response);  
  30.                     Loader.hide();  
  31.                 }  
  32.             });  
  33.         }  
  34.     }  
  35.       
  36.     return that;  
  37. }  

step 4- creating list.phtml file for listing

  1. <h2>Banners List</h2>  
  2.   
  3. <?php  
  4. $messages = Mage::getSingleton(‘customer/session’)->getData(‘status’true);  
  5. ?>  
  6.   
  7. <?php if ($messages[0]) { ?>  
  8.     <div class=“alert-message <?= $messages[0] ?>”><?= $messages[1] ?></div>  
  9. <? } ?>  
  10. <div class=“buttons pull-right” id=“add-div”>  
  11.     <a href=“/module/banner/edit/id/0″ class=“btn primary” id=“banner”>Add Banner</a>  
  12. </div>  
  13. <div id=“banners-container”></div>  
  14.   
  15. <script type=“text/javascript”>  
  16.     Module.Banner();  
  17. </script>  

step 5- creating listAjax.phtml file

  1. <?php  
  2. $banners = $this->getBanners(array(‘id’‘type’‘data’‘brand’‘user_id’‘active’‘created_at’));  
  3. ?>   
  4.   
  5. <div class=“result-count”>  
  6.     <span class=“pagination”><?= $this->getPaginationHtml(); ?></span>  
  7. </div>  
  8.   
  9. <table>  
  10.     <thead>  
  11.         <tr>  
  12.             <th>Type</th>  
  13.             <th>Data</th>  
  14.             <th>Brand</th>  
  15.             <th>User</th>  
  16.             <th>Status</th>  
  17.             <th>Created At</th>  
  18.             <th>Action</th>  
  19.         </tr>  
  20.     </thead>  
  21.     <tbody>  
  22.         <?php if (count($banners) > 0): ?>  
  23.             <?php foreach ($banners as $banner): ?>  
  24.                 <tr>  
  25.                     <td><?= ucfirst($banner['type']) ?></td>  
  26.                     <td><a href=“/module/banner/edit/id/<?= $banner['id'] ?>”><?= htmlentities(strlen($banner['data']) < 25 ? $banner['data'] : substr($banner['data'], 0 ,25) . ‘ …’) ?> </a></td>  
  27.                     <td><?= ucfirst($banner['brand']) ?></td>  
  28.                     <td><?= ucfirst($banner['email']) ?></td>  
  29.                     <td><?= $banner['active'] ?></td>  
  30.                     <td><?= $banner['created_at'] ?></td>  
  31.                     <td><a class=“delete” data-url=“/module/banner/delete/id/<?= $banner['id'] ?>” data-redirect=“/module/banner/list/”>Delete</a></td>  
  32.                 </tr>  
  33.             <?php endforeach ?>  
  34.         <?php else: ?>  
  35.             <tr>  
  36.                 <td colspan=“4″>No record(s) found.</td>  
  37.             </tr>  
  38.         <?php endif ?>  
  39.     </tbody>          
  40. </table>  

step 6-creating edit.phtml file

  1. <?php  
  2. $message = \Mage::getSingleton(‘customer/session’)->getData(‘errorMsg’, true);  
  3. $type = $this->getData(‘type’);  
  4. $id = $this->getId();  
  5. $active = $this->getData(‘active’);  
  6. ?>  
  7.   
  8. <h2><?php echo $id == 0 ? ‘Create’ : ‘Edit’; ?> Banner</h2>  
  9.   
  10. <?php if($message[1]) { ?>  
  11. <div class=“alert-message <?= $message[0] ?>”><?= $message[1] ?></div>  
  12. <?php } ?>  
  13.   
  14. <form action=“/module/banner/edit/id/<?= $id ?>” method=“post”>  
  15.     <div class=“clearfix”>  
  16.         <label>Type:</label>  
  17.         <div class=“input”>  
  18.             <select name=“type” id=“type” class=“medium”>  
  19.                 <option value=“html” <?= $type == ‘html’ ? ‘selected=”selected”‘ :  ?>>HTML</option>  
  20.                 <option value=“image” <?= $type == ‘image’ ? ‘selected=”selected”‘ :  ?>>Image</option>  
  21.             </select>  
  22.         </div>  
  23.     </div>  
  24.     <?= Mage::Helper(‘module/Product’)->getBrandsHtml($this->getData(‘brand’), true) ?>  
  25.     <div id=“image-div”>  
  26.         <div class=“clearfix”>  
  27.             <label>Link</label>  
  28.             <div class=“input”><input type=“text” class=“xlarge” name=“link” id=“link” value=“<?= $this->getData(‘link’) ?>” maxlength=“255″/></div>  
  29.         </div>  
  30.     </div>  
  31.     <div class=“clearfix”>  
  32.         <label>Width:</label>  
  33.         <div class=“input”><input type=“text” class=“xlarge” name=“width” id=“width” value=“<?= $this->getData(‘width’) ?>” maxlength=“4″/></div>  
  34.     </div>  
  35.     <div class=“clearfix”>  
  36.         <label>Height:</label>  
  37.         <div class=“input”><input type=“text” class=“xlarge” name=“height” id=“height” value=“<?= $this->getData(‘height’) ?>” maxlength=“4″/></div>  
  38.     </div>  
  39.     <div class=“clearfix”>  
  40.         <label>Data:</label>  
  41.         <div class=“input data”>  
  42.             <textarea cols=“45″ rows=“9″ class=“xxlarge” name=“data” id=“data”><?= $this->getData(‘data’) ?></textarea>  
  43.         </div>  
  44.     </div>  
  45.     <div class=“clearfix”>  
  46.         <label>Active:</label>  
  47.         <div class=“input”>  
  48.             <input type=“checkbox” value=“1″ <?= ($active == 1 || $active == ) ? ‘checked=”checked”‘ :  ?> name=“active” id=“active” />  
  49.         </div>  
  50.     </div>  
  51.     <div class=“actions”>  
  52.         <input type=“hidden” name=“id” value=“<?= $id ?>”/>  
  53.         <button type=“submit” class=“btn primary”>Submit</button>  
  54.         <a class=“btn primary” href=“/module/banner/list/” >Cancel</a>  
  55.     </div>  
  56. </form>  
  57.   
  58. <script type=“text/javascript”>  
  59.     Module.Banner();  
  60. </script>  

step 7- creating controller for all action

  1. class Namespace_Module_BannerController extends Mage_Core_Controller_Front_Action  
  2. {  
  3.     /** 
  4.      * for default action 
  5.      */  
  6.     public function indexAction()  
  7.     {  
  8.         Mage::helper(‘module/acl’)->loadPagePermissions(‘banner’‘view’);  
  9.         $this->loadLayout();  
  10.         $this->renderLayout();  
  11.     }  
  12.   
  13.     /** 
  14.      * list to get all banners 
  15.      */  
  16.     public function listAction()  
  17.     {  
  18.         Mage::helper(‘module/acl’)->loadPagePermissions(‘banner’‘view’);  
  19.         $this->loadLayout();  
  20.         $this->renderLayout();  
  21.     }  
  22.       
  23.     /** 
  24.      * list banners list for ajax call 
  25.      */  
  26.     public function listAjaxAction()  
  27.     {  
  28.         Mage::helper(‘module/Acl’)->loadPagePermissions(‘banner’‘view’);  
  29.         $this->loadLayout();  
  30.         $this->renderLayout();  
  31.     }  
  32.       
  33.     /** 
  34.      * To edit/add banner 
  35.      */  
  36.     public function editAction()  
  37.     {  
  38.         Mage::helper(‘module/Acl’)->loadPagePermissions(‘banner’‘view’);  
  39.         $params = $this->getRequest()->getPost();  
  40.         if (!emptyempty($params)) {  
  41.             try {  
  42.                 if (Mage::getModel(‘module/Banner’)->setData($params)->validate()->save()) {  
  43.                     Mage::getModel(‘customer/session’)->setData(‘status’array(‘success’‘Record saved successfully.’));  
  44.                     $this->_redirect(‘*/*/list/’);  
  45.                 }  
  46.             } catch (\Exception $e) {  
  47.                 Mage::getModel(‘customer/session’)->setData(‘errorMsg’array(‘errors’$e->getMessage()));  
  48.             }  
  49.         }  
  50.         $this->loadLayout();  
  51.         $this->renderLayout();  
  52.     }  
  53.       
  54.     /**  
  55.      * delete the selected banner id  
  56.      */  
  57.     public function deleteAction()  
  58.     {  
  59.         Mage::helper(‘module/Acl’)->loadPagePermissions(‘banner’‘view’);  
  60.         try {  
  61.             if (Mage::getModel(‘module/Banner’)->delete($this->getRequest()->getParam(‘id’, 0))) {  
  62.                 Mage::getModel(‘customer/session’)->setData(‘status’array(‘success’‘Record deleted successfully.’));  
  63.             } else {  
  64.                 Mage::getModel(‘customer/session’)->setData(‘status’array(‘error’‘Record not found’));  
  65.             }  
  66.         } catch (\Exception $e) {  
  67.             Mage::getModel(‘customer/session’)->setData(‘status’array(‘error’$e->getMessage()));  
  68.         }  
  69.     }  
  70. }  

step 8- creating model for banner management.

  1. <?php  
  2.   
  3. class Namespace_Module_Model_Banner extends Varien_Object  
  4. {  
  5.     /** 
  6.      * @var Varien_Db_Adapter_Pdo_Mysql Singleton instance of finder db 
  7.      */  
  8.     protected $_db;  
  9.       
  10.     /** 
  11.      * Constructor of the class to initialize the database object 
  12.      *  
  13.      */  
  14.     public function __construct()  
  15.     {  
  16.         $this->_db = Db::getInstance()->getDb();  
  17.     }  
  18.       
  19.     /** 
  20.      * Save the Banner data into the database 
  21.      *  
  22.      * @return boolean 
  23.      */  
  24.     public function save()  
  25.     {  
  26.         $id = $this->getData(‘id’);  
  27.         $this->setData(‘user_id’, Mage::registry(‘MODULE_USER’)->getId());  
  28.         if ($this->getData(‘type’) == ‘html’) {  
  29.             $this->setData(‘link’);  
  30.         }  
  31.         $this->setData(‘active’$this->getData(‘active’));  
  32.         try {  
  33.             if ($id == 0) {  
  34.                 $this->setData(‘created_at’date(‘Y-m-d H:i:s’));  
  35.                 $this->setData(‘updated_at’date(‘Y-m-d H:i:s’));  
  36.                 $this->_db->insert(‘j_finder_banner’$this->getData());  
  37.             } else {  
  38.                 $this->setData(‘updated_at’date(‘Y-m-d H:i:s’));  
  39.                 $this->_db->update(‘j_finder_banner’$this->getData(), $this->_db->quoteInto(‘id = ?’$id));  
  40.             }  
  41.         } catch (\Exception $e) {  
  42.             throw new \Exception(‘Error in save operation’);  
  43.         }  
  44.   
  45.         return $this;  
  46.     }  
  47.       
  48.     /** 
  49.      * Load the Banner details  
  50.      *  
  51.      * @param integer $id 
  52.      * 
  53.      * @return $data array details of Banner 
  54.      */  
  55.     public function load($id)  
  56.     {  
  57.         if ($id != 0) {  
  58.             $sql = $this->_db->select()  
  59.                 ->from(‘j_finder_banner’)  
  60.                 ->where(‘id = ?’$id)  
  61.                 ->limit(1);  
  62.             if($result = $sql->query()->fetch()) {  
  63.                 $this->setData($result);  
  64.             }              
  65.         }  
  66.           
  67.         return $this;  
  68.     }  
  69.       
  70.      /** 
  71.      * Delete the selected Banner 
  72.      *  
  73.      * @param integer $id 
  74.      * 
  75.      */  
  76.     public function delete($id)  
  77.     {  
  78.         if ($id != 0) {  
  79.             try {  
  80.                 $result = $this->_db->delete(‘j_finder_banner’$this->_db->quoteInto(‘id = ?’$id));  
  81.             } catch(\Exception $e) {  
  82.                 throw new \Exception(‘Unable to deleted record’);  
  83.             }   
  84.              
  85.             return $result;  
  86.         }  
  87.     }  
  88.       
  89.     /** 
  90.      * validate all post Banner data 
  91.      * 
  92.      * @return boolean  
  93.      */  
  94.     public function validate()  
  95.     {  
  96.         $errors = array();  
  97.         $data = $this->getData(‘data’);  
  98.         $link = $this->getData(‘link’);  
  99.         $width = $this->getData(‘width’);  
  100.         $height = $this->getData(‘height’);  
  101.         if ($this->getData(‘type’) == ‘image’) {  
  102.             if (emptyempty($link)) {  
  103.                 $errors[] = ‘Link must not be blank.’;  
  104.             }  
  105.             if (emptyempty($width)) {  
  106.                 $errors[] = ‘Width must not be blank.’;  
  107.             } elseif (!is_numeric($width) || $width < 0) {  
  108.                 $errors[] = ‘Width must be a positive numeric value.’;  
  109.             }  
  110.             if (emptyempty($height)) {  
  111.                 $errors[] = ‘Height must not be blank.’;  
  112.             } elseif (!is_numeric($height) || $height < 0) {  
  113.                 $errors[] = ‘Height must be a positive numeric value.’;  
  114.             }  
  115.         }  
  116.         if (emptyempty($data)) {  
  117.             $errors[] = ‘Data must not be blank.’;  
  118.         }  
  119.         if (!emptyempty($errors)) {  
  120.             Mage::register(‘error’$errors);  
  121.             throw new \Exception(implode(‘  
  122.  ’, $errors));  
  123.         }  
  124.   
  125.         return $this;  
  126.     }  
  127. }  

step 9- creating edit.php block file

  1. <?php  
  2.   
  3. class Namespace_Module_Block_Banner_Edit extends Mage_Core_Block_Template  
  4. {  
  5.     /** 
  6.      * @var array of data 
  7.      */  
  8.     protected $_data;  
  9.       
  10.     /** 
  11.      * Constructor of the class to set data variable 
  12.      * 
  13.      */  
  14.     public function __construct()  
  15.     {  
  16.         $this->_data = count($this->getPostData()) > 0  
  17.             ? $this->getPostData()  
  18.             : Mage::getModel(‘empire/Banner’)->load($this->getId())->getData();  
  19.     }  
  20.   
  21.     /** 
  22.      * To return the current banner id           
  23.      * 
  24.      * @return integer 
  25.      */  
  26.     public function getId()  
  27.     {  
  28.         return $this->getRequest()->getParam(‘id’, 0);  
  29.     }  
  30.   
  31.     /** 
  32.      * To return the post array data 
  33.      * 
  34.      * @return array 
  35.      */  
  36.     public function getPostData()  
  37.     {  
  38.         return $this->getRequest()->getPost();  
  39.     }  
  40. }  

step 10- You will create list.php.This file would kept only banners() listing method.