Filtering data collection magento

In this post we are discussing about how filtering data collection is done on magento

The most important method on a database Collection is addFieldToFilter. This adds your WHERE clauses. Consider this bit of code, run against the sample data database (substitute your own SKU is you’re using a different set of product data)

addFieldToFilter() = fields in sql “where” clause

$products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('sku')
->addFieldToFilter('sku','123');
var_dump($products);

For more complex filtering, pass an array as the second argument to addFieldToFilter().
The following list of filters and their sql equivalents is from Alan Storm’s excellent article on collections:

addFieldToFilter('sku', array("eq"=>'123'))
WHERE (e.sku = '123')
 
addFieldToFilter('sku',array("neq"=>'123'))
WHERE (e.sku != '123')
 
addFieldToFilter('sku',array("like"=>'123'))
WHERE (e.sku like 'n2610')
 
addFieldToFilter('sku',array("nlike"=>'123'))
WHERE (e.sku not like '123')
 
addFieldToFilter('sku',array("is"=>'123'))
WHERE (e.sku is '123')
 
addFieldToFilter('sku',array("in"=>array('123', '456', '789')))
WHERE (e.sku in ('123', '456', '789'))
 
addFieldToFilter('sku',array("nin"=>array('123', '456', '789')))
WHERE (e.sku not in ('123', '456', '789'))
 
addFieldToFilter('sku',array("notnull"=>'123'))
WHERE (e.sku is NOT NULL)
 
addFieldToFilter('sku',array("null"=>'123'))
WHERE (e.sku is NULL)
 
addFieldToFilter('sku',array("gt"=>'123'))
WHERE (e.sku > '123')
 
addFieldToFilter('sku',array("lt"=>'123'))
WHERE (e.sku < '123')
 
/* Two ways to do greater than equal: */
 
addFieldToFilter('sku',array("gteq"=>'123'))
WHERE (e.sku >= '123')
 
addFieldToFilter('sku',array("moreq"=>'123'))
WHERE (e.sku >= '123')
 
addFieldToFilter('sku',array("lteq"=>'123'))
WHERE (e.sku <= '123')
 
addFieldToFilter('sku',array("finset"=>array('123')))
WHERE (find_in_set('123',e.sku))
 
addFieldToFilter('sku',array('from'=>'50','to'=>'100'))
WHERE e.sku >= '50' and e.sku <= '100'

AND

->addFieldToFilter('sku',array('like'=>'123%'))
->addFieldToFilter('sku',array('like'=>'456%'))
WHERE (e.sku like '123%') AND (e.sku like '456%')

OR

->addFieldToFilter('sku',array(array('like'=>'123%'),array('like'=>'456%')))
WHERE (((e.sku like '123%') OR (e.sku like '456%')))

Hope this bit of code helps you to filter data collection in magento

Creating magento extension with custom database table

In this post we are discussing about creating magento extension with custom database table. Follow step by step and if you encounter any error don’t hesitate to contact me

Document Conventions

I am going to use a few common conventions here that should make it easier to figure out what you need to replace as I am making this as generic as possible.

Anything in angled brackets (including the angled brackets): < >, needs to replaced with the appropriate text..

Anything in square brackets (including the square brackets): [ ], needs to replaced with the appropriate text.

The reason I am using two different conventions here are that XML files already use angled brackets so you will only see the square brackets in use in XML files.

I have changed the document conventions to use the naming conventions as Naviz_Dummy, Becuase of i have got somany comments regarding the output of this code

NOTE: All directory, file, class names are Case Sensitive unless otherwise noted.

Create Directories

Magento Modules follow a common naming scheme, Namespace_Module. This is very important to remember as you need to be careful about how you name your classes. Every custom module will be created in the directory:

/app/code/local

The first step in creating your custom module is determining the namespace and module name. The namespace is simply an extra division that you can create you module in. This means that you can have two modules named the same thing if they are in two different namespaces. One way to use namespaces is to use your company name or initials for all of your modules. If my company name is Naviz and I am creating a module called Dummy the full module name would be Acme_News. Magento uses the namespace Mage. There is nothing stopping you from using that namespace under local, i.e. you could create Mage_Dummy and that would work just fine.

Note : You can not use underscore within your module name

Note2: It seems that currently, if you use upper case characters in module names (expecting to show word starts since neither – nor _ is allowed)… the install will fail or rather the module will not work. Suggestion: use a single upper case character, at the beginning of the name.

