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)

EventDescription
beforeCreatebefore the model is saved, when first created.
afterCreateafter the model is saved, when first created.
beforeSavebefore the model is saved, either created or updated.
afterSaveafter the model is saved, either created or updated.
beforeValidatebefore the supplied model data is validated.
afterValidateafter the supplied model data has been validated.
beforeUpdatebefore an existing model is saved.
afterUpdateafter an existing model is saved.
beforeDeletebefore an existing model is deleted.
afterDeleteafter an existing model is deleted.
beforeRestorebefore a soft-deleted model is restored.
afterRestoreafter a soft-deleted model has been restored.
beforeFetchbefore an existing model is populated.
afterFetchafter an existing model has been populated.

更多Model内置的方法可参考:https://docs.octobercms.com/2.x/database/model.html#events

Post Comment