The beforeSave() function is executed immediately after the model data has been successfully verified, but immediately before the data is saved. This function should also return true if you want to continue the save operation.
This callback is especially convenient for any data processing logic that must occur before your data is saved. If your storage engine needs dates in a specific format, refer to it in $ this-> data and change it.
The following is an example of how beforeSave can be used to convert dates. The code in the example is used for the indented application in the YYYY-MM-DD format in the database and is displayed as DD-MM-YYYY in the application. Of course, this can be easily changed. Use the code below in the appropriate model.
public function beforeSave($options = array()) { 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; } public function dateFormatBeforeSave($dateString) { return date('Ym-d', strtotime($dateString)); }
Make sure beforeSave () returns true, or your save will fail.
source share