How to Add Date Using Dynamic Field in system.xml File in Magento 2
Magento 2 CMS is a widely used platform to develop online stores. Owing to the flexibility of customization, the CMS is preferred to cater to modern business requirements.
Here, I’ve posted a similar solution that you can implement if your business requires to configure settings based on the calendar dates from the system configuration.
For example, you may want to restrict certain dates for delivery that are national holidays, or set exclusive offers for a certain period of time.
Such functionalities can be implemented easily with the programmatic solution to add date using dynamic field in system.xml in Magento 2 store.
Method to Add Date Using Dynamic Field in system.xml File in Magento 2:
- Create registration.php file at app\code\Vendor\Module directory
1234<?phpuse \Magento\Framework\Component\ComponentRegistrar;ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Vendor_Module', __DIR__); - Create module.xml file at app\code\Vendor\Module\etc directory
12345<?xml version="1.0"?><config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"><module name="Vendor_Module" setup_version="1.0.0"/></config> - Create system.xml file at app\code\Vendor\Module\etc\adminhtml\system.xml
1234567891011121314151617181920212223242526272829303132333435<?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="vendor" translate="label" class="dynamic_field" sortOrder="100"><label></label></tab><section id="deliverydate" translate="label" type="text" sortOrder="320" showInDefault="1" showInWebsite="1"showInStore="1"><label>Order Delivery Date</label><tab>vendor</tab><resource>Vendor_Module::module_configuration</resource><group id="general" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1"showInStore="1"><label>General</label><field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1"showInStore="1"><label>Enable</label><source_model>Magento\Config\Model\Config\Source\Enabledisable</source_model></field><field id="cutofftime" translate="cut off time" type="time" sortOrder="4" showInDefault="1" showInWebsite="1"showInStore="1"><label>Cut off Time</label><comment><![CDATA[If customers place order after this time the date when orders made will be counted as the following day.]]></comment></field><field id="dynamic_field_holidays" translate="label" sortOrder="4" showInDefault="1" showInWebsite="1" showInStore="1"><label>Holidays/Exclude Days/Blackout Days</label><backend_model>Vendor\Module\Block\Adminhtml\Config\Backend\ArraySerializedHolidays</backend_model><frontend_model>Vendor\Module\Block\Adminhtml\DynamicFieldHolidays</frontend_model></field></group></section></system></config> - Create ArraySerializedHolidays.php file at Vendor\Module\Block\Adminhtml\Config\Backend
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051<?phpnamespace Vendor\Module\Block\Adminhtml\Config\Backend;use Magento\Framework\App\Cache\TypeListInterface;use Magento\Framework\App\Config\ScopeConfigInterface;use Magento\Framework\App\Config\Value as ConfigValue;use Magento\Framework\Data\Collection\AbstractDb;use Magento\Framework\Model\Context;use Magento\Framework\Model\ResourceModel\AbstractResource;use Magento\Framework\Registry;use Magento\Framework\Serialize\SerializerInterface;class ArraySerializedHolidays extends ConfigValue{protected $serializer;public function __construct(SerializerInterface $serializer,Context $context,Registry $registry,ScopeConfigInterface $config,TypeListInterface $cacheTypeList,AbstractResource $resource = null,AbstractDb $resourceCollection = null,array $data = []) {$this->serializer = $serializer;parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);}public function beforeSave(){$value = $this->getValue();if (isset($value['__empty'])) {unset($value['__empty']);}$encodedValue = $this->serializer->serialize($value);$this->setValue($encodedValue);}protected function _afterLoad(){$value = $this->getValue();if ($value) {$decodedValue = $this->serializer->unserialize($value);$this->setValue($decodedValue);}}} - Create DynamicFieldHolidays.php file at Vendor\Module\Block\Adminhtml
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778<?phpnamespace Vendor\Module\Block\Adminhtml;use Magento\Backend\Block\Template\Context;use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;use Magento\Framework\DataObject;use Magento\Framework\Registry;class DynamicFieldHolidays extends AbstractFieldArray{private $holidaysRenderer;private $dateRenderer;public function __construct(Context $context,Registry $coreRegistry,array $data = []) {$this->_coreRegistry = $coreRegistry;parent::__construct($context, $data);}protected function _prepareToRender(){$this->addColumn('select_date',['label' => __('Date'),'id' => 'select_date','class' => 'daterecuring','style' => 'width:200px']);$this->addColumn('date_title',['label' => __('Content'),'class' => 'required-entry','style' => 'width:300px',]);$this->_addAfter = false;$this->_addButtonLabel = __('MoreAdd');}protected function _prepareArrayRow(DataObject $row): void{$options = [];$row->setData('option_extra_attrs', $options);}protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element){$html = parent::_getElementHtml($element);$script = '<script type="text/javascript">require(["jquery", "jquery/ui", "mage/calendar"], function (jq) {jq(function(){function bindDatePicker() {setTimeout(function() {jq(".daterecuring").datepicker( { dateFormat: "mm/dd/yy" } );}, 50);}bindDatePicker();jq("button.action-add").on("click", function(e) {bindDatePicker();});});});</script>';$html .= $script;return $html;}}
That’s it.
Any doubts in the above solution can be mentioned in the Comments section below. Also readHow to Implement Field Dependency from Different Groups in Magento 2 System.xml based on the selection of API providers.
I’d be glad to help you out.
Also, do share the solution with Magento Community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Add Custom CSS in Theme From Admin in Magento 2
How to Add Product Attribute to Sales Rules Conditions in Magento 2
Next