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

5 octobre 2011

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 block

For 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.


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 controller

Remind , 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:

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 yoursite.com/test/index for example).

   $this->loadLayout();    //Va chercher les elements à afficher
   $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> :

<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:

<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_IndexController is 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

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:

<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;)

     <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 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

And we will add in this file, the line:

      <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 block

Now, 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:

<?php
class 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 template

Now 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 works

We 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.

Step 5: Test!

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

End of this tutorial

Now 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 !)

find the summary of this tutorial

You should read this too :
  • No Related Post
kalai # 18 octobre, 2011

Hi, first of all very nice tutorial. I am working on magento for past 1 year. I tried your tutorial but im in struggle with the templates.. i followed everything but i can’t view the affi.phtml content…

# 18 octobre, 2011 admin

Hi Kalai, have you flush your Magento Cache ? ;)

basila # 29 octobre, 2011

I have the same problem with the magenta 1.6.0

kalai corrected this problem?

# 2 novembre, 2011 admin

@basila, @kala, @ashwini and all the other wich will as the same question: flush your cache and verify the syntax is correct for the Files, xml and all is the same as in the tutorial…it must work for you too if you had strictly follow the tutorial :) good chance to you guys :)

Gustavo # 16 novembre, 2011

Hello Everyone,

There are some errors and tags missing in the translation, I went trough the original french tutorial pierrefay.fr/guide-magento-developpeur-creez-block-149 and using google translator, I figured out that there is something important missing, the « layout » tag in the config.xml goes inside « frontend » and after « routers ».
The « global » goes inside « config », after « frontend ».

Everything is working now. Read the comments in french using google translator, they explain some interesting thigs there.

@admin: could you check that? There are some missing tags in step two, it says: Open it and add it in and after :, I think that when the translation was made, the tags were ommited.

Thanks for the tutorial, I’m following it step by step.

# 5 décembre, 2011 Elric

All of these articles have saved me a lot of headcaehs.

Gershon # 19 décembre, 2011

Worked real nice so far.. i been doing this for a bit but really wanted to understand how this works in depth..nice job bro continuing to next step…

# 2 janvier, 2012 sohail

Nice tutorial,but unfortunately, the block and there layout is not working for me. I think there some issues to connect block with the template and display something. I the block class is not called. Someone can please respond to that.

Thanks

Pardeep # 9 janvier, 2012

Hi,

i followed everything but i can’t view the output. it gives me an error. Can someone send me an email with attached these files at pardeep19@orangemantra.com.
Thanks in advance.
Pardeep

# 27 janvier, 2012 Jeff

followed everything. the only way I can get this to work was to relocate all /app/design/frontend/pfay/…
to app/design/frontend/base/template/pfay/…

Please tell me why I had to move the structure?

THX

vivek # 17 février, 2012

@admin, @pierre fay

it is not showing anything…

i’ve checked it thrice… so please give some suggestion.

its urgent…

# 17 février, 2012 Morthan

Hi,

I did everything step by step and I don’t see output from Monblock.php in view. Who knows why?
Is it possible, in step 2 into listing 3 in block tag in name attrib is a typo?

Emrah # 19 février, 2012

I was getting empty page and « Invalid block type » error in log file. Then I renamed block folder as « Block » and worked. That is folder names are case sensitive.
Thanks for this very good tutorial.

# 24 février, 2012 Pierre FAY

Thanks @everyone for all your message, i don’t have a lot of time to improve this blog for the moment but it will come soon.

@jeff: it’s because you must specify it in your Admin >Config > design, you must specify your workspace and where magento will get images,css etc… ;)

vivek # 2 mars, 2012

Hey Pierre, please help me…

I get the theme after done but that msg is not displayed…

what is the reason for that??

i’ve changed the folder as per jeff’s suggestion but not succeed.

Help me soon…

# 14 mars, 2012 kahovn

I have did everything step by step of tutorial, but when run : localhost/magento/test. Occure error as NetworkError: 404 Not Found – localhost/magento/test.

