System.xml Configuration

如果模块需要管理员设置某些选项,就需要通过 system.xml 配置文件来创建和保存配置字段。那么我们怎么创建和使用 system.xml 呢?

第一步:创建 system.xml

请在 Magento 2 后台进入 Stores -> Settings -> Configuration
Magento 2 的系统配置页面被分成了几个部分:Tabs, Sections, Groups, Fields 。

Magento 2 system configuration page is divided logically in few parts: Tabs, Sections, Groups, Fields

以之前的 ThankIT_HelloWorld 模块为基础,下面我们创建一个配置页面,tab 是 ThankIT (for our vendor),section 是 Hello World (for our module),group 组包含一些简单的字段。

File: app/code/ThankIT/HelloWorld/etc/adminhtml/system.xml

<?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="mageplaza" translate="label" sortOrder="10">
            <label>Mageplaza</label>
        </tab>
        <section id="helloworld" translate="label" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1">
            <class>separator-top</class>
            <label>Hello World</label>
            <tab>mageplaza</tab>
            <resource>Mageplaza_HelloWorld::hello_configuration</resource>
            <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
                <label>General Configuration</label>
                <field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
                    <label>Module Enable</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
                <field id="display_text" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
                    <label>Display Text</label>
                    <comment>This text will display on the frontend.</comment>
                </field>
            </group>
        </section>
    </system>
</config>

以下是关于 system.xml 中一些元素的介绍。

  • The Tab element may have many sections and some main attributes and child:
    • Id attribute is the identify for this tab
    • sortOrder attribute will define the position of this tab.
    • Translate attribute let Magento know which title need to translate
    • Label element child is the text which will show as tab title.
  • The Section element will have id, sortOrder, translate attributes like the Tab element. Some other attributes (showInDefault, showInWebsite, showInStore) will decide this element will be show on each scope or not. You can change the scope here
    change system configuration scope

The section may have many group and some other child elements:

  • Class: this value will be added as class for this element. You should use it if you want to make-up this element.
  • Label: the text title of this element
  • Tab: this’s a tab id. This tab element will let Magento know the tab which this section is belong to. This section will be placed under that tab
  • Resource: defined the ACL rule which the admin user must have in order to access this configuration.
  • Group: This element may have many field and some attributes which is same as Sections.
  • Fields: is the main path of this page. It will save the data which we want to setting. In this element, we focus on the type attribute. It will define how the element is when display. It can be: text, select, file… In this example we create 2 fields with type select and text. With each type we will define the child element for the field to make it work as we want.

第二步:设置默认值

我么可以通过 config.xml 来给 system.xml 中的字段设置默认值。

File: app/code/ThankIT/HelloWorld/etc/config.xml

<?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>
        <helloworld>
            <general>
                <enable>1</enable>
                <display_text>Hello World</display_text>
            </general>
        </helloworld>
    </default>
</config>

格式:

<default>
    <section_id>
        <group_id>
            <field_id>{value}</field_id>
        </group_id>
    </section_id>
</default>

第三步:刷新缓存

刷新缓存后,你就可以看到结果了:
ThankIT HelloWorld Configuration page

第四步:获得配置值

system.xml 中,我们加了两个字段,他们的 path 是:
helloworld/general/enable
helloworld/general/display_text

然后,我们改一下配置,保存后,刷新缓存。我们查看 core_config_data 这张数据库表,就会看到我们保存的配置值了(只创建了 config.xml 并不会在该表插入记录,后台点击保存后才会在表中插入记录)。

core_config_data 中的记录值

万变不离其宗,获取配置值,是通过 \Magento\Framework\App\Config\ScopeConfigInterface 来实现的。

通过查 di.xml 可以发现
<preference for="Magento\Framework\App\Config\ScopeConfigInterface" type="Magento\Framework\App\Config" />
所以实际注入的是 Magento\Framework\App\Config

标准用法

在构造函数中注入 \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig 并设置 $this->scopeConfig = $scopeConfig;

我们就可以通过

$this->scopeConfig->getValue('helloworld/general/enable', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);

来取得 helloworld/general/enable 的设置值。

通过 helper 来取得配置值

File: ThankIT/HelloWorld/Helper/Data.php

<?php
namespace ThankIT\HelloWorld\Helper;

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

class Data extends AbstractHelper
{

    const XML_PATH_HELLOWORLD = 'helloworld/general/';

    public function __construct(Context $context)
    {
        parent::__construct($context);
    }

    public function getConfigValue($field, $storeId = null)
    {
        return $this->scopeConfig->getValue(
            $field, ScopeInterface::SCOPE_STORE, $storeId
        );
    }

    public function getGeneralConfig($code, $storeId = null)
    {
        return $this->getConfigValue(self::XML_PATH_HELLOWORLD . $code, $storeId);
    }

}

File: app\code\ThankIT\HelloWorld\view\frontend\templates\index\index.phtml

<hr>
<h3>get configuration value by helper file</h3>
<?php
$helper = $this->helper('ThankIT\HelloWorld\Helper\Data');
echo $helper->getConfigValue('helloworld/general/display_text');
echo '<br/>';
echo $helper->getGeneralConfig('display_text');

结果:
get-configuration-value-by-helper-file


关于 helper
Helpers are classes that can be used anywhere we want,we can use them in controllers,views,modeles and even in other helpers. Helpers are usually created to provide methods for a common functionality. 它一般位于 /Helper 目录下,常用的文件名是 Data.php
它继承自 Magento\Framework\App\Helper\AbstractHelper

因为他的父类已经注入了\Magento\Framework\App\Config\ScopeConfigInterface 所以我们可以在 helper 中使用 $this->scopeConfig->getValue() 来获得配置值。

在 block 中我们可以通过 $this->helper('{Vendor}\{Module}\Helper\Data'); 来获得 helper 。注意,此处一定是右斜杠。path 是左斜杠。

参考文档

Magento 2 How to Create System.xml Configuration

发表评论

电子邮件地址不会被公开。 必填项已用*标注