Tag Archive: magento-module


In this post I will show you how to write a basic magento model to do AMD activities to a db table.

Under package “Mypackage” & module “Mymod” we will create model Test so that we can do AMD with table named “test”.

1.Here we first create a table test in db.

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

2.Create shell module Mymod under package Mypackage

//file:- /app/etc/modules/Mypackage_Mymod.xml

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

3.Write config.xml for Mymod module. Here we declate a handler for table test .
//file:-/app/code/local/Mypackage/Mymod/etc/config.xml

/
<?xml version="1.0"?>
<config>
    <modules>
        <Mypackage_Mymod>
            <version>0.1.0</version>
        </Mypackage_Mymod>
    </modules>
    <global>
        <models>
			<mymod>
				<!-- Init model for mymod module -->
				<class>Mypackage_Mymod_Model</class>
				<!-- Init db config handler for mymod models -->
				<resourceModel>mymod_mysql4</resourceModel>
			</mymod>
			
			<!-- declaring model vs db table relation -->
            <mymod_mysql4>
                <class>Mypackage_Mymod_Model_Mysql4</class>
				<!-- declate table test -->
                <entities>
                    <test>
                        <table>test</table>
                    </test>
                </entities>
				<!-- -/- -->
            </mymod_mysql4>
			<!-- -/- -->
        </models>
		
		
		<!-- Setup db read & write connection for Mymod module -->
		<resources>
			<!-- db write connection -->
			<mymod_write>
				<connection>
					<use>core_write</use>
				</connection>
			</mymod_write>
			<!-- db read connection -->
			<mymod_read>
				<connection>
					<use>core_read</use>
				</connection>
			</mymod_read>
		</resources>
		<!-- -/- -->
    </global>
</config>

4.Write model Test.php. Here we configure this model with the handler of table test.
file:-/app/code/local/Mypackage/Mymod/model/Test.php

<?php

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

5.Create the resource model for model test.
file:-/app/code/local/Mypackage/Mymod/model/Mysql4/Test.php. here we also configure the primary key id of the table test.

<?php

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

6.Create a collection class so that we can retrive data from table test.
file:-/local/Mypackage/Mymod/model/Mysql4/Test/Collection.php

<?php

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

That’s it we are done. Now we can do AMD operation with table test with model test.

	$model = Mage::getModel('mymod/test')
		->setName('Asad Rahman')
		->save();

Also use the test collection model to retrive collection data from table test.

	$model = Mage::getModel('mymod/test')
	$data = $model->getCollection()->getData();
	print_r($data);

Here I come to know about an awesome feature of Magento. When we add any eav attribute to an entity we can give a backend model name. Whenever Entity will be loaded magento initiates Mage_Eav_Model_Entity_Attribute model for each attribut. If it finds any backend model name for a eav attribut, it loads the corresponding model and based on what it is doing it will call different method from that model.

Here I am giving a complete example how you can use this feature. We will add an attribue to address model as “address_verified” , use a backend model to set this value whenever the any address will be save.

Step 1.Create a custom model “Mymodule”

Step 2.Write an sql setup for this module. It will add an “address_verified” attribute to address entity

<?php $installer = $this; $installer->startSetup();

$installer->run("
INSERT INTO {$this->getTable('eav_attribute')}  (
`entity_type_id` ,
`attribute_code` ,
`attribute_model` ,
`backend_model` ,
`backend_type` ,
`backend_table` ,
`frontend_model` ,
`frontend_input` ,
`frontend_input_renderer` ,
`frontend_label` ,
`frontend_class` ,
`source_model` ,
`is_global` ,
`is_visible` ,
`is_required` ,
`is_user_defined` ,
`default_value` ,
`is_searchable` ,
`is_filterable` ,
`is_comparable` ,
`is_visible_on_front` ,
`is_html_allowed_on_front` ,
`is_unique` ,
`is_used_for_price_rules` ,
`is_filterable_in_search` ,
`used_in_product_listing` ,
`used_for_sort_by` ,
`is_configurable` ,
`apply_to` ,
`position` ,
`note` ,
`is_visible_in_advanced_search`
)
VALUES (
'2', 'is_validated', NULL , 'customer_entity/address_attribute_backend_validate', 'int', NULL , NULL , 'text', NULL , NULL , NULL , NULL , '1', '1', '0', '0', NULL , '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '', '', '', '0'
);

");

$installer->endSetup(); 

Step3.Write the back end model in your local code pool


<?php 

class Mypackage_Customer_Model_Entity_Address_Attribute_Backend_Validate
	extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
	public function beforeSave($object)
	{
		//Write your code to validate address
		$object->setIsValidated($satoriStatus);
		return $this;
    }
}

Step 4. Override the backend model so that it runs from your local pool

</config>
 <models>
 <customer_entity>
 <rewrite>
 <address_attribute_backend_satori>Mypackage_Customer_Model_Entity_Address_Attribute_Backend_Satori</address_attribute_backend_satori>
 </rewrite>
 </customer_entity>
 </models>
<config>

Create a magento module

Magento module

Modules are the core functioning unit in a Magento system. Here I am giving an overview of how to write a “Hello World” module in magento.

