Magento 2 Training : Unit 7 – Lesson C

Why create a Helper ?
Helper can be called everywhere you want if you inject it on the wanted class.
You can have “generic” method in order to avoid duplicate code.

Do you remember the last configuration we created ?
We added a constant string on the file app/code/Maxime/Jobs/Block/Department/View.php.
But, if you want to call the configuration on another class, you will have to instanciate this constant too.
So we will put it on a helper.

Helper creation

You can create the file :
app/code/Maxime/Jobs/Helper/Data.php

With :

<?php

namespace Maxime\Jobs\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    const LIST_JOBS_ENABLED = 'jobs/department/view_list';

    /**
     * Return if display list is enabled on department view
     * @return bool
     */
    public function getListJobEnabled() {
        return $this->scopeConfig->getValue(
            self::LIST_JOBS_ENABLED,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
}

It’s a little class with the constant which contains the XML path of the configuration. And a method to retrive the value of the config. If the path changes, you will have to change it only on this file.

So we have to update our block class.

Call an Halper with Magento 2

Reopen the file :
app/code/Maxime/Jobs/Block/Department/View.php

And replace it with this content :

<?php
namespace Maxime\Jobs\Block\Department;
class View extends \Magento\Framework\View\Element\Template
{
    protected $_jobCollection = null;

    protected $_department;

    protected $_job;

    protected $_helper;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Maxime\Jobs\Model\Department $department
     * @param \Maxime\Jobs\Model\Job $job
     * @param \Maxime\Jobs\Helper\Data $helper
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Maxime\Jobs\Model\Department $department,
        \Maxime\Jobs\Model\Job $job,
        \Maxime\Jobs\Helper\Data $helper,
        array $data = []
    ) {
        $this->_department = $department;

        $this->_job = $job;

        $this->_helper = $helper;

        parent::__construct(
            $context,
            $data
        );
    }

    /**
     * @return $this
     */
    protected function _prepareLayout()
    {
        parent::_prepareLayout();

        // Get department
        $department = $this->getLoadedDepartment();

        // Title is department's name
        $title = $department->getName();
        $description = __('Look at the jobs we have got for you');
        $keywords = __('job,hiring');

        $this->getLayout()->createBlock('Magento\Catalog\Block\Breadcrumbs');

        if ($breadcrumbsBlock = $this->getLayout()->getBlock('breadcrumbs')) {
            $breadcrumbsBlock->addCrumb(
                'jobs',
                [
                    'label' => __('We are hiring'),
                    'title' => __('We are hiring'),
                    'link' => $this->getListJobUrl() // No link for the last element
                ]
            );
            $breadcrumbsBlock->addCrumb(
                'job',
                [
                    'label' => $title,
                    'title' => $title,
                    'link' => false // No link for the last element
                ]
            );
        }

        $this->pageConfig->getTitle()->set($title);
        $this->pageConfig->setDescription($description);
        $this->pageConfig->setKeywords($keywords);


        $pageMainTitle = $this->getLayout()->getBlock('page.main.title');
        if ($pageMainTitle) {
            $pageMainTitle->setPageTitle($title);
        }

        return $this;
    }

    protected function _getDepartment()
    {
        if (!$this->_department->getId()) {
            // our model is already set in the construct
            // but I put this method to load in case the model is not loaded
            $entityId = $this->_request->getParam('id');
            $this->_department = $this->_department->load($entityId);
        }
        return $this->_department;
    }

    public function getLoadedDepartment()
    {
        return $this->_getDepartment();
    }

    public function getListJobUrl(){
        return $this->getUrl('jobs/job');
    }

    protected function _getJobsCollection(){
        if($this->_jobCollection === null && $this->_department->getId()){
            $jobCollection = $this->_job->getCollection()
                ->addFieldToFilter('department_id', $this->_department->getId())
                ->addStatusFilter($this->_job, $this->_department);
            $this->_jobCollection = $jobCollection;
        }
        return $this->_jobCollection;
    }

    public function getLoadedJobsCollection()
    {
        return $this->_getJobsCollection();
    }

    public function getJobUrl($job){
        if(!$job->getId()){
            return '#';
        }

        return $this->getUrl('jobs/job/view', ['id' => $job->getId()]);
    }

    public function getConfigListJobs() {
        return $this->_helper->getListJobEnabled();
    }
}

– The LIST_JOBS_ENABLED constant doesn’t exist anymore
– We inject our helper on __construct method
– The getConfigListJobs method call the helper

On the front office, no change. The list display will always depends on the configuration value.

Continue training
Return to previous lesson
Create a Helper with Magento 2
Tagged on:

4 thoughts on “Create a Helper with Magento 2

  • 05/17/2016 at 05:20
    Permalink

    Hi Guy ! Tutorial is very good . However , where i can download all source of this module ? Please help me . Thanks !

    Reply
    • 05/17/2016 at 08:21
      Permalink

      You have to follow the training program.
      I will put the module on github soon

      Thank you for your comment 😉

      Reply
  • 09/26/2016 at 05:27
    Permalink

    Hey Max,

    It is one of the best tutorials to understand M2. Please let me know if there is any way to download that module!

    Thanks!

    Reply
  • 02/25/2017 at 14:58
    Permalink

    For a long time I was searching for a good tutorial. Your tutorial is awesome. Please post more…

    Brilliant….

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website.
Ok