Magento: Add/Edit Date Field in Admin Form

Let’s suppose that you have a custom Magento module named ‘YourModule’. You have a custom database table for the module. There is a date field in the table. Now, your requirement is that your module should be able to display and edit the date field from admin section.

This article shows how you can display and edit date field from admin form. A datepicker will be displayed beside the date field in admin form. So that, you can easily choose any desired date.

Here are the changes you need to do:-

1) Add date field in your module’s form

Add the following code in _prepareForm() function of app/code/local/YourNamespace/YourModule/Block/Adminhtml/Yourmodule/Edit/Tab/Form.php

Note:- Here the date field name is ‘purchase_date’.


  $fieldset->addField('purchase_date', 'date', array(
	  'label'     => Mage::helper('subscription')->__('Purchase Date'),                    
	  'name'      => 'purchase_date',
	  'image'     => $this->getSkinUrl('images/grid-cal.gif'),
	  'format'    => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT)
  ));

2) Save the date value into database

Now the date field with a datepicker is displayed in your admin form. To save the value into database, you need to add a line of code in saveAction() function of app/code/local/YourNamespace/YourModule/controllers/YourModuleController.php

Note:- You need to add the single line of code below. All other lines can be kept as usual. As you can see below, the _filterDates function will convert dates in array from localized to internal format.


if ($data = $this->getRequest()->getPost()) {	

// THIS IS THE CODE TO BE ADDED	
// START	
$data = $this->_filterDates($data, array('purchase_date', 'expiry_date'));
// END

$model = Mage::getModel('subscription/subscription');		
$model->setData($data)
      ->setId($this->getRequest()->getParam('id'));

Hope it helps. Thanks.