Let’s setup our directory structure:

/app/code/local/Naviz/Dummy/
Block/
controllers/
etc/
Model/
    Mysql4/
        Dummy/
sql/
    dummy_setup/
/app/design/frontend/base/default/

template/
    dummy/

Activate Module

Magento requires there to be an XML file that tells Magento to look for and use your custom module.

/app/etc/modules/Naviz_Dummy.xml
<?xml version="1.0"?>
<config>
  <modules>
    <Naviz_Dummy>
      <active>true</active>
      <codePool>local</codePool>
      <version>0.1.0</version>
    </Naviz_Dummy>
  </modules>
</config>

Also you can disable your module in the Configuration menu on the backend via the Advanced tab.

NOTE: Due to a bug in Magento, whitespace is not treated correctly. This means that if you leave space in the values between node names (anything in angled brackets <> is a node), Magento will break.

As an explanation of the above code you will see that all you are changing is the Naviz_Dummy text and leaving everything else the same. Please note the capital P in codePool. If this is lowercase this module will not be active.

Create Controller

/app/code/local/Naviz/Dummy/controllers/IndexController.php
<?php
class Naviz_Dummy_IndexController extends Mage_Core_Controller_Front_Action{
    public function IndexAction() {
      
	  $this->loadLayout();   
	  $this->getLayout()->getBlock("head")->setTitle($this->__("Dummy"));
	        $breadcrumbs = $this->getLayout()->getBlock("breadcrumbs");
      $breadcrumbs->addCrumb("home", array(
                "label" => $this->__("Home Page"),
                "title" => $this->__("Home Page"),
                "link"  => Mage::getBaseUrl()
		   ));

      $breadcrumbs->addCrumb("dummy", array(
                "label" => $this->__("Dummy"),
                "title" => $this->__("Dummy")
		   ));

      $this->renderLayout(); 
	  
    }
}

NOTE: You may notice that there is no closing, ?>, PHP tag in the code. This is a common coding style that Magento core classes use. Magento Coding Standard is similar (with some exceptions) to Zend Framework PHP Coding Standard and you can find the detailed explanations of this rule in Zend Framework Documentation

Create Configuration XML

/app/code/local/Naviz/Dummy/etc/config.xml
<?xml version="1.0"?>
<config>
  <modules>
    <Naviz_Dummy>
      <version>0.1.0</version>
    </Naviz_Dummy>
  </modules>
  <frontend>
    <routers>
      <dummy>
        <use>standard</use>
          <args>
            <module>Naviz_Dummy</module>
            <frontName>dummy</frontName>
          </args>
      </dummy>
    </routers>
		<layout>
		  <updates>
			<dummy>
			  <file>dummy.xml</file>
			</dummy>
		  </updates>
		</layout>
  </frontend>
  <global>
    <helpers>
      <dummy>
        <class>Naviz_Dummy_Helper</class>
      </dummy>
    </helpers>
	<blocks>
	  <dummy>
		<class>Naviz_Dummy_Block</class>
	  </dummy>
	</blocks>
	<models>
	  <dummy>
		<class>Naviz_Dummy_Model</class>
		<resourceModel>dummy_mysql4</resourceModel>
	  </dummy>
	  <dummy_mysql4>
		<class>Naviz_Dummy_Model_Mysql4</class>
		<entities>		  
			  <dummy>
				<table>dummy</table>
			  </dummy>
        </entities>
	  </dummy_mysql4>
	</models>
	<resources>
	  <dummy_setup>
		<setup>
		  <module>Naviz_Dummy</module>
		</setup>
		<connection>
		  <use>core_setup</use>
		</connection>
	  </dummy_setup>
	  <dummy_write>
		<connection>
		  <use>core_write</use>
		</connection>
	  </dummy_write>
	  <dummy_read>
		<connection>
		  <use>core_read</use>
		</connection>
	  </dummy_read>
	</resources>
  </global>
  <admin>
	<routers>
	  <dummy>
	    <use>admin</use>
		<args>
		  <module>Naviz_Dummy</module>
		  <frontName>admin_dummy</frontName>
		</args>
	  </dummy>
	</routers>
  </admin>
  <adminhtml>
	<menu>
	  <dummy module="dummy">
		<title>Dummy</title>
		<sort_order>100</sort_order>
		<children>
		  <dummy module="dummy">
		    <title>Manage Dummy</title>
			<sort_order>0</sort_order>
			<action>admin_dummy/adminhtml_dummy</action>
		  </dummy>
		</children>
	  </dummy>
	</menu>
	<acl>
	  <resources>
		<all>
		  <title>Allow Everything</title>
		</all>
		<admin>
		  <children>
			<dummy translate="title" module="dummy">
			  <title>Dummy</title>
			  <sort_order>1000</sort_order>
			  <children>
		  <dummy translate="title">
			<title>Manage Dummy</title>
			<sort_order>0</sort_order>
		  </dummy>
			  </children>
			</dummy>
		  </children>
		</admin>
	  </resources>
	</acl>
	<layout>
	  <updates>
		<dummy>
		  <file>dummy.xml</file>
		</dummy>
	  </updates>
	</layout>
  </adminhtml>
