Magento how to add a date picker to system configuration

Hi Friends

How to add a date field with its date picker in the System > Configuration area
It's simple :)

Opne your system.xml
Path: app/code/[local, community]/Namespace/Module/etc/

And add this code

Code:
<?xml version="1.0" encoding="UTF-8"?>
<config>
....
    <fields>
    ...
        <!--Date picker code start-->
        <startdate translate="label">
            <label>Start Date</label>
            <frontend_type>text</frontend_type>
            <frontend_model>modulename/adminhtml_system_config_date</frontend_model> <!--Call a module specific renderer model-->
            <sort_order>1</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <validate>required-entry</validate> <!--Optional-->
            <show_in_store>1</show_in_store>
        </startdate>
        <!--Date picker code end-->
    </fields>
...
</config>

Now create a new file in Block folder
Path: app/code/[local, community]/Namespace/Module/Block/Adminhtml/System/Config/Date

with the content code below:
<?php
class Namespace_Module_Block_Adminhtml_System_Config_Date extends Mage_Adminhtml_Block_System_Config_Form_Field
{
    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
    {
        $date = new Varien_Data_Form_Element_Date;
        //$format = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM);
        //$format = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_FULL);
        //$format = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_LONG);
        //$format = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
        // Other set custom type
        $format = ('yyyy-MM-dd');

        $data = array(
            'name'      => $element->getName(),
            'html_id'   => $element->getId(),
            'image'     => $this->getSkinUrl('images/grid-cal.gif'),
        );
        $date->setData($data);
        $date->setValue($element->getValue(), $format);
        //$date->setFormat(Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT));
        // Other set custom type
        $date->setFormat('yyyy-MM-dd');
        $date->setClass($element->getFieldConfig()->validate->asArray());
        $date->setForm($element->getForm());

        return $date->getElementHtml();
    }
}

Now clear cache and relogin in admin and check your configuration section :)

Note: This data picker saved date will be not in GMT, but in the current admin locale timezone.

0 comments: