Question

I have built a grid and admin form for editing a custom table with two date fields: "date_start" and "date_end"

It is saving correctly and if I enter a date it will save the date as I enter it. however if I do not enter a date it will instead save the date as if it was the current date. I need it to save an empty date as either blank or 0000-00-00 00:00:00 as this is later used in a method where a blank or empty date means we are not filtering by date.

The functionality could be replicated by adding two booleans for each date that say if you are filtering by that date but I find that is not the preferred method to do this.

I am assuming it would have to be in the controllers save action in the following section

$postData = $this->_filterDates($postData, array('date_start', 'date_end'));

// date code goes here    

$shiprate_model->addData($postData);

But I am not sure what method would be needed.

The only other place I could think of is the table structure but they already have a default set

`date_end` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',

Solution

$date_start_null = false;
$date_end_null = false;

if(!$postData['date_start']) $date_start_null = true;
if(!$postData['date_end']) $date_end_null = true;

$postData = $this->_filterDates($postData, array('date_start', 'date_end'));

if($date_start_null) $postData['date_start'] = '0000-00-00 00:00:00';
if($date_end_null) $postData['date_end'] = '0000-00-00 00:00:00';

Was able to get it working using a mixture of the solutions bellow, thanks for the help

Was it helpful?

Solution

Try something like the following ... I am assuming the above is from your entity controller's saveAction(). So, if the field has also a html name="date_end", you could do a simple check and force-assign the values you need, if the field(s) are empty:

if(empty($postData['date_start'])) $postData['date_start'] = '0000-00-00 00:00:00';
if(empty($postData['date_end'])) $postData['date_end'] = '0000-00-00 00:00:00';

$postData = $this->_filterDates($postData, array('date_start', 'date_end'));

OTHER TIPS

I'd implement the _beforeSave() function of your Model implementation.

public function _beforeSave() {
    if(!$this->getDateEnd()) {
        $this->setDateEnd("0000-00-00 00:00:00");
    }
    return parent::_beforeSave();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top