</config> 

NB : You can use the frontName of your choice without any link to your module name. IE : Mage_Catalog could have “mycatalog” as a frontName.

Create Helper

/app/code/local/Naviz/Dummy/Helper/Data.php
<?php
class Naviz_Dummy_Helper_Data extends Mage_Core_Helper_Abstract
{
}

Create Models

If you are quite new to Magento you should pay attention to one of its specifics! The Constructors below are not the usual PHP-Constructors!! Keeping that in mind can save hours of frustrating crashes 😉

/app/code/local/Naviz/Dummy/Model/Dummy.php
<?php

class Naviz_Dummy_Model_Dummy extends Mage_Core_Model_Abstract
{
    protected function _construct(){

       $this->_init("dummy/dummy");

    }

}
	 
/app/code/local/Naviz/Dummy/Model/Mysql4/Dummy.php
<?php
class Naviz_Dummy_Model_Mysql4_Dummy extends Mage_Core_Model_Mysql4_Abstract
{
    protected function _construct()
    {
        $this->_init("dummy/dummy", "dummy_id");
    }
}

NOTE: The ‘_id’ refers to the PRIMARY KEY in your database table.

/app/code/local/Naviz/Dummy/Model/Mysql4/Dummy/Collection.php
<?php
 class Naviz_Dummy_Model_Mysql4_Dummy_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
    {

		public function _construct(){
			$this->_init("dummy/dummy");
		}

		

    }

SQL Setup

/app/code/local/Naviz/Dummy/sql/dummy_setup/mysql4-install-0.1.0.php
<?php
 
$installer = $this;
$installer->startSetup();
$sql=<<<SQLTEXT
create table dummy (dummy_id int not null auto_increment, title varchar(100), content text(200), status varchar(100),primary key(dummy_id));
   
SQLTEXT;

$installer->run($sql);
 
$installer->endSetup();

NOTE: Please note the text that needs to be replaced. This SQL structure is up to you, this is merely a starting point.

Note Important: If you add fields and couldn’t save data in these fields please try to go to System→Cache Management Then 1.Flush Cache Storage 2.Flush Magento Cache.

Template Design

/app/design/frontend/base/default/layout/dummy.xml
<?xml version="1.0"?>   
<layout version="0.1.0">   
  <dummy_index_index>   
    <reference name="root">   
      <action method="setTemplate"><template>page/1column.phtml</template></action>   
    </reference>   
    <reference name="content">   
      <block type="dummy/index" name="dummy_index" template="dummy/index.phtml"/>   
    </reference>   
  </dummy_index_index>   
</layout>  

NOTE: The block type will automatically figure out what template file to use based on the second dummy declaration.

/app/design/frontend/base/default/template/dummy/index.phtml
<h4><?php echo $this->__('Module List') ?></h4>
 
<?php   
        /*
        This will load one record from your database table.
        load(dummy_id) will load whatever ID number you give it.
        */
    /*
    $news = Mage::getModel('dummy/dummy')->load(1);
    echo $news->getDummyId();
    echo $news->getTitle();
    echo $news->getContent();
    echo $news->getStatus();
    */
 
        /*
        This block of code loads all of the records in the database table.
        It will iterate through the collection and the first thing it will do
        is set the Title to the current value of $i which is incremented each
        iteration and then echo that value back out.  At the very end it will
        save the entire collection.
        */
    /*
    $i = 0;
         
    $collection = Mage::getModel('dummy/dummy')->getCollection();
    $collection->setPageSize(5);
    $collection->setCurPage(2);
    $size = $collection->getSize();
    $cnt = count($collection);
    foreach ($collection as $item) {
        $i = $i+1;
        $item->setTitle($i);
        echo $item->getTitle();
    }
 
    $collection->walk('save');   
    */
 
        /*
        This shows how to load one value, change something and save it.
        */
 
    /*
    $object = Mage::getModel('dummy/dummy')->load(1);
    $object->setTitle('This is a changed title');
    $object->save();
    */
