Menu Close
    Searching for an experienced Magento 2 Development Company ?

    Validate system.xml fields data when saving the configuration

    Hello Friends!

    In this blog, we will learn how we can validate store configuration fields information when saving the configurations.
    For example, we have to display the product information on a page and we want to display the product attributes in customized sort orders. So, we will configure these sorts of orders from the store configuration section. And we want to validate the sort order number must not be repeated.
    So, to validate this scenario, we can create a plugin to validate the sort order input fields values.

    To do this, please follow the below steps:

    1. Create system.xml file inside the app/code/Vendor/CustomModule/etc/adminhtml/ directory.

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../Config/etc/system_file.xsd">
        <system>
            <tab id="vendorname" translate="label" sortOrder="10">
                <label>VendorName</label>
            </tab>
            <section id="custommodule" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Custom Module Configuration</label>
                <tab>vendorname</tab>
                <resource>Vendor_CustomModule::config_blogs</resource>
                <group id="general" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Display Product Attributes Sort Order Settings</label>
                    <field id="name_sort_order" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        <label>Sort Order for ProductName</label>
                        <validate>required-entry</validate>
                    </field>
                    <field id="price_sort_order" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        <label>Sort Order for Price</label>
                        <validate>required-entry</validate>
                    </field>
                    <field id="sku_sort_order" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        <label>Sort Order for SKU</label>
                        <validate>required-entry</validate>
                    </field>
                    <field id="customattribute_sort_order" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                        <label>Sort Order for Custom Attributes</label>
                        <validate>required-entry</validate>
                    </field>
                </group>
            </section>
        </system>
    </config>

    2. Declare the plugin in di.xml file inside the app/code/Vendor/CustomModule/etc/adminhtml/ directory.

    <?xml version="1.0"?>
    
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <type name="Magento\Config\Model\Config">
            <plugin name="admin_system_config_save_plugin" type="Vendor\CustomModule\Plugin\Config\Model\ConfigPlugin" sortOrder="1"/>
        </type>
    </config>

    3. Create ConfigPlugin.php file to define the plugin inside the app/code/Vendor/CustomModule/Plugin/Config/Model/ directory.

    <?php
    /**
     * Vendor Desc.
     *
     * @category  Vendor
     * @package   Vendor_CustomModule
     * @author    Vendor
     * @copyright Copyright (c) Vendor (https://example.com)
     * @license   https://example.com/license.html
     */
    namespace Vendor\CustomModule\Plugin\Config\Model;
    
    class ConfigPlugin
    {
        /**
         * @var \Magento\Framework\App\RequestInterface
         */
        protected $request;
    
        /**
         * @var array
         */
        private $sortOrderArray = [];
       
        /**
         * Construct.
         *
         * @param \Magento\Framework\App\RequestInterface $request
         */
        public function __construct(
            \Magento\Framework\App\RequestInterface $request
        ) {
            $this->request = $request;
        }
    
        /**
         * added validation for sort order around save action
         *
         * @param \Magento\Config\Model\Config $subject
         * @param \Closure $proceed
         *
         * @return void
         */
        public function aroundSave(
            \Magento\Config\Model\Config $subject,
            \Closure $proceed
        ) {
            $requestData   = $this->request->getParams();
            $configSection = $requestData["section"] ?? "";
    
            if ($configSection == "custommodule") {
                $groups         = $requestData["groups"] ?? [];
                $this->sortOrderArray = [];
                if (!empty($groups)) {
                    $nameSortOrder  = $groups["general"]["fields"]["name_sort_order"]["value"]  ?? "";
                    $this->pushSortOrderInArray($nameSortOrder);
    
                    $priceSortOrder = $groups["general"]["fields"]["price_sort_order"]["value"] ?? "";
                    $this->pushSortOrderInArray($priceSortOrder);
    
                    $dateSortOrder  = $groups["general"]["fields"]["sku_sort_order"]["value"]  ?? "";
                    $this->pushSortOrderInArray($dateSortOrder);
    
                    $attrSortOrder = $groups["general"]["fields"]["customattribute_sort_order"]["value"]  ?? "";
                    $this->pushSortOrderInArray($attrSortOrder);
    
                    $prevCount  = count($this->sortOrderArray);
                    $afterCount = count(array_unique($this->sortOrderArray));
                    
                    if ($prevCount != $afterCount) {
                        throw new \Magento\Framework\Exception\AlreadyExistsException(
                            __('Attribute sort order must be unique.')
                        );
                    }
                }
            }
            
            return $proceed();
        }
    
        /**
         * push sort order in array
         *
         * @param int $value
         *
         * @return void
         */
        private function pushSortOrderInArray($value)
        {
            if ($value != "") {
                $this->sortOrderArray[] = $value;
            }
        }
    }

    4. After executing the setup:di: compile command from CLI and flushing the cache, the result will be as in the below images:

    config1
    config2
    config3

    Hope this will be helpful. Thanks 🙂

    . . .
    Discuss on Helpdesk

    Leave a Comment

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


    Be the first to comment.

    Back to Top