Please help me why?
Thanks

Khoa # 22 mars, 2012

Hi everyone,

I have one problem , when I config block with tag to call methods from my block class shall not be run.

Please help me this problem.
Thank you very much.

# 22 mars, 2012 Khoa

Hi everyone,

I have one problem , when I config block with class tag to call methods from my block class shall not be run.

Please help me this problem.
Thank you very much.

tuan # 7 avril, 2012

i do step by step. But i can’t show the message from method.
Can anyone send me a zip file container full code ?

# 10 avril, 2012 Michael

A common problem: if all is working except that you do not see the output of your block – make sure your layout and template files are inside the actual theme that the system is using! If all else fails set you theme back to default/default and then then place the files in default/default/layout and default/default/template respectively.

Geoff # 10 avril, 2012

If you can’t get the words to show up but there’s really no printed errors, try this:

Change location of test.xml to this folder: app / design / frontend / default / default / layout /

Change location of afficher.phtml to this folder: app / design / frontend / default / default / template / test /

Why default / default ? Because most Magento package / theme are set to that by default. If you’ve changed to a custom package / theme, you’ll need to change those path names…

The folder AFTER /template/ called /test/ is defined in the test.xml file.

What helped me was to turn on the Template Path Hints in Configuration > Developer > Debug. Btw, I’m on v.1.6.2.0. I realized I was missing the /test/ folder from the template. As soon as I added that in, everything was peachy ;)

# 4 mai, 2012 Gulam

I followed everything step by step but i can’t view the afficher.phtml content…

kalai, Did you get idea ?

Admin help me please…

Thank you :)

desbest # 18 juin, 2012

I’ve tried everything here out, and I can’t get the afficher.phtml block to show on the page.

Please help. :)

# 19 juin, 2012 anonymous

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

Should be

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

correct ??

zuber # 20 juin, 2012

toooooooooooooooooooooooo good

# 26 juin, 2012 khalid

Thanks for explaining in such a nice way ( Or my way ;) )

khalid # 27 juin, 2012

Worked just fine. Guys u we need to do some hectic homework before trying these codes. They are not for newbies. Just a reminder : do not make theme folder as stated in step 4. It should be your magento theme folder ( e.g. default ).

# 3 juillet, 2012 Michael

Great Tutorials, am giving up for now. Have went through this several times and can’t get anything to show.

Apart from what seems to be a default .xml file for the layout which leads me to believe there is a directory mistake somewhere in my code.

Michael # 4 juillet, 2012

Fixed it after doing some homework, Thanks Again!

# 18 juillet, 2012 marcinsdance

The block appeared only after I’ve put the two files into my theme directory specified in System->Config->Design
(pine in my case):

location of test.xml: app/design/frontend/default/pine/layout/test.xml

location of afficher.phtml: app/design/frontend/default/default/template/test/afficher.phtml

Robin # 1 août, 2012

Hi All,

i gone through the tutorial… But when i put the layout test.xml and afficher.phtml file inside the Pfay theme it’s not working…but when i put into the frontend/base/default folder everything works fine for me…
magento took the default theme here, that’s the reason it’s not get displayed…As per the tutorial Pfay is a additional theme….

Regards
Raphael

# 1 août, 2012 Robin

Hi,

Thanks for the tutorial…its a good tutorial i ever seen…

Regard
Raphael

jagat # 11 août, 2012

Thanks! it worked for me finally. All your comments saves lots of time. Thanks all you Guys!!!!

# 24 septembre, 2012 Samir J M Araujo

Thanks for this great articles series! For those guys like me that almost gave up on coding and started selling hot dogs on the streets, if your template afficher.phtml doesn’t show up, make sure that your block Monblock.php on app/code/local/Pfay/Test/Block has a capital « M »

Alex # 4 octobre, 2012

I found what my theme was then I mooved the layout and template files in the appropriate directory but it still isn’t working. I have a server eror… maybe it is the .phtml file? Mine is this one :