?>

NOTE: Uncomment anything that you would like to use and this is just a starting point and some common methods for you to try and pull the data out.

In this section I am utilizing the built-in Grid Widgets and form capabilities to create a form to allow editing and creating new items for your custom database.

Directory Additions

Here is the revised directory setup due to the additions and changes we need for the backend module.

/app/code/local/Naviz/Dummy/
Block/
    Adminhtml/
        Dummy/
            Edit/
                Tab/
controllers/
    Adminhtml/
etc/
Helper/
Model/
    Mysql4/
        Dummy/
sql/
    dummy_setup/
Blocks

These control the setup and appearance of your grids and the options that they display.

NOTE: Please note the fact that Block comes before Adminhtml in the class declaration. In any of the Magento modules in Adminhtml it is the opposite. For your module to work it has to be Block_Adminhtml otherwise you will get a ‘Cannot redeclare module…’ error.

/app/code/local/Naviz/Dummy/Block/Adminhtml/Dummy.php
<?php
 class Naviz_Dummy_Block_Adminhtml_Dummy extends Mage_Adminhtml_Block_Widget_Grid_Container{

	public function __construct()
	{

	$this->_controller = "adminhtml_dummy";
	$this->_blockGroup = "dummy";
	$this->_headerText = Mage::helper("dummy")->__("Dummy Manager");
	$this->_addButtonLabel = Mage::helper("dummy")->__("Add New Item");
	parent::__construct();
	
	}

}
/app/code/local/Naviz/Dummy/Block/Adminhtml/Dummy/Edit.php
<?php
	
class Naviz_Dummy_Block_Adminhtml_Dummy_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
		public function __construct()
		{

				parent::__construct();
				$this->_objectId = "dummy_id";
				$this->_blockGroup = "dummy";
				$this->_controller = "adminhtml_dummy";
				$this->_updateButton("save", "label", Mage::helper("dummy")->__("Save Item"));
				$this->_updateButton("delete", "label", Mage::helper("dummy")->__("Delete Item"));

				$this->_addButton("saveandcontinue", array(
					"label"     => Mage::helper("dummy")->__("Save And Continue Edit"),
					"onclick"   => "saveAndContinueEdit()",
					"class"     => "save",
				), -100);



				$this->_formScripts[] = "

							function saveAndContinueEdit(){
								editForm.submit($('edit_form').action+'back/edit/');
							}
						";
		}

		public function getHeaderText()
		{
				if( Mage::registry("dummy_data") && Mage::registry("dummy_data")->getId() ){

				    return Mage::helper("dummy")->__("Edit Item '%s'", $this->htmlEscape(Mage::registry("dummy_data")->getId()));

				} 
				else{

				     return Mage::helper("dummy")->__("Add Item");

				}
		}
}
/app/code/local/Naviz/Dummy/Block/Adminhtml/Dummy/Grid.php
<?php

class Naviz_Dummy_Block_Adminhtml_Dummy_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

		public function __construct()
		{
				parent::__construct();
				$this->setId("dummyGrid");
				$this->setDefaultSort("dummy_id");
				$this->setDefaultDir("DESC");
				$this->setSaveParametersInSession(true);
		}

		protected function _prepareCollection()
		{
				$collection = Mage::getModel("dummy/dummy")->getCollection();
				$this->setCollection($collection);
				return parent::_prepareCollection();
		}
		protected function _prepareColumns()
		{
				$this->addColumn("dummy_id", array(
				"header" => Mage::helper("dummy")->__("ID"),
				"align" =>"right",
				"width" => "50px",
			    "type" => "number",
				"index" => "dummy_id",
				));
                
				$this->addColumn("title", array(
				"header" => Mage::helper("dummy")->__("Title"),
				"index" => "title",
				));
						$this->addColumn('status', array(
						'header' => Mage::helper('dummy')->__('Status'),
						'index' => 'status',
						'type' => 'options',
						'options'=>Naviz_Dummy_Block_Adminhtml_Dummy_Grid::getOptionArray2(),				
						));
						
			$this->addExportType('*/*/exportCsv', Mage::helper('sales')->__('CSV')); 
			$this->addExportType('*/*/exportExcel', Mage::helper('sales')->__('Excel'));

				return parent::_prepareColumns();
		}

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


		
		protected function _prepareMassaction()
		{
			$this->setMassactionIdField('dummy_id');
			$this->getMassactionBlock()->setFormFieldName('dummy_ids');
			$this->getMassactionBlock()->setUseSelectAll(true);
			$this->getMassactionBlock()->addItem('remove_dummy', array(
					 'label'=> Mage::helper('dummy')->__('Remove Dummy'),
					 'url'  => $this->getUrl('*/adminhtml_dummy/massRemove'),
					 'confirm' => Mage::helper('dummy')->__('Are you sure?')
				));
			return $this;
		}
			
		static public function getOptionArray2()
		{
            $data_array=array(); 
			$data_array[0]='Yes';
			$data_array[1]='No';
            return($data_array);
		}
		static public function getValueArray2()
		{
            $data_array=array();
			foreach(Naviz_Dummy_Block_Adminhtml_Dummy_Grid::getOptionArray2() as $k=>$v){
               $data_array[]=array('value'=>$k,'label'=>$v);		
			}
            return($data_array);

		}
		

}
/app/code/local/Naviz/Dummy/Block/Adminhtml/Dummy/Edit/Form.php
<?php
class Naviz_Dummy_Block_Adminhtml_Dummy_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
		protected function _prepareForm()
		{
				$form = new Varien_Data_Form(array(
				"id" => "edit_form",
				"action" => $this->getUrl("*/*/save", array("id" => $this->getRequest()->getParam("id"))),
				"method" => "post",
				"enctype" =>"multipart/form-data",
				)
				);
				$form->setUseContainer(true);
				$this->setForm($form);
				return parent::_prepareForm();
		}
}

/app/code/local/Naviz/Dummy/Block/Adminhtml/Dummy/Edit/Tabs.php
<?php
class Naviz_Dummy_Block_Adminhtml_Dummy_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
		public function __construct()
		{
				parent::__construct();
				$this->setId("dummy_tabs");
				$this->setDestElementId("edit_form");
				$this->setTitle(Mage::helper("dummy")->__("Item Information"));
		}
		protected function _beforeToHtml()
		{
				$this->addTab("form_section", array(
				"label" => Mage::helper("dummy")->__("Item Information"),
				"title" => Mage::helper("dummy")->__("Item Information"),
				"content" => $this->getLayout()->
                createBlock("dummy/adminhtml_dummy_edit_tab_form")->toHtml(),
				));
				return parent::_beforeToHtml();
		}

}

/app/code/local/Naviz/Dummy/Block/Adminhtml/Dummy/Edit/Tab/Form.php
<?php
class Naviz_Dummy_Block_Adminhtml_Dummy_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
		protected function _prepareForm()
		{

				$form = new Varien_Data_Form();
				$this->setForm($form);
				$fieldset = $form->addFieldset("dummy_form", 
                array("legend"=>Mage::helper("dummy")->__("Item information")));

				
						$fieldset->addField("title", "text", array(
						"label" => Mage::helper("dummy")->__("Title"),
						"name" => "title",
						));
					
						$fieldset->addField("content", "textarea", array(
						"label" => Mage::helper("dummy")->__("Content"),
						"name" => "content",
						));
									
						 $fieldset->addField('status', 'select', array(
						'label'     => Mage::helper('dummy')->__('Status'),
						'values'   => Naviz_Dummy_Block_Adminhtml_Dummy_Grid::getValueArray2(),
						'name' => 'status',
						));

				if (Mage::getSingleton("adminhtml/session")->getDummyData())
				{
					$form->setValues(Mage::getSingleton("adminhtml/session")->getDummyData());
					Mage::getSingleton("adminhtml/session")->setDummyData(null);
				} 
				elseif(Mage::registry("dummy_data")) {
				    $form->setValues(Mage::registry("dummy_data")->getData());
				}
				return parent::_prepareForm();
		}
}

Controller

/app/code/local/Naviz/Dummy/controllers/Adminhtml/DummyController.php
<?php

