对象已移动

可在此处找到该文档 Magento 2 Development 22: Helper – New Self New Life
New Self New Life
No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
New Self New Life
No Result
View All Result
Home Softwares

Magento 2 Development 22: Helper

by admin
4 years ago
in Softwares
Magento 2 Development 22: Helper
Share on FacebookShare on Twitter


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,

2021-08-03_10-36

Subsequent Weblog -> Coming Quickly.

Earlier Weblog -> Magento 2 Growth 21: Loading Magento’s Information

author-thumb

Sanjay Chouhan
7 Badges

3 August 2021



Source link

Tags: DevelopmentHelperMagento
Previous Post

onInput Event

Next Post

The Best Places To Buy Second-Hand Clothes Online: 2021 Edition

Related Posts

User Guide for Odoo Zoho Analytics Connector
Softwares

User Guide for Odoo Zoho Analytics Connector

by admin
September 16, 2025
30+ Best Business & Corporate Report Templates for InDesign & Photoshop in 2025 — Speckyboy
Softwares

30+ Best Business & Corporate Report Templates for InDesign & Photoshop in 2025 — Speckyboy

by admin
September 18, 2025
Software tool turns everyday objects into animated, eye-catching displays—without electronics
Softwares

Software tool turns everyday objects into animated, eye-catching displays—without electronics

by admin
September 17, 2025
Surviving the AI Takeover in QA: How to Join the Top 1%
Softwares

Surviving the AI Takeover in QA: How to Join the Top 1%

by admin
September 14, 2025
We are getting close now – Vivaldi Browser snapshot 3797.35
Softwares

We are getting close now – Vivaldi Browser snapshot 3797.35

by admin
September 10, 2025
Next Post
The Best Places To Buy Second-Hand Clothes Online: 2021 Edition

The Best Places To Buy Second-Hand Clothes Online: 2021 Edition

Savage Garden's Darren Hayes shares the Truly Madly Deeply rewrite he just rejected for a TV ad

  • Trending
  • Comments
  • Latest
I Only Have More Questions After Another Bizarre Outing With The Harrigans

I Only Have More Questions After Another Bizarre Outing With The Harrigans

April 20, 2025
Amazon Forgot to Take the 2024 MacBook Air Off Sale After Their Big Spring Event

Amazon Forgot to Take the 2024 MacBook Air Off Sale After Their Big Spring Event

April 4, 2025
Google’s AI Ambitions An ‘Existential Crisis’ For News Online

Google’s AI Ambitions An ‘Existential Crisis’ For News Online

September 6, 2025
Instagram Adds New Teleprompter Tool To Edits

Instagram Adds New Teleprompter Tool To Edits

June 11, 2025
The Most Visited Websites in the World [Infographic]

The Most Visited Websites in the World [Infographic]

May 12, 2025
Acyan's "Ghost Town" EP Is Bass Music Storytelling at Its Most Ominous

Acyan's "Ghost Town" EP Is Bass Music Storytelling at Its Most Ominous

May 18, 2025
Easy Blueberry Scones (With Frozen Blueberries)

Easy Blueberry Scones (With Frozen Blueberries)

April 10, 2025
Where will Prince Harry stay during UK visit without Meghan Markle?

Where will Prince Harry stay during UK visit without Meghan Markle?

September 8, 2025
Blake Lively Taught Me This! | Perez Hilton

Blake Lively Taught Me This! | Perez Hilton

September 19, 2025
Why Was ‘The Late Show With Stephen Colbert’ Canceled? The Real Reason – Hollywood Life

Why Was ‘The Late Show With Stephen Colbert’ Canceled? The Real Reason – Hollywood Life

September 19, 2025
Julia Fox Brings Adorable Son to Him Premiere — Plus More Star Sightings!

Julia Fox Brings Adorable Son to Him Premiere — Plus More Star Sightings!

September 18, 2025
YELLOWSTONE Spinoff THE DUTTON RANCH Adds Jai Courtney to the Cast — GeekTyrant

YELLOWSTONE Spinoff THE DUTTON RANCH Adds Jai Courtney to the Cast — GeekTyrant

September 18, 2025
This S’pore startup wants to make alt-meat as cheap as chicken

This S’pore startup wants to make alt-meat as cheap as chicken

September 18, 2025
Country singer Spencer Hatcher shares emotional video weeks after his mother’s murder: ‘My biggest fan’

Country singer Spencer Hatcher shares emotional video weeks after his mother’s murder: ‘My biggest fan’

September 18, 2025
Meta Showcases New AI Glasses, VR Upgrades, at Connect 2025

Meta Showcases New AI Glasses, VR Upgrades, at Connect 2025

September 18, 2025
Dave Blunts Says Kanye West Tried To ‘Groom’ Him

Dave Blunts Says Kanye West Tried To ‘Groom’ Him

September 18, 2025
New Self New Life

Your source for entertainment news, celebrities, celebrity news, and Music, Cinema, Digital Lifestyle and Social Media and More !

Categories

  • Celebrity
  • Cinema
  • Devices
  • Digital Lifestyle
  • Entertainment
  • Music
  • Social Media
  • Softwares
  • Uncategorized

Recent Posts

  • Blake Lively Taught Me This! | Perez Hilton
  • Why Was ‘The Late Show With Stephen Colbert’ Canceled? The Real Reason – Hollywood Life
  • Julia Fox Brings Adorable Son to Him Premiere — Plus More Star Sightings!
  • Home
  • Disclaimer
  • DMCA
  • Privacy Policy
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites. slotsfree  creator solana token

No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites.

New Self New Life