How to use System Configuration and Helpers in Magento 2.

Written by Payal Patel

Apr 19, 2021

How to use System Configuration and Helpers in Magento 2.

Let’s discuss how to use System Configuration and Helpers in Magento 2. The system configuration and helpers are simplifying work with the Magento store. A helper is called from anywhere. A file system.xml is used to create configuration fields in Magento 2 System Configuration.

We discussed in previous tutorials how to create UI form and UI grid in Magento 2.

A system.xml file create in the app/code/Dolphin/Contact/etc/adminhtml folder.

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="dolphin" translate="label" sortOrder="1000">
            <label>dolphin</label>
        </tab>
        <section id="dolphin" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>MyModule</label>
            <tab>dolphin</tab>
            <resource>Dolphin_MyModule::configuration</resource>
            <group id="general" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>General</label>
                <field id="enabled" translate="label,comment,tooltip" sortOrder="1" type="select" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Enabled</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                    <config_path>dolphin_contact/general/enabled</config_path>
                    <comment>Helpful message about using this field.</comment>
                    <tooltip>Longer helpful message about using this field.</tooltip>
                </field>
                <field id="title" type="text" translate="label" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Title</label>
                    <validate>required-entry alphanumeric</validate>
                    <config_path>dolphin_contact/general/title</config_path>
                    <depends>
                        <field id="enabled">1</field>
                    </depends>
                </field>
                <field id="secret_key" type="obscure" translate="label" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Secret Key</label>
                    <validate>required-entry</validate>
                    <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
                    <config_path>dolphin_contact/general/secret_key</config_path>
                    <depends>
                        <field id="enabled">1</field>
                    </depends>
                </field>
                <field id="option" type="select" translate="label" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Option</label>
                    <source_model>Dolphin\MyModule\Model\Config\Source\Option</source_model>
                    <config_path>dolphin_contact/general/option</config_path>
                    <depends>
                        <field id="enabled">1</field>
                    </depends>
                </field>
            </group>
        </section>
    </system>
</config>

In this above code, you can see the section attributes showInDefault=”1″, showInWebsite=”1″ and showInStore=”1″. In this case the section will show in all scopes like as default, website and store.

The <tab> section and <tab>dolphin</tab> assign the section to the new tab in left sidebar by the reference tab id. Then the <resource>Dolphin_MyModule::configuration</resource> resource id defined will be in the acl.xml file.

The <group> section allows a newly filed grouping to the section. You can see the <source_model> attribute to the specified model Magento\Config\Model\Config\Source\Yesno supply the select value and it’s the boolean options in the system configuration. It also specified <config_path>dolphin_contact/general/enabled</config_path>. It’s defined the configuration path.

The <comment> and <tooltip> tags are used to display for any comment or tooltip for extra information. If you want the translated label for a different store then you can use the translate attribute of the enclosing filed tag as a comma-separated list translate=”label,comment,tooltip”. The <validate> tag is the use for the validation and it’s can be validated only with the alphanumeric values. The <depends> tag contains a <field> tag referencing the “enabled” field.

Now, you can see the <source_model>Dolphin\MyModule\Model\Config\Source\Option</source_model>. So, create a file Option.php in the app/code/Dolphin/MyModule/Model/Config/Source folder with the following code.

<?php

namespace Dolphin\MyModule\Model\Config\Source;

use Magento\Framework\Option\ArrayInterface;

class Option implements ArrayInterface
{
    public function toOptionArray()
    {
        return [
            ['value' => '0', 'label' => __('Option 0')],
            ['value' => '1', 'label' => __('Option 1')],
            ['value' => '2', 'label' => __('Option 2')],
        ];
    }
}

Now, create the ACL config file acl.xml in the app/code/Dolphin/MyModule/etc folder.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Magento_Backend::stores">
                    <resource id="Magento_Backend::stores_settings">
                        <resource id="Magento_Config::config">
                            <resource id="Dolphin_MyModule::configuration" title="Dolphin" />
                        </resource>
                    </resource>
                </resource>
            </resource>
        </resources>
    </acl>
</config>

In the above code, <resource id=”Dolphin_MyModule::dolphin” title=”Dolphin” /> which relations the resource id defined above in etc/adminhtml/system.xml (Dolphin_MyModule::configuration) to the Magento config ACL. This make display in System > User Roles > {User} > Role Resources.

Now, create the Default config file config.xml in the app/code/Dolphin/MyModule/etc folder.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <dolphin_contact>
            <general>
                <title>Dolphin</title>
            </general>
        </dolphin_contact>
    </default>
</config>

In this above code, you can see the config_path it’s can be defined in etc/adminhtml/system.xml file as like dolphin_contact/general/title.

Now, create the Helper file Data.php in the app/code/Dolphin/MyModule/Helper folder.

<?php

namespace Dolphin\MyModule\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Encryption\EncryptorInterface;

class Data extends AbstractHelper
{
    protected $encryptor;

    public function __construct(
        Context $context,
        EncryptorInterface $encryptor
    )
    {
        parent::__construct($context);
        $this->encryptor = $encryptor;
    }

    /*
     * @return bool
     */
    public function isEnabled($scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT)
    {
        return $this->scopeConfig->isSetFlag(
            'dolphin_contact/general/enabled',
            $scope
        );
    }

    /*
     * @return string
     */
    public function getTitle($scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT)
    {
        return $this->scopeConfig->getValue(
            'dolphin_contact/general/title',
            $scope
        );
    }

    /*
     * @return string
     */
    public function getSecretKey($scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT)
    {
        $secretKey = $this->scopeConfig->getValue(
            'dolphin_contact/general/secret_key',
            $scope
        );
        $secretKey = $this->encryptor->decrypt($secretKey);
        
        return $secretKey;
    }

    /*
     * @return string
     */
    public function getOption($scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT)
    {
        return $this->scopeConfig->getValue(
            'dolphin_contact/general/option',
            $scope
        );
    }
}

In the above code, you can see the Magento\Framework\App\Config\ScopeConfigInterface class defined for scope config value and retrieve a value from the core_config_data table.

Now, the Helper functions can use anywhere such as Block, Template, etc. We will use the Helper function call in the Block file with the following code.

So, create the Block file Index.php in the app/code/Dolphin/MyModule/Block folder.

<?php

namespace Dolphin\MyModule\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Dolphin\MyModule\Helper\Data;

class Index extends Template
{
    /**
     * @var Data
     */
    protected $helper;

    public function __construct(Context $context, Data $helper) {
        $this->helper = $helper;
        parent::__construct($context);
    }

    /**
     * @return bool
     */
    public function isEnabled()
    {
        return $this->helper->isEnabled();
    }
}

In the above code, you can see the isEnabled() function return value from the helper.

We hope our guide is very effective for you. If any questions, please feel free to leave a comment below.

Payal Patel

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP