October/Winter CMS 在Model使用beforeSave方法做数据预处理
今天使用系统内置的taglist
字段来实现tag标签功能,因为数据表中存在slug
的必填项导致数据录入的时候它会提示错误,这时候需要在Model中使用beforeSave
方法来做数据预处理
public function beforeSave() { if(!$this->slug){ $slugString = $this->title; if(!preg_match("/[a-z]/i", $slugString)){ $slugString = urlencode($slugString); //中文转码 } $this->slug = str_slug($slugString); } }
其中使用urlencode
是将把中文字符转码。
Model的事件(Events)
Event | Description |
---|---|
beforeCreate | before the model is saved, when first created. |
afterCreate | after the model is saved, when first created. |
beforeSave | before the model is saved, either created or updated. |
afterSave | after the model is saved, either created or updated. |
beforeValidate | before the supplied model data is validated. |
afterValidate | after the supplied model data has been validated. |
beforeUpdate | before an existing model is saved. |
afterUpdate | after an existing model is saved. |
beforeDelete | before an existing model is deleted. |
afterDelete | after an existing model is deleted. |
beforeRestore | before a soft-deleted model is restored. |
afterRestore | after a soft-deleted model has been restored. |
beforeFetch | before an existing model is populated. |
afterFetch | after an existing model has been populated. |
更多Model内置的方法可参考:https://docs.octobercms.com/2.x/database/model.html#events