3.7.7.4 beforeSave
beforeSave()
Place any pre-save logic in this function. This function executes immediately after model data has been successfully validated, but just before the data is saved. This function should also return true if you want the save operation to continue.
This callback is especially handy for any data-massaging logic that needs to happen before your data is stored. If your storage engine needs dates in a specific format, access it at $this->data and modify it.
Below is an example of how beforeSave can be used for date conversion. The code in the example is used for an application with a begindate formatted like YYYY-MM-DD in the database and is displayed like DD-MM-YYYY in the application. Of course this can be changed very easily. Use the code below in the appropriate model.
function beforeSave() {
if (!empty($this->data['Event']['begindate']) && !empty($this->data['Event']['enddate'])) {
$this->data['Event']['begindate'] = $this->dateFormatBeforeSave($this->data['Event']['begindate']);
$this->data['Event']['enddate'] = $this->dateFormatBeforeSave($this->data['Event']['enddate']);
}
return true;
}
function dateFormatBeforeSave($dateString) {
return date('Y-m-d', strtotime($dateString)); // Direction is from
}
function beforeSave() {if (!empty($this->data['Event']['begindate']) && !empty($this->data['Event']['enddate'])) {$this->data['Event']['begindate'] = $this->dateFormatBeforeSave($this->data['Event']['begindate']);$this->data['Event']['enddate'] = $this->dateFormatBeforeSave($this->data['Event']['enddate']);}return true;}function dateFormatBeforeSave($dateString) {return date('Y-m-d', strtotime($dateString)); // Direction is from}
Be sure that beforeSave() returns true, or your save is going to fail.
