alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end...

51
Create a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure In a first tutorial , I promise to create a tutorial that allows you to create a complete module in Magento. » Basic knowledge: Before you venture into magento, check that you have already a solid foundation in programming. prerequisite for developing Magento are: - Have already installed Magento. - Know what the MVC pattern. - Know the object-oriented PHP (and PHP of course …) - How does the whole template magento You have the first 2 but do not have the 3rd, go to: magento designer’s guide The structure of a Magento module In a magneto module there are 2 parties, the « code » and « templates ». code determines the actions that the module will be able to achieve the interraction with the database etc … while templates are just the layout of the data sent by code. Magento, the two parties will be placed at two different locations. your « code » will be in /app/code/local/monNameSpace/monNomDeModule/ while the « template » of the module will be in: /app/design/frontend/monRepertoiredeTemplates/monTemplate (for the frontend) And /app/design/adminhtml/monRepertoiredeTemplates/monTemplate (for the backend)

Transcript of alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end...

Page 1: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

Create a magento plugin from the start to the end !

Lesson 1.

Magento Developper’s Guide (Lesson 1) – Magento plugins structure

In a first tutorial   , I promise to create a tutorial that allows you to create a complete module in Magento.  » Basic knowledge: Before you venture into magento, check that you have already a solid foundation in programming.

prerequisite for developing Magento are: - Have already installed Magento.- Know what the MVC pattern.- Know the object-oriented PHP (and PHP of course …)- How does the whole template magentoYou have the first 2 but do not have the 3rd, go to: magento designer’s guide

The structure of a Magento moduleIn a magneto module there are 2 parties, the « code » and « templates ».

code determines the actions that the module will be able to achieve the interraction with the database etc … while templates are just the layout of the data sent by code.

Magento, the two parties will be placed at two different locations.

your « code » will be in/app/code/local/monNameSpace/monNomDeModule/

while the « template » of the module will be in:/app/design/frontend/monRepertoiredeTemplates/monTemplate (for the frontend)

And/app/design/adminhtml/monRepertoiredeTemplates/monTemplate (for the backend)

The « code » of my template will contain the following elements:

Block : Where you go to the « controller » of your block

Controllers: the controllers of your module

Models: Performers of your module

Page 2: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

Helper: of your helpers module

etc: the configuration of your module

sql: SQL query to execute to create your module during the instalation

Reminder on blocks:Magento, a Block is a piece of your site that walks « alone », you can insert just anywhere. In fact, a block is a kind of « mini controller » that you can add anywhere on your site.

According to the page of your site, you can assign to different templates depending on the view you want to call it.

folder / app / code:In this folder you will find three folders that contain:

Community: the plugins you have recovered (on magentoconnect for example).

Core: the default magento modules (especially not EDIT)

Local: the modules you have developed

Your duties until the next tutorial:Try to browse the folders on your site to understand what I tell you. Open the files and try to understand.Conclusion

the tutorial:You have seen the structure of modules magento, if you do your homework you should understand a little better.

Does this sound a bit abstract for the moment? This is normal! That’s a lot of information at once.

In the next tutorial, we will begin the creation of our first module by creating the Controller.

Do not worry, trust me: we will create a complete module A to Z, step by step. We’ll take it easy and see everything that you seem a bit abstract in the first tutorial gradually become clear as we advance.

Now do your homework! Courrage good;)

If you have any questions please feel free to post a comment.

Page 3: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

Lesson 2.

Magento Developper’s Guide (Lesson 2) – Create your own controller

This tutorial is the 2nd of many tutorials   , you will now learn how to create your own controller in Magento. If you have not read the first articles yet, I strongly advise you to do so. With Magento, you can access to your controller with the url: http://yoursite.com/plugin/method/

Start by creating your module:1 – Create the folder /app/code/local/Pfay/Test/

This create your namespace Pfay and your module Test .

2 – Enable the module in Magento:

Add a file Pfay_all.xml /app/etc/module/

And insert the following code in it

123456789

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

This file is used to declare all your modules in the Pfay namespace, you have to put it between the tags « modules » declaration of your plugin one after the other.

1234

<Pfay_Test>   <active> true </active>   <codePool> local </codePool></Pfay_Test>

Pfay_Test allows you to declare the namespace of your plugin Test Pfay.active: true = the plugin is activefalse = the plugin is not enabled

codePool: The module will be in the local file because it is a module that we create ourselves (remember the lesson 1).Magento will therefore find the files in that module in the /app/code/ local/Pfay/Test/

Page 4: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

ahead and create the controller:go to /app/code/local/Pfay/Test/

1 – Create the file /app/code/local/Pfay/Test/controllers/

2 – Inside create a IndexController.php which will contain:

1234567891011

class Pfay_Test_IndexController extends Mage_Core_Controller_Front_Action{   public function indexAction ()   {     echo 'test index';   }   public function mamethodeAction ()   {     echo 'test mymethod';    }}

Now if you go to http://yoursite.com/test/index   What’s happening?

Actually … you can not find the page, there’s an error because you have not already declare your controller in the plugin.

Config.xml file to configure your plugin:In the same way that you have declared your plugin for Magento to take into account Pfay_All.xml, the file config.xml of your plugin will allow you to you declare the controller of your plugin.

Mangento will check Pfay_All.xml and find your file, it will go in your /app/code/local/Pfay/Test/etc/ and reads the config.xml file to see or pick up your controller.

So create your file Test , a record etc/ with in config.xml .

config.xml contains:

12345678910

<?xml version="1.0"?>  <config>     <modules>        <Pfay_Test>          <version>1.0.0</version>        </Pfay_Test>     </modules>     <frontend>       <routers>          <routeurfrontend>              <use>standard</use>              <args>

Page 5: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

111213141516171819

                 <module>Pfay_Test</module>                 <frontName>test</frontName>              </args>           </routeurfrontend>       </routers>    </frontend></config>

Explanation:

12345

<modules>  <Pfay_Test>    <version>1.0.0</version>   </Pfay_Test></modules>

In this section, we declare the identity of the module for magento module to verify that what you declare in your Pfay_All.xml is the good plugin and if the version number allow you to eventually have an update for your plugin.

123456789

<routers>     <routeurfrontend>        <use>standard</use>          <args>             <module>Pfay_Test</module>             <frontName>test</frontName>          </args>     </routeurfrontend></routers>

Allows you to declare a router « routeurfrontend » which is actually the road used by magento to access your controller.In our example, the router is « standard » (it means that it is a module that will be displayed on the frontend).

The module name is Pfay_Test and the shortcut to access it via the url is test and when you will type

http://yoursite.com/ test /index , we arrive on the index method of your controller IndexController.php (in your folder controllers )

You can also access it using your router in place of frontName.

http://yoursite.com/routeurfrontend/index/

Now test your module:

Page 6: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

http://yoursite.com/ test /index  you can read « test index » (you can add /index at the end of your url if you want to call the index method but by default if nothing is specified it calls the method « index »)

You know now create a controller. Now try to understand this by doing it again and again at home and you should be able to move on the next tutorial.

If you have any questions, feel free to leave a comment. If you want to help me, share a link to this website with your friends on facebook, twitter etc… 

Lesson 3.

