In my configuration, I have two field number x and number y. I want to add a condition in which the number y must be less than the number x. How can I write this condition in a configuration file (system.xml)
1 Answer
You can use Js mixin to add a custom validation rule for your system config field as described below
Step 1) Create file requirejs-config.js under /app/code/Company/MyModule/view/adminhtml/
File: /app/code/Company/MyModule/view/adminhtml/web/requirejs-config.js
var config = {
config: {
mixins: {
'mage/validation': {
'Pritam_HideInfo/js/validation-mixin': true
}
}
}
}
step 2) Create file validation-mixin.js under /app/code/Company/MyModule/view/adminhtml/web/js
File: /app/code/Company/MyModule/view/adminhtml/web/js/validation-mixin.js
define([
'jquery'
], function ($) {
"use strict";
return function () {
$.validator.addMethod(
'validate-minimumage',
function(value, element) {
var xElemHtmlId = "Your Cofig field ID for X";// Plesae find id from View Source of the page
var xval = $("#"+xElemHtmlId).val();
xval = parseInt(xval);
//console.log("x value="+xval);
//console.log("Y value="+value);
return (value >= xval ? false : true);
},
$.mage.__('Y must be less then number X')
);
}
});
step 3: You system.xml should have x and y fields
............. .............
<field id="myconfigx" translate="X" type="text" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
<label>X</label>
<validate>validate-number</validate>
</field>
<field id="myconfigy" translate="X" type="text" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Y</label>
<validate>validate-number validate-minimumage</validate>
</field>
............. .............
step 4: Remove static files using below commands
sudo rm -rf var/generation/* sudo rm -rf var/di/* sudo rm -rf var/view_preprocessing/* sudo rm -rf var/view_preprocessed/* sudo rm
-rf var/pub/static/* sudo rm -rf var/cache/* sudo rm -rf var/generated sudo rm -rf var/composer_home sudo rm -rf var/page_cache sudo rm -rf var/view_preprocessed sudo rm -rf pub/static/frontend/* sudo rm -rf pub/static/adminhtml/*