Reminder on the Magento2 MVC
When we go on http://www.example.com/mymodule/test/index Magento2 will call our action app/code/Hikmadh/Mymodule/Controller/Test/Index.php :
_view->loadLayout();
$this->_view->renderLayout();
}
}
In this action it loads the layout and display it. Magento will fetch the file app/code/Hikmadh/Mymodule/view/frontend/layout/mymodule_test_index.xml.
It knows the information to display for our action thanks to the directives contained in this layout file.
Here magento display our block using the class Hikmadh\Mymodule\Block\Contactslist for the “logical” part and the Hikmadh_Mymodule::test_index.phtml template
i.e app/code/Hikmadh/Mymodule/view/frontend/templates/test_index.phtml for the "view" (template) part.
Edit our magento2 block to get the collection
We will now modify our block so that it automatically takes a contact type object when it is created that will allow us to retrieve its collection and pass it to our template. Edit your Contactslist.php file like this:
_mymodel = $mymodel;
$this->_resource = $resource;
parent::__construct(
$context,
$data
);
}
public function getContacts()
{
$collection = $this->_mymodel->getCollection();
return $collection;
}
}
Show the collection items in the template
We will then edit our template file app/code/Hikmadh/Mymodule/view/frontend/templates/test_index.phtml as follows:
getContacts();
?>
empty
html/
Name
email
getName(); ?>
getEmail(); ?>
there is no contact in this list
You notice that we use the function getContacts() created in the block just above. Display your page (do not forget to empty your cache) and you should normally see your contact table displayed on the magento front office. Congratulations this is the end of this tutorial which is finally a reminder for the developers magento2 🙂