Magento Developper’s Guide (Lesson 3) – Create your own Block

This tutorial is the 3rd of many   , if you do not already have read them I suggest you starting with the summary of this series. We have previously created a plugin, we will now learn how to create and display a magento Block.

Why create a blockFor now, your plugin is a bit « simple », you can perform treatments but its usefulness and quite limited. We will now learn how to display content using a template, that’s what is a magento block 

How does it work? ok we’ll do a little reminder:controller , call your layout to know what to show in this layout, you place blocks which are in fact a kind of « little controllers » (who will retrieve a list of client for exemple). Then these blocks appeals templates to display their informations.

Page 7: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

Now that you understand how it works, the only way to understand it si to make one ! So…let’s go!

Step 1: Call the layout in the controllerRemind , your plugin is located in /app/code/local/Pfay/Test/. The plugin name is Test and it is in the namespace Pfay

Now open your controller:

/app/code/local/Pfay/Test/controllers/IndexController.php

And modify it like this:

123456789101112

class Pfay_Test_IndexController extends Mage_Core_Controller_Front_Action{     public function indexAction()     {          $this->loadLayout();          $this->renderLayout();     }      public function mamethodeAction()      {          echo ‘test mamethode’;      }}

As you can see, I added in my action index , two small lines. These lines will search what to display when you get on this action (by going to the URL http://yoursite.com/ test /index  for example).

1 $this->loadLayout();    //Va chercher les elements à afficher

Page 8: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

2 $this->renderLayout();   //Affiche les elements

For now, there’s nothing more to do on the controller. We indicated to our controller that it must get the information in the layout, let’s see what happens on the side of the layout …

Step 2: Declare the items to be displayed using the Layout.To start before you can use the Layout, (and if you read the previous tutorials you begin to predict the continued …) it must be declare, with a declaration Magento is going to be able to use it. To do this go into our file config.xml (located in the directory /etc of your module).

Open it and add it in <frontend> and after <routers> :

1234567

<layout>   <updates>        <test>             <file>test.xml</file>         </test>    </updates></layout>

This litte xml code will allow you to declare your file test.xml as the layout of your plugin test (because it is in your config.xml of your Test plugin)

Now declare the folder or will find the Blocks:

In <config> and bitter <frontend> now add:

1234567

<global>     <blocks>         <test>              <class>Pfay_Test_Block</class>         </test>      </blocks></global>

In you declare your Blocks, it is also where you will declare later your models and Helpers (we will see later what it is).

Important Note:In Magento when you declare your classes, the name of your class is the path to this file, so our controller Pfay_Test_IndexControlleris at the following address: /app/code/local/Pfay/Test/IndexController.php

So you deduce that the names of your blocks will be the type Pfay_Test_IndexController_MonBlock

Page 9: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

Now that the config.xml file is configured and magento is able to find our layout and our blocks, let’s see what happens on the side of the Layout!

layout:If you recall, in the first lesson of this tutorial   , we saw that a plugin contains some code template and that files are has two locations in the directories magento.

The layout is part of the « template », we declared it in our config.xml module as named test.xml

Now go to the directory layout of your Magento theme.

In our example, the template currently used in magento will be in the following directory: \app\design\frontend\pfay\theme\ .

We will therefore create a Layout test.xml in the directory \app\design\frontend\pfay\theme\layout\ Once this file is created, edit it and copy it:

123456789101112

<layout version="0.1.0">     <default>          <reference name="content">          </reference>      </default>      <routeurfrontend_index_index>           <reference name="content">                <block type="test/monblock"  name="afficher_monbloc"                          template="test/afficher.phtml" />           </reference>      </routeurfrontend_index_index></layout>

I do not tell you how it works, if you do not understand what code I advise you to read the guide magento designer   and it must be mastered before starting to try to develop a module.I’m going to remind you what are some piece of code in case;)

123

<routeurfrontend_index_index>    ...</routeurfrontend_index_index>

To indicate which blocks a magento add to wich page, we have created the layout!

This layout define the pages, in this pages we add blocks. One page is written like this: «  router name »_ »name of the controller »_ »action name » So if you want to access our action http://yoursite.com/test/index   we have already defined in the config.xml that the name of the router will be routeurfrontend , we know that the controller called in this case is the controller IndexController.php , and that the method wich will be called is indexAction() . The page will be in the layout represented by the tag: routeurfrontend_index_index

Page 10: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

And we will add in this file, the line:

1 <block type="test/monblock" name="afficher_monbloc" template="test/afficher.phtml" />

That mean for magento « creates a block that you will take in the Test module, which is called « monblock » and use the template « afficher.phtml » which will be in the folder « test » of the « template » folder.

Step 3: Create the blockNow, we have to create the block «  monblock « ,so go to the folder you specified in config.xml to store blocks (app/code/local/Pfay/Test/Block) and create the Monblock.php file in it.

This file will contain:

12345678

<?phpclass Pfay_Test_Block_Monblock extends Mage_Core_Block_Template{     public function methodblock()     {         return ‘informations about my block !!’ ;     }}

This file is just a class of type Block (Mage_Core_Block_Template) with a method methodblock() which returns a sentence (String)

Step 4: Create the templateNow go to the directory \app\design\frontend\pfay\theme\template\

And create a directory « test » with a file inside afficher.phtml.

This file will contain:

[Php]

echo $this->methodblock();?>

[/php]

How it worksWe have defined a block of type « test/monblock » in the layout, which appeals to our template afficher.phtml. So in afficher.phtml we can access to the monblock functions thanks to the variable $this.

Page 11: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

Step 5: Test!Now go to http://yoursite.com/ test /index  and now, you can see appear on your website a text: « information from my block!  »

End of this tutorialNow you can insert a block with the template in any page of your site. Our example is simple because the goal is to understand how Magento work. Our block is not really usefull in a real website.

A block is generally used to make treatment of the style list the last 5 products added to your Magento store, display a contact form… you would be happy to hand them over several locations your site just by inserting a small line in your layout is not it ? Ok now you understand What does a block and how to create one, Congratulations ! 

Here is the end of this tutorial, i hope you enjoyed this, feel free to leave comments if you have any questions or comments   You can help me by sharing this tutorial on facebook, twitter or, talking about this blog with friends (yes at a dinner it’s a very cool subject…you’ll be a star, even more if your friends are not geeks xD !)

Lession 4.

Magento Developper’s Guide (Lesson 4) – The Model and the database

This tutorial is the 4th of many   , if you do have not already done this, i suggest you to read the previous tutorials and to start at the summary of this series.

We have previously created a plugin with a controller, a block and its associated template. Our plugin works well and I think now you understand how it works. I take the opportunity to thank you for your very positive feedback that motivate me to continue this series of tutorials.

Now, a plugin that is the equivalent of a echo is not very useful and it has nothing very complicated as you have seen. In this tutorial we will modify our plugin to look for data in our database (in MySQL) and display it in our Block.

Step 1: Create the tableWe will say that our plugin is an address book, we want the block to display all the book addresses one after the other of the form:

Name Surname telephone_number

Example:

John Smith 0000000000

John Smith 0000000000

Page 12: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

John Smith 0000000000

John Smith 0000000000

We will start by creating a table in the database, we will call this table pfay_test

So execute the following query:

123456