[Php]
methodblock();
?>
[/Php]

# 4 octobre, 2012 Alex

sorry it didn’t work for my code:

I added a php tag between [Php] and the echo function and I changed [/php] in [/Php].

Vithal Bariya # 21 novembre, 2012

change this file Monblock.php

replace this code

# 12 décembre, 2012 Vithal Bariya

change this file Monblock.php
replace this code

‘informations about my block !!’

another type

informations about my block !! single cot

magentoNewb # 25 décembre, 2012

Great work.. finally it worked for me.. Thanks a lot.. placed test.xml in frontend/base/default/layout/ and afficher.phtml in frontend/base/default/template/test/ directory.

# 16 mars, 2013 Abhishek

Finally it worked for me.
if you are in trouble please follow the steps.
1.edit afficher.phml
methodblock();
?>

2. Change location of test.xml to this folder: app / design / frontend / default / default / layout /

3.Change location of afficher.phtml to this folder: app / design / frontend / default / default / template / test /

thanks Geoff for this.

Duy # 3 mai, 2013

I tried this tutorial and I can’t see the information my block in fronted. Finally, I resolved it (if you use template like « default/default »)
In file test.xml at layout folder, please add this line below:

…. (your code originial)

It will be worked ! Trust me ^^ »

# 7 mai, 2013 jawwad ahmed

Finally worked, a bit triky.

Guys follow Raphael comments and move your files to /base/default everything will work

Thanks for tutorial and thannks for comments too.

jawwad

Daniel # 1 juillet, 2013

This helped me alot! Thanks 1000 times.

# 1 juillet, 2013 Haseeb

Thanks for the step by step. It wasn’t working for me as well. i kept on banging my head. reading again and again if i missed anything. Than i copied layout and template to default/default/template and default/default/layout. still nothing. than i removed

from the xml file and it worked

Rupesh Kumar Singh # 3 août, 2013

This is very good tutorial for beginners.

# 15 août, 2013 Sanjib Dutta

This is very good.it help me a lot as a beginners.

Jose Manuel Orts # 23 août, 2013

Thank you very much for this great tutorial series!! And thank Geoff very much!!, who help me to show the data, because it’s the default module which render layout.

# 5 septembre, 2013 Rashmi

Got the error.. i have placed the under but it shoulb be before in config.xml

Adnan Arshad # 7 octobre, 2013

Great work.. finally it worked for me.. Thanks a lot..

placed:
app/design/frontend/base/default/layout/test.xml
and
app/design/frontend/base/default/template/test/afficher.phtml

enjoy

# 12 novembre, 2013 Vikash

Hi,
Great tutorial help me a lot.Thanks admin.You doing a great job Thanks Again

E # 8 janvier, 2014

To fix the problem when the block text doesn’t appear :
1. make sure you have cache disabled, this is a good advice not only in this case but for the whole development process (System -> Cache Management -> Select All -> Action Disable -> Submit)

2. Change location of test.xml to this folder: app / design / frontend / default / default / layout /

3.Change location of afficher.phtml to this folder: app / design / frontend / default / default / template / test /
(as suggested by Abhishek)

4. edit afficher.phtml to

# 9 février, 2014 Altaf Hussain

I am building module for magento 1.8.x, and this tutorial is helping me a lot. I followed all the steps, but the block was not calling. It was due to default tag in the my layout test.xml file. I remove that default tag contents and then it started work. I dont know why, but now it is working fine. :) . Thanks for nice articles.

Altaf Hussain # 9 février, 2014

I am sorry, ignore my above comment and delete it. The issue was due to the tag . I replaced it with and then it started work.

# 10 février, 2014 karan

Done :D

Raghuveer # 2 juin, 2014

I do not know why people are not getting the required out put. I followed this tutorial and got the result exactly as expected. Please follow this tutorial again and you will get it.

# 17 juin, 2014 Nilam Dodiya

Thanks…This helped me alot!

Vous aussi donnez votre avis
(requis)



Expert magento sur Lille - Pierre FAY