Create a block in magento2

This tutorial is the 4th in a long series of magento2 tutorial. It will be updated as the platform evolves. You will now learn how to create a block to inject logic into your Magento2 templates. If you do not know magento (v1) it does not matter, I'll talk about it of course but it is not require to know the magento platform (v1) to master this tutorial on magento2. In the previous tutorial we saw how to create a view on magento2 for our extension! We are now going to see how to put logic in your block because to display static templates is nice 2min but we want to move to the higher level ;).

Create our magento2 block

The block is the logical part that will be used in the layout to display the template. There is two parts in a block: the "visual" part which is the phtml, and the logical part that I will call in the next steps of this tutorial : the "block". When we speak of block, we will talk about the "logical" part which will be in the "Block" folder of our module. And when I talk about "template", I will talk about the phtml that is in your "view" folder.

So start by creating a "Block" (be carefull of the capitalization) folder at the root of your module (/Pfay/Contact/Block). This folder will contain all the blocks of our module (all the logical parts of our module will be in this "Block" folder, and all phtml templates will be in the "view" folder).

Create a Contactslist.php file inside this folder. This file will have the following contents:

<?php
namespace Pfay\Contacts\Block;
use Magento\Framework\View\Element\Template;

class Contactslist extends \Magento\Framework\View\Element\Template
{
    public function __construct(Template\Context $context, array $data = array())
    {
        parent::__construct($context, $data);
        $this->setData('contacts',array());
    }

    public function addContacts($count)
    {
        $_contacts = $this->getData('contacts');
        $actualNumber = count($_contacts);
        $names = array();
        for($i=$actualNumber;$i<($actualNumber+$count);$i++) {
            $_contacts[] = 'nom '.($i+1);
        }
        $this->setData('contacts',$_contacts);
    }
}

What is in this class? This class use an attribute $_contacts of Array type, empty vide lors de son instanciation.
At every call of the function addContacts, we will add 1 to the count of the contacts.
You will notice that you can pass information to the block and retrieve it automatically via the "magic methods" $this->getData('mavariable') and $this->setData ('mavariable', 'mavaleur')
Magento developers (v1) are used to use the "magic methods".

Link our magento2 block to our template

We must now change the layout for our contactslist.phtml template to look for the class we just created ( Pfay\Contacts\Block\Contactslist ) instead of the class we used before ( Magento\Framework\View\Element\Template ).
Edit the file Pfay/Contacts/view/frontend/layout/contacts_test_index.xml like that :

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Pfay\Contacts\Block\Contactslist" name="contactForm" template="Pfay_Contacts::test_index.phtml"></block>
        </referenceContainer>
    </body>
</page>

Modify our phtml template to use the functions of our block

Now that we have made the link between the template and the block in the layout, we can use the functions of the block in the templates! We will therefore modify the file /Pfay/Contacts/view/frontend/templates/contactslist.phtml as follows:

<div id="contactslist">
    <h2>empty</h2>
    <table>
        <tr>
            <th>Name</th>
        </tr>
        <?php $contacts = $this->getData('contacts'); ?>
        <?php foreach ($contacts as $contact): ?>
            <tr>
                <td><?php echo $contact ?></td>
            </tr>
        <?php endforeach; ?>
        <tr>
            <td>there is no contact in this list</td>
        </tr>
    </table>


    <h2>10 éléments</h2>
    <table>
        <tr>
            <th>Name</th>
        </tr>
        <?php $this->addContacts(10); ?>
        <?php $contacts = $this->getData('contacts'); ?>
        <?php foreach ($contacts as $contact): ?>
            <tr>
                <td><?php echo $contact ?></td>
            </tr>
        <?php endforeach; ?>
    </table>

    <h2>20 éléments</h2>
    <table>
        <tr>
            <th>Name</th>
        </tr>
        <?php $this->addContacts(10); ?>
        <?php $contacts = $this->getData('contacts'); ?>
        <?php foreach ($contacts as $contact): ?>
            <tr>
                <td><?php echo $contact ?></td>
            </tr>
        <?php endforeach; ?>
    </table>
</div>

At first, there are no contacts. The method is called by passing 10, so there are 10 contacts. We reapply the method by passing it 10, so there are now 20contacts.
This code is simple but it allows you to see that we can easily call the methods of our block magento2 from the templates.
Then go to your page www.magento2.lan/contacts/test/index and see the result :)

There you go ! This is the end of this tutorial. Does not it work for you? Retrieve the sources of this module on the bottom and find it more easily by downloading the code at the bottom of this tutorial.

You now know how to add a block and link it to your magento2 template... Congratulations!

As usual, if you liked this tutorial, please take a premium account to offer me cofee :) Do not hesitate also to ask your questions in the comments, I will try to answer quickly
Available documents for this article :
Books that can help you :
  • Livre Magento 2 Developer's Guide by Branko
  • Livre Mastering Magento2 Second Edition
  • Livre Magento 2 Cookbook
Questions about this lesson
No questions for this lesson. Be the first !

You must be logged in to ask for help on a lesson.