One crucial idea that’s extensively in Magento is Helper. So right here we are going to study what’s helper and tips on how to use them.
It’s all the time good concept to create all of the capabilities that are used steadily in a single class. That’s why we use helper to group all steadily used or widespread strategies collectively. It helps in implementing the DRY idea in coding.
By grouping I imply we create totally different helper which take care various things, if placing all of the strategies in a single class develop into too cumbersome. One such instance of grouping that you just steadily observe in magento is a helper to deal with all electronic mail associated duties.
The helpers may be injected anyplace (i.e. in Blocks, Controllers, templates, and many others) in order that we will entry the strategies of that helper class. Injection of sophistication is only a fancy time period for “mentioning the category within the constructor” in order that we will create object of that class.
On this weblog, for now I’ll solely create a single perform to get the client id. We can’t get the client id from session, if all of the caches are enabled. So we have to do some hack, which we are going to do later. If you happen to bear in mind we’ve used the client id in 3-4 locations. And all over the place we’ve used the session to get it. Now if we’ve to implement the hack, we should replace the code in 3-4 locations. Which isn’t best. So we are going to create a perform in helper to get the client id. And we are going to name it all over the place else the place the client id is required. So now we’ve to alter in just one perform, if we do some modifications later. Word that we are going to and might preserve including extra capabilities to the helper as we see match.
Creating and Utilizing the Helper
To create the helpers we use new folder named Helper contained in the module listing. By default we create helper with identify Information. However we will use any names. Let’s create the helper as Helper/Information.php
<?php
namespace WebkulBlogManagerHelper;
use MagentoCustomerModelSession;
class Information extends MagentoFrameworkAppHelperAbstractHelper
{
public $customerSession;
public perform __construct(
Session $customerSession,
MagentoFrameworkAppHelperContext $context
) {
$this->customerSession = $customerSession;
dad or mum::__construct($context);
}
public perform getCustomerId()
{
$customerId = $this->customerSession->getCustomerId();
return $customerId;
}
}
Since it is a helper, we’ve prolonged the default helper class. And we’ve created a technique to get the client id.
Now let’s shortly replace all of the codes the place we’ve used the client id. We should edit Block/BlogList.php
<?php
namespace WebkulBlogManagerBlock;
class BlogList extends MagentoFrameworkViewElementTemplate
{
public $blogCollection;
public perform __construct(
MagentoFrameworkViewElementTemplateContext $context,
WebkulBlogManagerModelResourceModelBlogCollectionFactory $blogCollection,
WebkulBlogManagerHelperData $helper,
array $information = []
) {
$this->blogCollection = $blogCollection;
$this->helper = $helper;
dad or mum::__construct($context, $information);
}
public perform getBlogs()
{
$customerId = $this->helper->getCustomerId();
$assortment = $this->blogCollection->create();
$collection->addFieldToFilter('user_id', $customerId)
->setOrder('updated_at', 'DESC');
return $assortment;
}
}
As you possibly can see right here, we’ve eliminated the session codes. And injected the helper class within the constructor and referred to as the getCustomerId perform.
We additionally need to edit the Controller/Handle/Edit.php
<?php
namespace WebkulBlogManagerControllerManage;
use MagentoCustomerControllerAbstractAccount;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkViewResultPageFactory;
class Edit extends AbstractAccount
{
public $resultPageFactory;
public $blogFactory;
public $helper;
public $messageManager;
public perform __construct(
Context $context,
PageFactory $resultPageFactory,
WebkulBlogManagerModelBlogFactory $blogFactory,
WebkulBlogManagerHelperData $helper,
MagentoFrameworkMessageManagerInterface $messageManager
) {
$this->resultPageFactory = $resultPageFactory;
$this->blogFactory = $blogFactory;
$this->helper = $helper;
$this->messageManager = $messageManager;
dad or mum::__construct($context);
}
public perform execute()
{
$blogId = $this->getRequest()->getParam('id');
$customerId = $this->helper->getCustomerId();
$isAuthorised = $this->blogFactory->create()
->getCollection()
->addFieldToFilter('user_id', $customerId)
->addFieldToFilter('entity_id', $blogId)
->getSize();
if (!$isAuthorised) {
$this->messageManager->addError(__('You aren't authorised to edit this weblog.'));
return $this->resultRedirectFactory->create()->setPath('weblog/handle');
}
$resultPage = $this->resultPageFactory->create();
$resultPage->getConfig()->getTitle()->set(__('Edit Weblog'));
$format = $resultPage->getLayout();
return $resultPage;
}
}
And in addition Controller/Handle/Save.php
<?php
namespace WebkulBlogManagerControllerManage;
use MagentoCustomerControllerAbstractAccount;
use MagentoFrameworkAppActionContext;
class Save extends AbstractAccount
{
public $blogFactory;
public $helper;
public $messageManager;
public perform __construct(
Context $context,
WebkulBlogManagerModelBlogFactory $blogFactory,
WebkulBlogManagerHelperData $helper,
MagentoFrameworkMessageManagerInterface $messageManager
) {
$this->blogFactory = $blogFactory;
$this->helper = $helper;
$this->messageManager = $messageManager;
dad or mum::__construct($context);
}
public perform execute()
{
$information = $this->getRequest()->getParams();
$customerId = $this->helper->getCustomerId();
if (isset($information['id']) && $information['id']) {
$isAuthorised = $this->blogFactory->create()
->getCollection()
->addFieldToFilter('user_id', $customerId)
->addFieldToFilter('entity_id', $information['id'])
->getSize();
if (!$isAuthorised) {
$this->messageManager->addError(__('You aren't authorised to edit this weblog.'));
return $this->resultRedirectFactory->create()->setPath('weblog/handle');
} else {
$mannequin = $this->blogFactory->create()->load($information['id']);
$model->setTitle($information['title'])
->setContent($information['content'])
->save();
$this->messageManager->addSuccess(__('You could have up to date the weblog efficiently.'));
}
} else {
$mannequin = $this->blogFactory->create();
$model->setData($information);
$model->setUserId($customerId);
$model->save();
$this->messageManager->addSuccess(__('Weblog saved efficiently.'));
}
return $this->resultRedirectFactory->create()->setPath('weblog/handle');
}
}
Yet another file that we’ve to edit is Controller/Handle/Delete.php
<?php
namespace WebkulBlogManagerControllerManage;
use MagentoCustomerControllerAbstractAccount;
use MagentoFrameworkAppActionContext;
class Delete extends AbstractAccount
{
public $blogFactory;
public $helper;
public $jsonData;
public perform __construct(
Context $context,
WebkulBlogManagerModelBlogFactory $blogFactory,
WebkulBlogManagerHelperData $helper,
MagentoFrameworkJsonHelperData $jsonData
) {
$this->blogFactory = $blogFactory;
$this->helper = $helper;
$this->jsonData = $jsonData;
dad or mum::__construct($context);
}
public perform execute()
{
$blogId = $this->getRequest()->getParam('id');
$customerId = $this->helper->getCustomerId();
$isAuthorised = $this->blogFactory->create()
->getCollection()
->addFieldToFilter('user_id', $customerId)
->addFieldToFilter('entity_id', $blogId)
->getSize();
if (!$isAuthorised) {
$msg=__('You aren't authorised to delete this weblog.');
$success=0;
} else {
$mannequin = $this->blogFactory->create()->load($blogId);
$model->delete();
$msg=__('You could have efficiently deleted the weblog.');
$success=1;
}
$this->getResponse()->setHeader('Content material-type', 'utility/javascript');
$this->getResponse()->setBody(
$this->jsonData->jsonEncode(
[
'success' => $success,
'message' => $msg
]
));
}
}
Now we’ve created and used a helper. Please confirm all of the pages that these modifications have an effect on. And please make a behavior of checking/verifying the modifications even when it’s a minor change.
Cacheable
Yet another factor that I missed earlier is use of cacheable argument. By default magento cached all pages. So when you allow all caches and verify the weblog itemizing web page you will notice some complicated outcomes.
Magento recommends that each one public pages (pages which may be accessed with out sign-in) should be cacheable. Which means all pages similar to class web page, product web page, cms web page are cached. And it make sense as a result of the general public pages are get steadily accessed and the info on these pages don’t change based mostly on who the consumer is.
Nevertheless for all non public web page (these pages which may be accessed solely after logging in), we should always disable the cache if the info is just not static for that web page.
We now have not but created any public web page, we are going to do in subsequent blogs. So in our case the personal pages are weblog itemizing, weblog edit web page and weblog add web page. We don’t care weblog add web page as a result of it’s static as a result of we simply present a clean type. However for the opposite two pages we should disable the cache. Which we will do from the format xml file.
So let’s first edit the view/frontend/format/blogmanager_manage_index.xml
<?xml model="1.0"?>
<web page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Structure/and many others/page_configuration.xsd">
<replace deal with="customer_account"/>
<physique>
<referenceContainer identify="content material">
<block class="WebkulBlogManagerBlockBlogList" identify="blogmanager.weblog.checklist" template="Webkul_BlogManager::checklist.phtml" cacheable="false" />
</referenceContainer>
</physique>
</web page>
Right here we’ve completed a really minor change. We now have simply added cacheable=”false” within the node. Now this web page gained’t be cached. Word that if there have been a number of blocks then including cacheable=”false” in any certainly one of them will make the entire web page non cacheable. Which means we can’t say that cache this block and never this in a web page.
Let’s edit the opposite web page too view/frontend/format/blogmanager_manage_edit.xml
<?xml model="1.0"?>
<web page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Structure/and many others/page_configuration.xsd">
<replace deal with="customer_account"/>
<head>
<css src="https://webkul.com/weblog/magento-2-development-22-helper/Webkul_BlogManager::css/model.css"/>
</head>
<physique>
<referenceContainer identify="content material">
<block class="WebkulBlogManagerBlockBlog" identify="blogmanager.weblog.edit" template="Webkul_BlogManager::edit.phtml" cacheable="false" />
</referenceContainer>
</physique>
</web page>
Now it’ll work advantageous even when we allow all caches.
Present Few Extra Columns
It isn’t associated to the earlier subjects. However it’s a minor change so I’ll append it on this weblog. As you possibly can see their are numerous necessary particulars are lacking from the weblog checklist on vendor facet. We’ll do some modifications to indicate standing, created at and up to date at on the grid.
First we are going to edit the phtml file view/frontend/templates/checklist.phtml
<div class="blog-list-table-container">
<desk class="blog-list-table">
<tr class="blog-list-table-head">
<th class="blog-list-table-id">
<?= __("Id")?>
</th>
<th class="blog-list-table-title">
<?= __("Title")?>
</th>
<th class="blog-list-table-content">
<?= __("Content material")?>
</th>
<th class="blog-list-table-status">
<?= __("Standing")?>
</th>
<th class="blog-list-table-date">
<?= __("Up to date At")?>
</th>
<th class="blog-list-table-date">
<?= __("Created At")?>
</th>
<th class="blog-list-table-action-edit">
<?= __("Edit")?>
</th>
<th class="blog-list-table-action-delete">
<?= __("Delete")?>
</th>
</tr>
<?php
$blogs = $block->getBlogs();
$statuses = $block->getStatuses();
foreach ($blogs as $weblog) {?>
<tr class="blog-list-table-row">
<td class="blog-list-table-id">
<?= $blog->getId()?>
</td>
<td class="blog-list-table-title">
<?= $blog->getTitle()?>
</td>
<td class="blog-list-table-content">
<?= substr($blog->getContent(), 0, 20).'...'?>
</td>
<td class="blog-list-table-status">
<?= $statuses[$blog->getStatus()]?>
</td>
<td class="blog-list-table-date">
<?= $block->getFormattedDate($blog->getUpdatedAt())?>
</td>
<td class="blog-list-table-date">
<?= $block->getFormattedDate($blog->getCreatedAt())?>
</td>
<td class="blog-list-table-action blog-list-table-action-edit">
<a href="https://webkul.com/weblog/magento-2-development-22-helper/<?= $block->getUrl("weblog/handle/edit', ['id'=>$blog->getId()])?>">
<?= __('Edit') ?>
</a>
</td>
<td class="blog-list-table-action blog-list-table-action-delete">
<a href="https://webkul.com/weblog/magento-2-development-22-helper/<?= $block->getUrl("weblog/handle/delete', ['id'=>$blog->getId()])?>">
<?= __('Delete') ?>
</a>
</td>
</tr>
<?php } ?>
</desk>
</div>
<script sort="textual content/x-magento-init">
{
"*": {
"bloglist": ""
}
}
</script>
Within the head part of the desk we’ve added the three columns and equally within the physique part additionally.
We now have referred to as a technique getStatuses
which is able to return an associative array with integer (0 or 1) as the important thing and the standing label as the worth. Utilizing this we will present the label based mostly on the worth.
Yet another factor is that we’re not exhibiting the date straight from the database. We now have created getFormattedDate perform within the block class which is able to format the date in a pleasant readable format.
Now let’s create these strategies in Block/BlogList.php
<?php
namespace WebkulBlogManagerBlock;
class BlogList extends MagentoFrameworkViewElementTemplate
{
public $blogCollection;
public $statuses;
public perform __construct(
MagentoFrameworkViewElementTemplateContext $context,
WebkulBlogManagerModelResourceModelBlogCollectionFactory $blogCollection,
WebkulBlogManagerHelperData $helper,
WebkulBlogManagerModelBlogStatus $blogStatus,
MagentoFrameworkStdlibDateTimeTimezoneInterface $date,
array $information = []
) {
$this->blogCollection = $blogCollection;
$this->helper = $helper;
$this->blogStatus = $blogStatus;
$this->date = $date;
dad or mum::__construct($context, $information);
}
public perform getBlogs()
{
$customerId = $this->helper->getCustomerId();
$assortment = $this->blogCollection->create();
$collection->addFieldToFilter('user_id', $customerId)
->setOrder('updated_at', 'DESC');
return $assortment;
}
public perform getStatuses()
{
$statuses = [];
foreach ($this->blogStatus->toOptionArray() as $standing) {
$statuses[$status['value']] = $standing['label'];
}
return $statuses;
}
public perform getFormattedDate($date)
{
return $this->date->date($date)->format('d/m/y H:i');
}
}
In getStatuses we’ve used the category that we created to get the statuses for the ui element. It’s a good apply as a result of if we wish to add extra statuses then we should change solely in a single file.
To get the formatted date we’ve used MagentoFrameworkStdlibDateTimeTimezoneInterface which is able to return the date within the talked about format. If we wish to convert then we’ve to cross the timestamp in date() and if we depart it empty then the present timestamp will likely be used. Word that it will return the date based mostly on the locale.
Now you will notice all the small print like,
Subsequent Weblog -> Coming Quickly.
Earlier Weblog -> Magento 2 Growth 21: Loading Magento’s Information