class Naviz_Dummy_Adminhtml_DummyController extends Mage_Adminhtml_Controller_Action
{
		protected function _initAction()
		{
				$this->loadLayout()->
                _setActiveMenu("dummy/dummy")->_addBreadcrumb(Mage::helper("adminhtml")->
                __("Dummy  Manager"),Mage::helper("adminhtml")->__("Dummy Manager"));
				return $this;
		}
		public function indexAction() 
		{
			    $this->_title($this->__("Dummy"));
			    $this->_title($this->__("Manager Dummy"));

				$this->_initAction();
				$this->renderLayout();
		}
		public function editAction()
		{			    
			    $this->_title($this->__("Dummy"));
				$this->_title($this->__("Dummy"));
			    $this->_title($this->__("Edit Item"));
				
				$id = $this->getRequest()->getParam("id");
				$model = Mage::getModel("dummy/dummy")->load($id);
				if ($model->getId()) {
					Mage::register("dummy_data", $model);
					$this->loadLayout();
					$this->_setActiveMenu("dummy/dummy");
					$this->_addBreadcrumb(Mage::helper("adminhtml")->__("Dummy Manager"), Mage::helper("adminhtml")->__("Dummy Manager"));
					$this->_addBreadcrumb(Mage::helper("adminhtml")->__("Dummy Description"), Mage::helper("adminhtml")->__("Dummy Description"));
					$this->getLayout()->getBlock("head")->setCanLoadExtJs(true);
					$this->_addContent($this->getLayout()->
                    createBlock("dummy/adminhtml_dummy_edit"))->_addLeft($this->getLayout()->createBlock("dummy/adminhtml_dummy_edit_tabs"));
					$this->renderLayout();
				} 
				else {
					Mage::getSingleton("adminhtml/session")->
                    addError(Mage::helper("dummy")->__("Item does not exist."));
					$this->_redirect("*/*/");
				}
		}

		public function newAction()
		{

		$this->_title($this->__("Dummy"));
		$this->_title($this->__("Dummy"));
		$this->_title($this->__("New Item"));

        $id   = $this->getRequest()->getParam("id");
		$model  = Mage::getModel("dummy/dummy")->load($id);

		$data = Mage::getSingleton("adminhtml/session")->getFormData(true);
		if (!empty($data)) {
			$model->setData($data);
		}

		Mage::register("dummy_data", $model);

		$this->loadLayout();
		$this->_setActiveMenu("dummy/dummy");

		$this->getLayout()->getBlock("head")->setCanLoadExtJs(true);

		$this->_addBreadcrumb(Mage::helper("adminhtml")->
        __("Dummy Manager"), Mage::helper("adminhtml")->__("Dummy Manager"));
		$this->_addBreadcrumb(Mage::helper("adminhtml")->
        __("Dummy Description"), Mage::helper("adminhtml")->__("Dummy Description"));


		$this->_addContent($this->getLayout()->
        createBlock("dummy/adminhtml_dummy_edit"))->_addLeft($this->getLayout()->createBlock("dummy/adminhtml_dummy_edit_tabs"));

		$this->renderLayout();

		}
		public function saveAction()
		{

			$post_data=$this->getRequest()->getPost();


				if ($post_data) {

					try {

						

						$model = Mage::getModel("dummy/dummy")
						->addData($post_data)
						->setId($this->getRequest()->getParam("id"))
						->save();

						Mage::getSingleton("adminhtml/session")->
                        addSuccess(Mage::helper("adminhtml")->__("Dummy was successfully saved"));
						Mage::getSingleton("adminhtml/session")->setDummyData(false);

						if ($this->getRequest()->getParam("back")) {
							$this->_redirect("*/*/edit", array("id" => $model->getId()));
							return;
						}
						$this->_redirect("*/*/");
						return;
					} 
					catch (Exception $e) {
						Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
						Mage::getSingleton("adminhtml/session")->setDummyData($this->getRequest()->getPost());
						$this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
					return;
					}

				}
				$this->_redirect("*/*/");
		}