Simple basics before start you cooking 🙂

At the time of instantiating, magento system reads all the Xmls inside the folder /app/etc/modules/ to get the list of active modules and their corresponding code repository . So very first step of creating a magento module is to declare the module and its core repository(the repository of the module, in magento it’s calles codepool ).

If you open /app/code/ you will see 3 coodpool :- core, community and local.

app/
|–code/
| |—community/
| |—core/
| |—local/
|

The “core” cood pool is dedicated for magento’s all system modules. The “community” codepool is for all modules developed by magento’s partners and local is the codepool dedicated for you as a developer to write your own customized code.

In Magentos’ all modules are organized under a package. This package is nothing but a simple folder under codepool containing different modules. For example all core modules of magento system is kept unde package “Mage” (open the folder /app/code/code/ , you see the folder “Mage” under which all system module resides).

Before start cooking lets fixup the name of our module is Mymodule and our package name is Mypackage .

1.Declare your shell module and it’s code pool

Create a xml file /app/etc/modules/Mymodule.xml (You can use any name, even you can use a single file to declare number of modules).

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

2.Create the basic structure Under /app/code/core/local/ :-

Mypackage/
|–Mymodule/
| |–Block/
| |–controllers/
| |–etc/
| |–Helper/
| |–sql/
|

3.Write the front controller /controllers/IndexController.php

<?php

   class Mypackage_Mymodule_IndexController extends Mage_Core_Controller_Front_Action
   {
      public function indexAction()
      {

         //Do nothing fo the time being

         $this->loadLayout();
         $this->_initLayoutMessages('customer/session');
         $this->renderLayout();
      }
   }

4.Create design layout for our controller action
/app/design/frontend/default/default/layout/mymodule.xml

   <?xml version="1.0"?>
   <layout version="0.1.0">
      <default>
      </default>
      <mymodule_index_index>

         <remove name="right"/>
         <remove name="left"/>

         <reference name="root">
            <action method="setTemplate"><template>page/1column.phtml</template></action>
         </reference>

         <reference name="content">
            <block type="mymodule/helloworld" name="helloworld" template="mymodule/helloworld.phtml"/>
         </reference>
      </mymodule_index_index>
   </layout>

4.Create associated block
/Block/Helloworld.php

<?php
   class Mypackage_Mymodule_Block_Helloworld extends Mage_Core_Block_Template
   {
      public function getHelloWorldMsg()
      {
         return "Hello world";
      }
   }
&#91;/sourcecode&#93;
<h3>5.Create Helper for this module
<em>/Helper/Data.php</em></h3>


<?php

   class Mypackage_Mymodule_Helper_Data extends Mage_Core_Helper_Abstract
   {

   }

&#91;/sourcecode&#93;
<h3>6.Now organize every thing write the settings for this module in
<em>/etc/config.xml</em></h3>
We declare the following things in out config.xml

i) Version number of the module. Magento keep track to version number in "core_resource" table which is used to run sql_setup[Details discussed in another post] .

ii) Router information for this module. It contains frontanme and access privilege (front end controller or admin ).

iii) Which layout xml to use for its design.

iv) Global path for module , blocks and helper .

v) Default connection to use for db read &amp; write.



<?xml version="1.0"?>
   <config>
      <!-- i.Version Number -->
      <modules>
         <Mypackage_Mymodule>
            <version>0.1.0</version>
         </Mypackage_Mymodule>
      </modules>
      <!-- ii. Router information -->
      <frontend>
         <routers>
            <mymodule>
                 <!-- Means front end controller -->
                  <use>standard</use>
                  <!-- Fron name "Myfrontname" declared for "Mypackage_Mymodule" -->
                  <args>
                     <module>Mypackage_Mymodule</module>
                     <frontName>myfrontname</frontName>
                  </args>
            </mymodule>
         </routers>
         <!-- iii. Desing layout file -->
         <layout>
            <updates>
               <mymodule>
                  <file>mymodule.xml</file>
               </mymodule>
            </updates>
         </layout>
      </frontend>

      <global>
         <!-- iv. Global path for model, blocks, helper -->
         <!-- models reside under path "Mypackage/Mymodule/model/" -->
         <models>
            <mymodule>
               <class>Mypackage_Mymodule_Model</class>
            </mymodule>
         </models>
         <!-- blocks reside under path "Mypackage/Mymodule/Blocks/" -->
         <blocks>
            <mymodule>
               <class>Mypackage_Mymodule_Block</class>
            </mymodule>
         </blocks>
         <!-- Helper reside under path "Mypackage/Mymodule/Helper/" -->
         <helpers>
            <mymodule>
               <class>Mypackage_Mymodule_Helper</class>
            </mymodule>
         </helpers>
         <!-- v. Declaring db connections -->
         <!-- Also sql setup handler declared in this portion -->
         <resources>
            <mymodule_write>
               <connection>
                  <use>core_write</use>
               </connection>
            </mymodule_write>

            <mymodule_read>
               <connection>
                  <use>core_read</use>
               </connection>
            </mymodule_read>
         </resources>

      </global>
   </config>

That’s it. Go to http://yourdomain.come/magentopath/myfrontname/ and see your first magento modules output 🙂