CREATE TABLE `magento`.`pfay_test` (`id_pfay_test` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `nom` VARCHAR( 50 ) NOT NULL , `prenom` VARCHAR( 50 ) NOT NULL , `telephone` VARCHAR( 20 ) NOT NULL);

Your table is now in the database. To interact with it, we’ll create the model.

Step 2: Declare the model in config.xmlYou know, Magento use the MVC model, it is necessary to create a model in order to interact with our database.

To create a template, you who have followed the previous three tutorials …what are we going to have to do? You have the answer comes out automatically from your head as you start to get used to ^ ^, we will first declare the model in the config.xml file of our plugin.

Go therefore etc/config.xml and add in <global> after the declaration <blocks> :

123456789101112131415161718

<models><test>     <class>Pfay_Test_Model</class>     <resourceModel>test_mysql4</resourceModel> </test><test_mysql4>     <class>Pfay_Test_Model_Mysql4</class>     <entities>         <test>           <table>pfay_test</table>         </test>      </entities></test_mysql4></models>    <!-- allow the plugin to read and write --><resources>        <!-- connection to write -->        <test_write>            <connection>                <use>core_write</use>            </connection>        </test_write>

Page 13: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

192021222324252627282930

        <!-- connection to read ->       <test_read>          <connection>             <use>core_read</use>          </connection>       </test_read></resources> <!-- -/- -->

In :

It says here that the model classes wills be in the directory app/code/local/Pfay/Test/Model/ and the « resource » that is to say the thing used to collect data for the model will be defined by test_mysql4

defined in the classes will be in app/code/local/Pfay/Test/Model/Mysql4/ and an entity test represent the table pfay_test we have created earlier in the database.

Step 3: Create the ModelOnce your Model declared, you can now create the files. So create the following three files:

app/code/local/Pfay/Test/Model/

app/code/local/Pfay/Test/Model/Mysql4/

app/code/local/Pfay/Test/Model/Mysql4/Test/

Then, in app/code/local/Pfay/Test/Model/ create a file Test.php which will contain the following code:

123456789

<?phpclass Pfay_Test_Model_Test extends Mage_Core_Model_Abstract{     public function _construct()     {         parent::_construct();         $this->_init('test/test');     }}

This is your test model, you are telling that there’s a logical entity test of your plugin test .Then go to the folder app/code/local/Pfay/Test/Model/Mysql4/ and create a file Test.php which will contain:

Page 14: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

12345678

<?phpclass Pfay_Test_Model_Mysql4_Test extends Mage_Core_Model_Mysql4_Abstract{     public function _construct()     {         $this->_init('test/test', 'id_pfay_test');     }}