		public function deleteAction()
		{
				if( $this->getRequest()->getParam("id") > 0 ) {
					try {
						$model = Mage::getModel("dummy/dummy");
						$model->setId($this->getRequest()->getParam("id"))->delete();
						Mage::getSingleton("adminhtml/session")->
                        addSuccess(Mage::helper("adminhtml")->__("Item was successfully deleted"));
						$this->_redirect("*/*/");
					} 
					catch (Exception $e) {
						Mage::getSingleton("adminhtml/session")->
                        addError($e->getMessage());
						$this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
					}
				}
				$this->_redirect("*/*/");
		}

		
		public function massRemoveAction()
		{
			try {
				$ids = $this->getRequest()->getPost('dummy_ids', array());
				foreach ($ids as $id) {
                      $model = Mage::getModel("dummy/dummy");
					  $model->setId($id)->delete();
				}
				Mage::getSingleton("adminhtml/session")->
                addSuccess(Mage::helper("adminhtml")->__("Item(s) was successfully removed"));
			}
			catch (Exception $e) {
				Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
			}
			$this->_redirect('*/*/');
		}
			
		/**
		 * Export order grid to CSV format
		 */
		public function exportCsvAction()
		{
			$fileName   = 'dummy.csv';
			$grid       = $this->getLayout()->createBlock('dummy/adminhtml_dummy_grid');
			$this->_prepareDownloadResponse($fileName, $grid->getCsvFile());
		} 
		/**
		 *  Export order grid to Excel XML format
		 */
		public function exportExcelAction()
		{
			$fileName   = 'dummy.xml';
			$grid       = $this->getLayout()->createBlock('dummy/adminhtml_dummy_grid');
			$this->_prepareDownloadResponse($fileName, $grid->getExcelFile($fileName));
		}
}

XML Configuration Changes

/app/code/local/Naviz/Dummy/etc/config.xml
<?xml version="1.0"?>
<config>
  <modules>
    <Naviz_Dummy>
      <version>0.1.0</version>
    </Naviz_Dummy>
  </modules>
  <frontend>
    <routers>
      <dummy>
        <use>standard</use>
          <args>
            <module>Naviz_Dummy</module>
            <frontName>dummy</frontName>
          </args>
      </dummy>
    </routers>
		<layout>
		  <updates>
			<dummy>
			  <file>dummy.xml</file>
			</dummy>
		  </updates>
		</layout>
  </frontend>
  <global>
    <helpers>
      <dummy>
        <class>Naviz_Dummy_Helper</class>
      </dummy>
    </helpers>
	<blocks>
	  <dummy>
		<class>Naviz_Dummy_Block</class>
	  </dummy>
	</blocks>
	<models>
	  <dummy>
		<class>Naviz_Dummy_Model</class>
		<resourceModel>dummy_mysql4</resourceModel>
	  </dummy>
	  <dummy_mysql4>
		<class>Naviz_Dummy_Model_Mysql4</class>
		<entities>		  
			  <dummy>
				<table>dummy</table>
			  </dummy>
        </entities>
	  </dummy_mysql4>
	</models>
	<resources>
	  <dummy_setup>
		<setup>
		  <module>Naviz_Dummy</module>
		</setup>
		<connection>
		  <use>core_setup</use>
		</connection>
	  </dummy_setup>
	  <dummy_write>
		<connection>
		  <use>core_write</use>
		</connection>
	  </dummy_write>
	  <dummy_read>
		<connection>
		  <use>core_read</use>
		</connection>
	  </dummy_read>
	</resources>
  </global>
  <admin>
	<routers>
	  <dummy>
	    <use>admin</use>
		<args>
		  <module>Naviz_Dummy</module>
		  <frontName>admin_dummy</frontName>
		</args>
	  </dummy>
	</routers>
  </admin>
  <adminhtml>
	<menu>
	  <dummy module="dummy">
		<title>Dummy</title>
		<sort_order>100</sort_order>
		<children>
		  <dummy module="dummy">
		    <title>Manage Dummy</title>
			<sort_order>0</sort_order>
			<action>admin_dummy/adminhtml_dummy</action>
		  </dummy>
		</children>
	  </dummy>
	</menu>
	<acl>
	  <resources>
		<all>
		  <title>Allow Everything</title>
		</all>
		<admin>
		  <children>
			<dummy translate="title" module="dummy">
			  <title>Dummy</title>
			  <sort_order>1000</sort_order>
			  <children>
		  <dummy translate="title">
			<title>Manage Dummy</title>
			<sort_order>0</sort_order>
		  </dummy>
			  </children>
			</dummy>
		  </children>
		</admin>
	  </resources>
	</acl>
	<layout>
	  <updates>
		<dummy>
		  <file>dummy.xml</file>
		</dummy>
	  </updates>
	</layout>
  </adminhtml>
