How To Use Helper And Setting In Magento 2

I have introduced How To Get Items To Storefront In Magento 2 in the previous lesson. In this lesson, I will introduce you to How To Use Helper And Setting In Magento 2.

This lesson is very important, you will need to use it a lot. You should read the Magento 2 Extension Tutorial step by step to be able to understand this lesson.

Module File Structure

We updated our module file structure looks as follows:

helper and system file structure

How to use Helper

First, create Data.php with the following path:

<?php
namespace Magetop\Helloworld\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;

class Data extends AbstractHelper
{
    public function __construct(Context $context)
    {
        parent::__construct($context);
    }

    function checkDate($date = '')
    {
        $ok = false;
        if($date != '')
        {
            $day = date('w', strtotime($date));
            if($day == 0)
                $ok = true;
        }
        return $ok;
    }
}

Next, edit Index.php in the Controller.

<?php
namespace Magetop\Helloworld\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magetop\Helloworld\Model\ResourceModel\Posts\CollectionFactory;
use Magetop\Helloworld\Helper\Data;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $_resultPageFactory;
    protected $_postsFactory;
    protected $_dataHelper;

    public function __construct(
        Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        CollectionFactory $postsFactory,
        Data $dataHelper)
    {
        parent::__construct($context);
        $this->_resultPageFactory = $resultPageFactory;
        $this->_postsFactory = $postsFactory;
        $this->_dataHelper = $dataHelper;
    }

    public function execute()
    {
        echo "Get Data From magetop_blog table";
        $this->_postsFactory->create();
        $collection = $this->_postsFactory->create()
            ->addFieldToSelect(array('title', 'description', 'created_at', 'status'))
            ->addFieldToFilter('status', 1)
            ->setPageSize(10);
        echo '<pre>';
        print_r($collection->getData());
        echo '<pre>';
        echo "========== Check date, helper function ======== <br>";
        $date = '2020-04-01';
        if ($this->_dataHelper->checkDate($date)) {
            echo "Yes, {$date} is Sunday , I can go to your home";
        } else {
            echo "Yes, {$date} is not Sunday , I was to busy";
        }
    }
}

Clear cache and check it in <yourdomain>/helloworld/index/index

Get Data using Data Helper

How to use Setting

The setting is very important in an extension because it helps the admin can configure data for the extension.

Create file system.xml in Magetop/Helloworld/etc/adminhtml/system.xml.

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * system
 *
 * @copyright Copyright © 2020 Magetop. All rights reserved.
 * @author    [email protected]
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="magetop_helloworld" translate="label" sortOrder="1">
            <label>Magetop</label>
        </tab>
        <section id="blog" translate="label" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Magetop Helloworld</label>
            <tab>magetop_helloworld</tab>
            <resource>Magetop_Helloworld::system_config</resource>
            <group id="setting" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>General Settings</label>
                <field id="enable" translate="label" type="select" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Enable</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
                <field id="number_posts" translate="label comment" type="text" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Number Posts</label>
                    <comment>Number Posts</comment>
                    <validate>required-entry</validate>
                </field>
            </group>
        </section>
    </system>
</config>

You run two commands:

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f

Go to Magento Admin Panel > STORES > Configuration in Settings section.

Configuration in Magento Backend
Config Value In Magento Backend

You need to edit Data.php in Helper.

<?php
namespace Magetop\Helloworld\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\ScopeInterface;

class Data extends AbstractHelper
{
    public function __construct(Context $context)
    {
        parent::__construct($context);
    }

    function checkDate($date = '')
    {
        $ok = false;
        if($date != '')
        {
            $day = date('w', strtotime($date));
            if($day == 0)
                $ok = true;
        }
        return $ok;
    }
    /**
     * @param string $path
     * @return mixed
     */
    function getHelloSetting($path = '')
    {
        return $this->scopeConfig->getValue($path,ScopeInterface::SCOPE_STORE);
    }
}

And call the new function in Controller, you can edit the file.

Edit Index.php in the Controller.

<?php
namespace Magetop\Helloworld\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magetop\Helloworld\Model\ResourceModel\Posts\CollectionFactory;
use Magetop\Helloworld\Helper\Data;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $_resultPageFactory;
    protected $_postsFactory;
    protected $_dataHelper;

    public function __construct(
        Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        CollectionFactory $postsFactory,
        Data $dataHelper)
    {
        parent::__construct($context);
        $this->_resultPageFactory = $resultPageFactory;
        $this->_postsFactory = $postsFactory;
        $this->_dataHelper = $dataHelper;
    }

    public function execute()
    {
        echo "Get Data From magetop_blog table <br>";
        $numberPosts = $this->_dataHelper->getHelloSetting('blog/setting/number_posts');
        echo "Number Posts = {$numberPosts}";
        $this->_postsFactory->create();
        $collection = $this->_postsFactory->create()
            ->addFieldToSelect(array('title','description','created_at','status')) // fields to select
            ->addFieldToFilter('status',1) // filter status = 1
            ->setPageSize($numberPosts); // get 2 items
        echo '<pre>';
        print_r($collection->getData());
        echo '<pre>';
        echo "==========Check date, helper function ======== <br>";
        $date = '2020-04-01';
        if ($this->_dataHelper->checkDate($date)) {
            echo "Yes, {$date} is Sunday , I can go to your home";
        } else {
            echo "Yes, {$date} is not Sunday , I was to busy";
        }
    }
}

Then, you can see it in <yourdomain>/helloworld/index/index

Check it after config value in backend

I hope through this series you can create your own complete module. Good luck!

In addition to How To Use Helper And Setting In Magento 2, you can read the articles How To Use Event In Magento 2.

Follow us for the more helpful article!

We hope this is a useful series for you.

Thank you for reading!

4.5 4 votes
Article Rating

Aaron LX

Aaron is a passionate writer, crazy about shopping, eCommerce and trends. Besides his outstanding research skills and a positive mind, Aaron eagerly shares his experience with the readers.

Leave a Reply or put your Question here

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x