This is where you specify your model, a Magento test/test will use as primary key the id_pfay_test . (Be careful that this field is in auto increment and is the primary key of your table.

Then go to the folder app/code/local/Pfay/Test/Model/Mysql4/Test/ and create a file Collection.php which will contains:

123456789

<?phpclass Pfay_Test_Model_Mysql4_Test_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract {     public function _construct()     {         parent::_construct();         $this->_init('test/test');     }}

This file is used to define the model for your collection test/test.

You ‘re maybe not very well understanding what all this is, it is imperative that you to memorize these steps to create a template in Magento. Once these files are created, you can use your model to interact with your tables very easily.

Step 4: List contacts in our BlockRemember, in the preceding tutorial we have created a block in app/code/local/Pfay/Test/Block called Myblock.php . We will change that block to display the contact list in the database.

First, insert few lines in your database table pfay_test .

Then change your Myblock.php as follows:

123456

<?phpclass Pfay_Test_Block_Myblock extends Mage_Core_Block_Template{     public function methodblock()     {        //on initialize la variable        $retour='';        /* we are doing the query to select all elements of the pfay_test table (thanks to our model test/test and we sort them by

Page 15: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

789101112131415161718192021

id_pfay_test */     $collection = Mage::getModel('test/test')->getCollection()                                 ->setOrder('id_pfay_test','asc');         /* then, we check the result of the query and with the function getData() */        foreach($collection as $data)        {             $retour .= $data->getData('nom').' '.$data->getData('prenom')                     .' '.$data->getData('telephone').'<br />';         }         //i return a success message to the user thanks to the Session.         Mage::getSingleton('adminhtml/session')->addSuccess('Cool Ca marche !!');         return $retour;      } }

Looking at the code, I think you’ll understand what we did with comments, if this is not the case feel free to leave a comment.

Now test your code by going to http://yoursite.com/ test /index   and you’ll see your contact list.

Your homeworks:Try to repeat this and make a plugin from scratch before starting the next tutorial, you need to know to how to do the 4 firsts tutorials « fingers in the nose » before starting the next tutorial 

Practice for exemple in making a new plugin to manage your movie library. It strongly resembles to what we’ve done, but it’s different so you’ll be able to practice and really understand what you are doing. Good luck 

End of this tutorialHere is the end of this tutorial, I hope this tutorial helps you, you now know to interact with the database in your Magento extensions. Feel free to leave comments if you have any questions or comments 

Lession 5.Magento Developper’s Guide (Lesson 5) – The Model, collections and forms

This tutorial is the 5th of many   , if you do not have already read them from the start, i suggest you to start with the summary of this series.

We have in the previous tutorials creates a module with a controller, a block and its template and a connection to the database. We will now see how to go further with the database and how to better interact with magento.

Page 16: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

model, collections, forms …

As we saw earlier to retrieve data from your database, you have to use the getModel , which takes as parameters the type of object, in the previous tutorial we defined an object type test/test in our model.

So we will get this model by:

1 Mage::getModel('test/test');

With this model you can store messages and nicknames and you can retrieve an object in your database. If I want to get for example the « test » object with the identifier 2, you will do:

1 Mage::getModel('test/test')->load('2');

Now we want to retrieve all objects of this type that have been registered in our database. To do this we will use what is called a collectionwe will get through the method getCollection from our model.

1 $macollection =  Mage::getModel('test/test')->getCollection();

With this collection, we can make operation on our database such as:

12345

$macollection =  Mage::getModel('test/test')->getCollection();//sorted by ID$macollection->setOrder('id_pfay_test','asc');//only select those withe the phone number 03 20 58 74 89$macollection->addFilter('telephone', '0320587489');

Now, what would you say if you put your module in a form to add phone numbers directly from the frontend and it sorts the entries by user name when viewing? anyone? Ok here we go!

1 – Sort data when viewing

We have seen in the previous tutorial, your contact list is displayed in your block

So open Monbloc.php located in app/code/local/Pfay/Test/Block and change this line:

123

$collection = Mage::getModel('test/test')                    ->getCollection()                    ->setOrder('id_pfay_test','asc');

You notice it’s done in this line of code (it’s crazy it’s really good ^ ^).

2 – Add the Form

Edit the Template afficher.phtml located in \app\design\frontend\pfay\theme\template\test\ as this:

Page 17: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

123456789101112131415161718192021222324

<form action="<?php echo Mage::getUrl('test/index/save') ?>" method="post">  <fieldset>    <ul>     <li>       <label for="nom">Nom</label>       <input type="text" id="nom" name="nom" />     </li>     <li>         <label for="prenom">Prenom</label>         <input type="text" id="prenom" name="prenom" />     </li>     <li>        <label for="nom">Telephone</label>        <input type="text" id="telephone" name="telephone" />    </li>     <li>        <input type="submit" value="Save" />    </li>  </ul> </fieldset></form><?php   echo $this->methodblock(); ?>

Explanation:   This is a form, it send the informations to the method save of your controller IndexController of your module Test . The url will be found using the method getUrl.

Now, what happen when we send the form? Open the controller IndexController of your module Test (/app/code/local/Pfay/test/controllers /) and add the following method:

123456789101112131415

public function saveAction() {    //on recuperes les données envoyées en POST    $nom = ''.$this->getRequest()->getPost('nom');    $prenom = ''.$this->getRequest()->getPost('prenom');    $telephone = ''.$this->getRequest()->getPost('telephone');    //on verifie que les champs ne sont pas vide    if(isset($nom)&&($nom!='') && isset($prenom)&&($prenom!='')                               && isset($telephone)&&($telephone!='') )   {      //on cree notre objet et on l'enregistre en base      $contact = Mage::getModel('test/test');      $contact->setData('nom', $nom);      $contact->setData('prenom', $prenom);      $contact->setData('telephone', $telephone);      $contact->save();   }   //on redirige l’utilisateur vers la méthode index du controller indexController   //de notre module <strong>test</strong>

Page 18: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

161718192021

   $this->_redirect('test/index/index');}

To understand what i’ve made, read the comments in the code, it retrieves information on the form and saves them on base and then redirects to the index method.

Note that this piece of code that I put in the save method, we could have put it in the method of the block in order to record information in your list no matter where on your website you insert the block … it works well.

Your homework: again this tutorial, try saving your form data, practice blocks. .., that’s how we get there.

end of this tutorial Congratulations you have reached the end of this tutorial. Leave a message comment, It’s always nice and i love to talk with you guys 

Lession 6.

Magento Developper’s Guide (Lesson 6) – Create a plugin in the backend

This tutorial is the 6th of many   , if it’s not already done, i suggest you read to the tutorials starting with the summary of this series.

In this tutorial I will start by stopping listing you everything we have done since the beginning because it start to be a lot and it’s going to be boring (or to make you silly) ^ ^ So… you have done a complete plugin that runs on the front office, Today we will look at Backoffice !

Your address book appears in the frontend, how to ensure that our form (which we created in the previous tutorial   ) appears in the backoffice

Ready? Ok … let’s start

1 – Magento and administrationBefore starting like a warrior on the code, let’s start by understanding how the administration of magento works.

First of all you have to know that in the admin plugin it is always the same, there will be a « code » part and a « template » part (the principle of MVC … separate the code and the view), the part code is found in the « code » folders of your plugin in a directory called Adminhtml.

Page 19: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

Thus, administration Blocks of your plugin will be found in /app/code/local/Pfay/Test/Block/Adminhtml/

The controllers will be found in /app/code/local/Pfay/Test/controllers/Adminhtml/

And model is the same for the admin and the front part, of course we will not create a new one when it already existing)

For the backoffice part, you’ll search your templates and your layout in /app/design/adminhtml/default/Pfay/, once you are here, it’s the same as for the front, you have your file layout and your folder template where you store your layout and your respective templates.

2 – Hmm … 6th tutorials, it’s your turn : the first thing to do …?Obviously you are used, we start by editing the config.xml file in our plugin, go to /app/code/local/Pfay/Test/etc/.

After <\frontend> and before <global> add:

123456789101112131415161718192021222324252627

<admin>     <routers>         <test>            <use>admin</use>            <args>               <module>Pfay_Test</module>               <frontName>admintest</frontName>            </args>         </test>      </routers> </admin> <adminhtml>   <layout>      <updates>          <test>              <file>test.xml</file>           </test>      </updates>   </layout>   <menu>      <test translate="title" module="adminhtml">         <title>My plugins</title>         <sort_order>100</sort_order>         <children>             <set_time>                   <title>Adress book</title>                   <action>admintest/adminhtml_index</action>              </set_time>          </children>       </test>    </menu></adminhtml>

Page 20: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

2829303132

A little explanation ?

1234567891011

<admin>      <routers>          <test>             <use>admin</use>             <args>                <module>Pfay_Test</module>                <frontName>admintest</frontName>             </args>          </test>       </routers>  </admin>

First we create an administration router, the tag is set to use the admin can say that it will be an administration plugin (as opposed to if we had used the standard value).To access to the admin part of our plugin, we define a shortcut to the url thanks to the attribute frontName that we make as « admintest ». To access our plugin we will therefore go to the URL: http://votresite.com/admintest/adminhtml_index

123456789101112131415161718192021

<adminhtml>   <layout>      <updates>          <test>              <file>test.xml</file>           </test>      </updates>   </layout>   <menu>      <test translate="title" module="adminhtml">         <title>My plugins</title>         <sort_order>100</sort_order>         <children>             <set_time>                   <title>Adress book</title>                   <action>admintest/adminhtml_index</action>              </set_time>          </children>       </test>    </menu></adminhtml>

Page 21: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

Then, we define that the layout used to load this plugin will be file test.xml who will be in the folder /app/design/adminhtml/default/Pfay/layout/

Then thanks to the the tag menu we’re creating the menu for the administration

The tag is easy to decode, it says:

Title:   the title of the column (here « My plugins »)set_order:   the order in the menu (here 100 to put it at the end)

Then each children of this tag is a line of the menu. For each item children, there is a name and a link … In fact, each children menu is just a shortcut, if you will click on it, you are redirected to the page (in our example to http://yoursite.com/admintest/adminhtml_index )

3 – Create the controller of the admin partCreate the folder \app\code\local\Pfay\Test\controllers\Adminhtml\ and the file IndexController.php in it which will contain:

12345678

class Pfay_Test_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action{  public function indexAction()  {          $this->loadLayout();          $this->renderLayout();  }}

I don’t explain this file, you’ve aleady seen how it work in the previous tutorials

4 – Add the form in the admin interfaceNow your plugin works and can be accessed via the menu, even if (for now) it does nothing.

To save time, copy your file that contains your form phtml to the admin of magento, take the file afficher.phtml located in /app/design/frontend/pfay/theme/template/test/ and copy it to /app/design/ adminhtml /default/ Pfay /template/test/

in your form and add the following hidden field (required for security in magento)

1<input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>"  />

Now, change the layout test.xml in /app/design/adminhtml/default/Pfay/layout/ like this:

1234

<?xml version="1.0" ?><layout version="0.1.0">  <test_adminhtml_index_index>     <reference name="content">             <block type="test/monblock"  name="afficher_monbloc"

Page 22: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

56789

                  template="test/afficher.phtml" />      </reference>   </test_adminhtml_index_index></layout>

As you have copied the template in your template admin directory, it combines the block from the front with your template admin and it works, you now have your form in the administration 

This is the end of this tutorial Congratulations !! you have reached the end of this tutorial. As always leave a comment message to say if you like this article or not and ask questions. It’s always nice when you have any questions, please 

Lession 7.Magento Developper’s Guide (Lesson 7) – The magento admin grid

This tutorial is the 7th of many   , if it’s not already done, i suggest you read to the tutorials starting with the summary of this series.

Remember, in the previous tutorial we had created a part in the administration of magento to manage our contact list directly from the magento backend.

In the Magento administration, when you want to list your products, you see a GridView (a kind of table with which can be sorted, edit an article, delete etc …) and you’ll say that it could be nice to use the same in our module. In this tutorial we’ll see how to insert a GridView in the administration part of our Magento plugin.

A Magento Grid is constructed from a set of files that you will find in the file Block/Adminhtml from your module.

1 – The Grid ContainerCreate a folder: \app\code\local\Pfay\Test\Block\Adminhtml\ and put in a file Grid.php. This is the file which (as its name suggests) will contain your Grid. It contains:

123456789101112

<?phpclass Pfay_Test_Block_Adminhtml_Grid extends Mage_Adminhtml_Block_Widget_Grid_Container{    public function __construct()    {     //where is the controller     $this->_controller = 'adminhtml_test';     $this->_blockGroup = 'test';     //text in the admin header     $this->_headerText = 'Adressbook management';     //value of the add button     $this->_addButtonLabel = 'Add a contact';     parent::__construct();     }}

Page 23: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

131415

2 – The GridYou indicate that the controller’s grid will be in the test folder, create the folder then create a folder:\app\code\local\Pfay\Test\Block\Adminhtml\Test\ and create a file Grid.php in it containing :

12345678910111213141516171819202122232425262728293031323334353637

<?phpclass Pfay_Test_Block_Adminhtml_Test_Grid extends Mage_Adminhtml_Block_Widget_Grid{   public function __construct()   {       parent::__construct();       $this->setId('contactGrid');       $this->setDefaultSort('id_pfay_test');       $this->setDefaultDir('DESC');       $this->setSaveParametersInSession(true);   }   protected function _prepareCollection()   {      $collection = Mage::getModel('test/test')->getCollection();      $this->setCollection($collection);      return parent::_prepareCollection();    }   protected function _prepareColumns()   {       $this->addColumn('id_pfay_test',             array(                    'header' => 'ID',                    'align' =>'right',                    'width' => '50px',                    'index' => 'id_pfay_test',               ));       $this->addColumn('nom',               array(                    'header' => 'nom',                    'align' =>'left',                    'index' => 'nom',              ));       $this->addColumn('prenom', array(                    'header' => 'prenom',                    'align' =>'left',                    'index' => 'prenom',             ));        $this->addColumn('telephone', array(                     'header' => 'telephone',                     'align' =>'left',                     'index' => 'telephone',          ));         return parent::_prepareColumns();    }    public function getRowUrl($row)

Page 24: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

383940414243444546474849

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

We configure our magento Grid , stating the collection use to interact with the database in prepareCollection() (here we will use the collection of model ‘test/test’ created in the previous tutorials). Then with prepareColumns() he says which columns of our table with a display method addColumn(). I don’t explain the code more than that, it seems to me pretty obvious that if you want to add a column, just add an entry like this:

123456

$this->addColumn('telephone', array(     'header' => 'telephone',     'align' =>'left',     'index' => 'telephone', ));

Here, our Grid is now configured. Now, when we will click on one of the columns, we have to arrive on a form to edit our contact.

3 – The Form ContainerSo create a file edit.php in the same directory:\app\code\local\Pfay\Test\Block\Adminhtml\Test\This file edit.php will contain the following code:

12345678910111213

<?phpclass Pfay_Test_Block_Adminhtml_Test_Edit extends                    Mage_Adminhtml_Block_Widget_Form_Container{   public function __construct()   {        parent::__construct();        $this->_objectId = 'id';        //vwe assign the same blockGroup as the Grid Container        $this->_blockGroup = 'test';        //and the same controller        $this->_controller = 'adminhtml_test';        //define the label for the save and delete button        $this->_updateButton('save', 'label','save reference');        $this->_updateButton('delete', 'label', 'delete reference');    }       /* Here, we're looking if we have transmitted a form object,

Page 25: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

1415161718192021222324252627282930

          to update the good text in the header of the page (edit or add) */    public function getHeaderText()    {        if( Mage::registry('test_data')&&Mage::registry('test_data')->getId())         {              return 'Editer la reference '.$this->htmlEscape(              Mage::registry('test_data')->getTitle()).'<br />';         }         else         {             return 'Add a contact';         }    }}

I’ve commented the code, this file is a Form Container (see extends) That’s a structure that will allow you to receive application forms. Now we have to do the form itself.

4 – Create FormNow create the folder:\app\code\local\Pfay\Test\Block\Adminhtml\Test\Edit\in the file and form.php

This file will contain the following code:

123456789101112131415161718

class Pfay_Test_Block_Adminhtml_Test_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',                 )              );      $form->setUseContainer(true);      $this->setForm($form);      return parent::_prepareForm();   }}

Page 26: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

Here we create an object of type Varien_Data_Form that’s the « standard » magento form, we set the action attribute of the form with the function getUrl() and we defines the method of sending information (by post).And that’s all, we have defined our information form. Now we will create the lines of our form. In our directory\app\code\local\Pfay\Test\Block\Adminhtml\Test\Edit\, create a file Tabs.php which is actually a kind of « tabs container »)

This file will contain the following code:

12345678910111213141516171819202122

  <?php  class Pfay_Test_Block_Adminhtml_Test_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs  {     public function __construct()     {          parent::__construct();          $this->setId('test_tabs');          $this->setDestElementId('edit_form');          $this->setTitle('Information sur le contact');      }      protected function _beforeToHtml()      {          $this->addTab('form_section', array(                   'label' => 'Contact Information',                   'title' => 'Contact Information',                   'content' => $this->getLayout()     ->createBlock('test/adminhtml_test_edit_tab_form')     ->toHtml()         ));         return parent::_beforeToHtml();    }}

That entries will be created through block in the plugin Test, which will adminhtml_test_edit_tab_form, then create the folder:\app\code\local\Pfay\Test\Block\Adminhtml\Test\Edit\Tab and create the file in form.php .

123456789101112

<?phpclass Pfay_Test_Block_Adminhtml_Test_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form{   protected function _prepareForm()   {       $form = new Varien_Data_Form();       $this->setForm($form);       $fieldset = $form->addFieldset('test_form',                                       array('legend'=>'ref information'));        $fieldset->addField('nom', 'text',                       array(                          'label' => 'Nom',                          'class' => 'required-entry',                          'required' => true,                           'name' => 'nom',

Page 27: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

13141516171819202122232425262728293031323334353637

                    ));        $fieldset->addField('prenom', 'text',                         array(                          'label' => 'Prenom',                          'class' => 'required-entry',                          'required' => true,                          'name' => 'prenom',                      ));          $fieldset->addField('telephone', 'text',                    array(                        'label' => 'telephone',                        'class' => 'required-entry',                        'required' => true,                        'name' => 'telephone',                 )); if ( Mage::registry('test_data') ) {    $form->setValues(Mage::registry('test_data')->getData());  }  return parent::_prepareForm(); }}

5 – Insert our block in LayoutThen in the layout.xml your theme of directors, change your block by:

1 <block type="test/adminhtml_grid" name="test" />

That’s all, your grid works very well ! (no ? huhu…try again ??). Congratulations !!…Oh it not working :’(….it does not change? this is normal, you must implement the save method in your magento controller !

6 – Implement the functions in the controllerSo go in your \app\code\local\Pfay\Test\controllers\Adminhtml\IndexController.php and edit it like this:

123456

<?phpclass Pfay_Test_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action{    protected function _initAction()    {        $this->loadLayout()->_setActiveMenu('test/set_time')                ->_addBreadcrumb('test Manager','test Manager');

Page 28: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152

       return $this;     }      public function indexAction()      {         $this->_initAction();         $this->renderLayout();      }      public function editAction()      {           $testId = $this->getRequest()->getParam('id');           $testModel = Mage::getModel('test/test')->load($testId);           if ($testModel->getId() || $testId == 0)           {             Mage::register('test_data', $testModel);             $this->loadLayout();             $this->_setActiveMenu('test/set_time');             $this->_addBreadcrumb('test Manager', 'test Manager');             $this->_addBreadcrumb('Test Description', 'Test Description');             $this->getLayout()->getBlock('head')                  ->setCanLoadExtJs(true);             $this->_addContent($this->getLayout()                  ->createBlock('test/adminhtml_test_edit'))                  ->_addLeft($this->getLayout()                  ->createBlock('test/adminhtml_test_edit_tabs')              );             $this->renderLayout();           }           else           {                 Mage::getSingleton('adminhtml/session')                       ->addError('Test does not exist');                 $this->_redirect('*/*/');            }       }       public function newAction()       {          $this->_forward('edit');       }       public function saveAction()       {         if ($this->getRequest()->getPost())         {           try {                 $postData = $this->getRequest()->getPost();                 $testModel = Mage::getModel('test/test');               if( $this->getRequest()->getParam('id') <= 0 )                  $testModel->setCreatedTime(                     Mage::getSingleton('core/date')                            ->gmtDate()                    );                  $testModel                    ->addData($postData)                    ->setUpdateTime(                             Mage::getSingleton('core/date')                             ->gmtDate())                    ->setId($this->getRequest()->getParam('id'))                    ->save();

Page 29: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

53545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798

                 Mage::getSingleton('adminhtml/session')                               ->addSuccess('successfully saved');                 Mage::getSingleton('adminhtml/session')                                ->settestData(false);                 $this->_redirect('*/*/');                return;          } catch (Exception $e){                Mage::getSingleton('adminhtml/session')                                  ->addError($e->getMessage());                Mage::getSingleton('adminhtml/session')                 ->settestData($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                {                    $testModel = Mage::getModel('test/test');                    $testModel->setId($this->getRequest()                                        ->getParam('id'))                              ->delete();                    Mage::getSingleton('adminhtml/session')                               ->addSuccess('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('*/*/');       }}?>

Page 30: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

99100101102103104105106107108

109110

Now it really works!

This is the end of this tutorial That’s it for today;) It can seem abstract, but force yourself doing it again and again and do not worry at one time it will be easy for you.Feel free to leave your messages in comments, It’s always nice and if you have any questions I will answer you

Lession 8.Magento Developper’s Guide (Lesson 8) – Rewrite / modify a magento block

This tutorial is the 8th of many   , if it’s not already done, i suggest you read to the tutorials starting with the summary of this series.

Sometimes you need to change the behavior of Magento, we want for exemple to change the behavior of a block to display information about a product.

In this tutorial we will see how to change a basic block of Magento. When you want to do this kind of modification, it is better to keep in mind one of the basic rules magento development (attention if I make an exam … it will be asked..so remember ! XD)

« We never modify the files located in the core »

NEVER…NEVER…NEVER…it’s very important remember forget the idea of going directly edit the files in/app/code/core.

Instead, we will overload this Block, create a class that will extend this core Block and rewrite only the part you want to change. Then, in order to use it, declare your file in our config.xml file (as usual).

1 – Start by re-creating a module in your folder Pfay and call it MyProductSo create the file:

/app/code/local/Pfay/MyProduct

Page 31: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

With etc/config.xml and do not forget to declare the Pfay_All.xml (see lesson 2   ).

2 – Create your « modified » BlockWhat interests us is to rewrite the block Mage_Catalog_Block_Product_View. Let’s say we want to rewrite the method « showInfos » of this Block.

So we will create in /app/code/local/Pfay/MyProduct/Block/Product/file view.php.

Which will contain:

1234567

Class Pfay_MonProduit_Block_Product_View extends Mage_Catalog_Block_Product_View{   public function afficherLesInfos()   {      return 'les infos complementaires';   }}

3 – Tell Magento to take into account the new version of this blockEdit the config.xml of your module MyProduct and put in it:

12345678910111213141516171819

<?xml version="1.0"?><config> <modules>    <Pfay_MonProduit>        <version>1.0.0</version>    </Pfay_MonProduit> </modules> <global>   <blocks>    <catalog>         <rewrite>              <product_view>                    Pfay_MonProduit_Block_Catalog_Product_View               </product_view>             </rewrite>      </catalog>  </blocks> </global></config>

With these tags, we say we will configure a block of Magento’s core called « catalog » and we will rewrite () the « product_view » block of this module.

Page 32: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

Now it will take our new block to replace the base.

Conclusion:

« Et voila ! » (the french for « Here we are »   ) You now know to rewrite a block;)

As usual, feel free to leave your messages and make a comment links to these tutorials on your websites. It’s always nice:)

Lession 9.Magento Developper’s Guide (Lesson 9) – Rewrite / modify a Magento Model

This tutorial is the 9th of many   , if it’s not already done, i suggest you read to the tutorials starting with the summary of this series.

Here is a small article until the next which is a little longer to write, It subjects will be « the Events and Observers in Magento ».

If you want to help me, you can make a small article about this series of tutorials on your blog, you can tweet on these article, folow my facebook page and share it, talk about this blog, etc … But please no copy/paste, Google does not like! Thank you 

why and when editing an existing templateToday we will extend a Model, this may be useful sometimes so you need to know how to do it. This can be useful for exemple, if you want to change the method getName() of a customer.

How do you rewrite a modelLet’s start from the plugin MyProduct you have made in the previous tutorials and extend it model.

1234567891011121314

class Pfay_MonProduit_Model_Customer  extends Mage_Customer_Model_Customer{  public function getName()  {     $name = '';        if ($this->getPrefix()) {            $name .= $this->getPrefix() . ' ';        }        $name .= $this->getFirstname();        if ($this->getMiddlename()) {            $name .= ' ' . $this->getMiddlename();        }        $name .=  ' ' . $this->getLastname();        if ($this->getSuffix()) {            $name .= ' ' . $this->getSuffix();        }        return $name.'22222222';

Page 33: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

1516171819

  }}

Then the same principle, edit config.xml and add :

1234567

<models>  <customer>    <rewrite>      <product> Pfay_MonProduit_Model_Customer</product>    </rewrite>  </customer></models>

Now, if you use getName() method on an Customer object, you will have the string « 22222222″ after the name.

This is an example to show you that we can make modification of the model very easily, this example is useless but it is easy to understand 

Conclusion:And voila! (remember ?! « And voila » is the french word for « Here we are ! ») You now know how to rewrite a block;)

As usual, feel free to leave your messages and put a links to these tutorials on your websites. It’s always nice for me

Lession 10.Lesson 10 – Rewrite / Edit Controller Magento

This tutorial is the 10th in this series, if you have not already done it, i suggest you to read the tutorials starting withsummary of this series   .There’s a long time that i must write the leçcon 10, this day is finally arrived! The next months i just abandoned the blog, because I do not have much time to post … It’s been a while since I’m talking about a project, i’m still working on and honnestly subscribe to the newsletterbecause it will provide you an access to my project ! it will be huge !

Finaly there is this famous lesson 10 .. why I have not writen it until now? Because when I did the first blog posts I just did not know how too and I founded it a bit complicated…Since that time now i’ve learned a lot and i’m now magento certified developper Plus…it has been a long road to be there.

Page 34: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

ok so now how to make a rewrite of a controller ? Because your module will not khnow where to search for your extended class…you have to make a require in your controller.

1 require_once "Mage/Checkout/controllers/CartController.php";

This give you something like:

12345678

require_once "Mage/Checkout/controllers/CartController.php";class Pfay_Checkout_CartController extends Mage_Checkout_CartController{    # Rewrite of indexAction    public function indexAction() {        die('your method has been rewrited !!');    }}

the require_once is important if your extends not work (because magento can not autoload that class)

Then your class is taken into account instead of the « classic » CartController of magento, set in the config.xml of your module:

123456789101112131415

<?xml version="1.0" encoding="UTF-8"?><config>   ...<frontend><routers>     <checkout>         <args>           <modules>             <Pfay_Checkout before="Mage_Checkout">Pfay_Checkout</Pfay_Checkout>           </modules>         </args>     </checkout>   </routers></frontend></config>

Yes just it and it works! In fact he said « just take the controller Pfay_Checkout in my module before Mage_Checkout like that it loads my class, then this class extends the previous require_once class … and now it works.

Well this article was not so long to do it … in fact I hope it will help someone and it will be useful for you. Sometimes you just have to take the time but after a day of work and training we are tired and we think about thing differently ! All this to say that I would post more often and I thank you for reading this blog   It is you who motivate me to write and all your messages and comments make me very happy. Thank you again

Lession 11.

Page 35: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

Magento Developper’s Guide (Lesson 11) – Events and Observers in magento

This tutorial is the 11th of many tutorials   , you will now learn how to create your own controller in Magento. If you have not read the first articles yet, I strongly advise you to do so.

Today we will see a new way to modify a base behavior of magento thanks to the Events and the Observers. This kind of programming method is a web development standard i recommend you to master if you want to work with Magento.

1 – A bit of theoryThis programming method is called a « design pattern », what that is?

First,we will start by defining two terms:

Event: We can consider an event as a kind of flag that rises when a specific situation happens for example when the user presses the « pay » button of your website, it is an event. Your order has been registered? Here it is an event too. Etc …

Observer: An Observer is also called « Listener » he will listen to your program to detect events. When there is an event taking place, it will perform an action.

A small example: The neighbor and youLet us talk a bout a situation , you’re at home and you host a party ! you start the night party and everything goes well, then one time, one of your friend who drank a little too much (Okok he’s completly drunk xD !) begins to sing loudly in the garden …

Your neighbor is a « no life » and has never had a friend, he’s at home all the time (worst !! maybe it is a magento developper xD!) And it has nothing to do best of his life waiting you make too much noise to be able to call the police (for disturbing the peace) … that’s how he like to spent his time (we need all kinds of people to make a world).

In short, we all know that kind of situation. Now in this story, a friend makes too much noise, « making too much noise » here is the event .The observer is your neighbor, and he watches what? If you make too much noise (if an event is raised). And there will be action when the event is raised: call the police!

With this great example (in which I’m not talking about real facts … especially not my neighbor xD), you get the principle i hope! Now let’s go for practice and we will move to our favorite e-commerce CMS Magento …!

2 – Create an ObserverAn Observer in magento is in the directory Model of your plugin and extends the class Varien_Event_Observer (class which I think is clear …), go in /app/code/local/Pfay/Test/Model/ folder and create your Observer.php

Page 36: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

123456789101112131415

<?phpclass Pfay_Test_Model_Observer extends Varien_Event_Observer{   public function __construct()   {   }   public function saveCmsPageObserve($observer)   {         $event = $observer->getEvent();         $model = $event->getPage();     print_r($model->getData());         die('test'); }}?>

Here we’ve created an Observer with a function saveCmsPageObserve , this function is the method that will be executed when a page CMS will be saved in the backend of Magento.

In our example we stops the program to display a message but instead of a true die(), you will create a process to record additional information on your page in another table (for exemple).

I think i do not need you to explain this short code, I get the event using the method getEvent on the Observer we passed as parameter of the method (the parameter is automatically sent to the method). Then starting from the event, from the method getPage(), I get my cmspage and I display its content with print_r and the getData as we are used to.

3 – Ensures that the Observer is declared in MagentoNow we have created our Observer , we need to declare it in Magento, how it’s done? … 11th tutorial, if you have not an idea I urge you to hang you … muahahaha restart this series of tutorials from the beginning because I think you have not understood the Magento development principles.

SO…if you have understood, we will edit the config.xml our plugin. So open the file:/app/code/local/Pfay/Test/etc/config.xmlAnd in , after or after add:

12345678

<strong><events>   <cms_page_prepare_save>    <observers>       <Pfay_Exemple_Model_Observer>           <type>singleton</type>           <class>exemple/observer</class>           <method> saveCmsPageObserve</method>           </ Pfay_Exemple_Model_Observer>       </observers>  </cms_page_prepare_save>

Page 37: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

9101112

</events></strong>

Some small

explanations are necessary here:Tag:

1 <strong> <cms_page_prepare_save> </strong>

Represent the event is monitored in our example your neighbor was waiting you to do a lot of noise in order to launch its action (call the cops). Here we expect the action cms_page_prepare_save to launch our action saveCmsPageObserve ).

The rest seems logical:

12345678

<strong>    <observers>      <Pfay_Exemple_Model_Observer>     <type>singleton</type>     <class>exemple/observer</class>     <method> saveCmsPageObserve</method>         </ Pfay_Exemple_Model_Observer>    </observers></strong>

We define the class observer that will be used when this method will be called with the type, class and method to use.

Ok Ok I understand but how do we know that it is the event cms_page_prepare_save wich is used?

It is not complicated, in fact we will see in the core file, it opens the file: \app\code\core\Mage\Adminhtml\controllers\Cms\PageController.php look at the method saveAction() , at the following line:

12

<strong>      Mage::dispatchEvent('cms_page_prepare_save', array('page' => $model, 'request'>getRequest()));</strong>

It is by dispatchEvent that generates the event in our program.

With this line we know that the event is called cms_page_prepare_save and that he passes a table with a page that contains the model object and an request object, they may be recovered in your observer method thanks to the features getPage() and getRequest() .

Page 38: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

« Et voilà ! », I think we went around. Now you can have fun with the events and Observers in Magento.

Leave a comment to please me or to ask a question and if you liked this article help me by sharing a link to this article on your blog, facebook page or twitter.

Lession 12.Magento Developper’s Guide (Lesson 12) – The Helpers in magento

This tutorial is the 12th of many tutorials   , you will now learn how to create your own helper in Magento. If you have not read the first articles yet, I strongly advise you to do so. We have previously created a plugin, we will now learn how to use a helper!

What is a HelperAs the name implies a « helper » is something that is right for you ! It is an object that will contain practical functions for you and you can call it from anywhere, you just load your helper to use it. For example:

1 $helper = Mage::helper('monhelper');

Note that this call is actually equivalent to:

1 $helper = Mage::helper('monhelper/data');

Indeed, it is the default helper « data » wich is called.

Create your own HelperAs you are now used to, it starts by declaring it in the config.xml of your plugin, do that in <global> and after </blocks>

12345

<helpers>   <test>          <class>Pfay_Test_Helper</class>    </test></helpers>

Then creates the folder and the file app/code/local/Pfay/Test/Helper/data.php function wich will contains the function bytwo($ nbr) with a number as an argument and returns that number multiplied by two. A helper is an object that extends the core class Mage_Core_Helper_Abstract.

12345

<?phpclass Pfay_Test_Helper_Data extends Mage_Core_Helper_Abstract{   public function bytwo($nbr){        return $nbr*2;   }}

Page 39: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

6

Now in/app/code/local/Pfay/Test/Block/monblock.php we change the function by:

123456789

<?phpclass Pfay_Test_Block_Monblock extends Mage_Core_Block_Template{      public function methodblock()      {            $helper = Mage::helper('test');            return '2*2 = '.$helper->bytwo(2);      }}

Now when we go on http://yoursite.com/index.php/test/index/, we see that it works!

Here we are ! you understand how to create a helper on magento, I invite you to practice, the only way to improve yourself   If you have any questions, feel free to leave a comment.

You want to help me? Share this article on twitter, do an article on this series of tutorials on your blog, tell your friends, participate in the comments and return to this site;)

Lession 13.Magento Developper’s Guide (Lesson 13) – Add a field in System > Configuration and how to use it

This tutorial is the 13th of many tutorials   . If you have not read the first articles yet, I strongly advise you to do so. We have made good progress on this series of tutorial and I already want to congratulate you for having arrived so far;) Today we will see how to add a configuration field in the backoffice (System> Configuration) and how to use it. We will take the example of a field where we will put card numbers

Create a new plugin to store information about Payment card in System > ConfigurationWe will add on a side bar a « CARDS » section and a « cards » group with a tab « Config » and in it we will add a field to store your card numbers.

First start by creating the structure of your project (declare it in Pfay_All.xml, create your controllers folder, config …) then start to set it up (in config.xml of course;) )

The XML:

123456

<?xml version="1.0"?><config>    <modules>        <Pfay_Ecard>            <version>1.0.0</version>            <depends>            <!-- no dependencies -->

Page 40: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

7891011121314151617181920212223242526272829303132333435363738394041424344

            </depends>        </Pfay_Ecard>    </modules>    <frontend>           <routers>              <route_ecard>                  <use>standard</use>                  <args>                     <module>Pfay_Ecard</module>                     <frontName>ecard</frontName>                  </args>               </route_ecard>           </routers>        </frontend>     <adminhtml>      <acl>        <resources>            <admin>                <children>                    <system>                        <children>                            <config>                                <children>                                    <ecard_section translate="title">                                        <title>My Section </title>                                        <sort_order>100</sort_order>                                    </ecard_section>                                </children>                            </config>                        </children>                    </system>                 </children>            </admin>        </resources>    </acl>     </adminhtml></config>

Now awe will declare our menu by creating etc/system.xml, at this level of the tutorial i think explaining to you what are theses xml doing is not important;) Basically the first xml said: « In adminhtml (so..in the admin) in system create a new block …  »

1234

<?xml version="1.0" ?><config>    <tabs>        <ecard_tab translate="label">            <label>Cartes</label>

Page 41: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

56789101112131415161718192021222324252627282930313233343536373839

            <sort_order>100</sort_order>        </ecard_tab>    </tabs>    <sections>        <ecard_section translate="label">            <label>Cartes</label>            <sort_order>200</sort_order>            <show_in_default>1</show_in_default>            <show_in_website>1</show_in_website>            <show_in_store>1</show_in_store>            <tab>ecard_tab</tab>            <groups>                <ecard_group translate="label">                    <label>Config</label>                    <comment>Card Configuration</comment>                    <sort_order>10</sort_order>                    <show_in_default>1</show_in_default>                    <show_in_website>1</show_in_website>                    <show_in_store>1</show_in_store>                    <fields>                        <ecard_field translate="label comment">                            <label>Card Number</label>                            <comment>a text to help</comment>                            <show_in_default>1</show_in_default>                            <show_in_website>1</show_in_website>                            <show_in_store>1</show_in_store>                            <frontend_input>text</frontend_input>                        </ecard_field>                    </fields>                </ecard_group>            </groups>        </ecard_section>    </sections></config>

This xml is used to add our tab in the menu on the side of System > Configuration, then to retrieve information from the fields we will use:

1 Mage::getStoreConfig('ecard_section/ecard_group/ecard_field');

to test it, create the controller in controllers/IndexController.php :

[

12

<?phpclass Pfay_Ecard_IndexController extends Mage_Core_Controller_Front_Action{

Page 42: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

34567891011

    /*     * To test Ecards functions...     */    public function indexAction()    {        echo  Mage::getStoreConfig('ecard_section/ecard_group/ecard_field');    }}

then go testing your controller:http:/yoursite.com/index.php/ecard/index/index

You should see the information in your fields. 

Congratulations you now know to create a configuration fields in the backoffice!

WARNING:the ACL have to take effect so you must disconnect from the magento admin and login again.

thank you for following this tutorial and come back regularly on this blog… You want to help? Take 5 minutes to make a link to this article or about blog (or in twitter, google+ or more..) thank you very much;)

Lession 14.

Lession 15.Magento Developper Guide (Lesson 15) – Translate your Magento plugin, the Internationalization

This tutorial is the 15th of many tutorials   . If you have not read the first articles yet, I strongly advise you to do so.

As you know the websites are often translated into several languages, this plugin was not translated from one language to another, it is now time to get started.yOn Magento, you will find translations in folder/app/locale/ , is in fact the code for the language. For example the French translations will be found in /app/locale/fr_FR and the German’s will be in de_DE.

The files format is CSV and structure is as follows:

[txt]« String to translate », « la chaine traduite »[txt]

Files must be declared in your config.xml plugin:

1 <translate>

Page 43: alvessingh.files.wordpress.com€¦  · Web viewCreate a magento plugin from the start to the end ! Lesson 1. Magento Developper’s Guide (Lesson 1) – Magento plugins structure.

23456789

  <modules>    <Pfay_Test>             <files>          <default>Pfay_Test.csv</default>       </files>    </Pfay_Test>  </modules></translate>

Now when you want to translate your string, use:

12

<?php echo $this->__('String to translate'); ?>//result: la chaine traduite

Magento will search for the corresponding translation to your chain in your csv file. if you are in French, it will search the correspondence in the file/app/locale/fr_FR/Pfay_Test.csv, then he will find the string « String to translate » and return « la chaine traduite. »

I hope it will helps.