</config> 

XML Layout

/app/design/adminhtml/default/default/layout/dummy.xml
<?xml version="1.0"?>
<layout version="0.1.0">
  <dummy_adminhtml_dummy_index>
	<reference name="content">
	  <block type="dummy/adminhtml_dummy" name="dummy" />
	</reference>
  </dummy_adminhtml_dummy_index>
</layout>

Standard Magento Admin URLs, no rewrite needed

Also, rather than using a rewrite for the admin section described above, you can implement the same standard admin generated urls Magento uses. These look like: ‘/admin/dummy/index/’ instead of the above that would generate ‘/dummy/adminhtml_dummy/index/’.

To implement this different url structure you can change the following in your config.xml:

/app/code/local/Naviz/Dummy/etc/config.xml
    ...
    <admin>
        <routers>
            <!-- Includes our controller, so when we add the adminhtml menu item below, it is found! -->
            <adminhtml>
                 <args>
                     <modules>
                         <dummy before="Mage_Adminhtml">Naviz_Dummy_Adminhtml</dummy>
                     </modules>
                 </args>
             </adminhtml>
        </routers>
    </admin>
    <adminhtml>
        <menu>
            <dummy module="dummy">
                <title>[Module]</title>
                <sort_order>71</sort_order>               
                <children>
                    <items module="dummy">
                        <title>Manage Items</title>
                        <sort_order>0</sort_order>
                        <action>adminhtml/dummy</action>
                    </items>
                </children>
            </dummy>
        </menu>
    ...
    

Here i am attaching the completed module zip: Download Naviz_Dummy

Hopping this article helps you when creating magento extension with custom database table

Change the color scheme of google maps

When we use Google Maps JavaScript API v3 we have the extreme freedom to customize the output we gets like to change the color scheme of google maps

You can create a new map type to which to apply styles, by creating a StyledMapType and passing the feature and styler information to the constructor. This approach does not affect the style of the default map types.

To create a new map type:

  • Create your array of styles. See Map Features and Stylers for instructions.
  • Create a new google.maps.StyledMapType object, passing it the array of styles, as well as a name for the new map type.
  • Create your map object and, in the map options, include an identifier for the the new map type in the mapTypeIds array (which is a property of the mapTypeControlOptions object).
  • Associate the identifier in the last step with the new styled map.
  • Set the map to use the new map type.

And the code is shown below

function initialize() {

  // Create an array of styles.
  var styles = [
    {
      stylers: [
        { hue: "#00ffe6" },
        { saturation: -20 }
      ]
    },{
      featureType: "road",
      elementType: "geometry",
      stylers: [
        { lightness: 100 },
        { visibility: "simplified" }
      ]
    },{
      featureType: "road",
      elementType: "labels",
      stylers: [
        { visibility: "off" }
      ]
    }
  ];

  // Create a new StyledMapType object, passing it the array of styles,
  // as well as the name to be displayed on the map type control.
  var styledMap = new google.maps.StyledMapType(styles,
    {name: "Styled Map"});

  // Create a map object, and include the MapTypeId to add
  // to the map type control.
  var mapOptions = {
    zoom: 11,
    center: new google.maps.LatLng(55.6468, 37.581),
    mapTypeControlOptions: {
      mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
    }
  };
  var map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

  //Associate the styled map with the MapTypeId and set it to display.
  map.mapTypes.set('map_style', styledMap);
  map.setMapTypeId('map_style');
}

So i think you will get an little idea on how we can customize the google maps and we are mainly discussed about the change the color scheme of google maps

Remove Blank Lines Between Code

Sometimes when we are dealing with the files through ftp some servers append so many blank lines in between codes.When we are using Dreamweaver we can remove blank lines between code using the regular expressions

  • Hit CTRL-F to open the Find-and-Replace tool
  • Click the “use regular expression” checkbox
  • Ensure the Search drop-down shows “Search Source Code“
  • Copy-and-Paste ‘[\r\n]{2,}’ in the Find textarea
  • Copy-and-Paste “\n” in the Replace text box.
  • Click the”Find Next” or “Find All” just to be sure this is working properly before you go straight into the “Replace All”

Feature.Remove blank Lines Between Code

So this will help us to remove blank lines between code and its easy to implement