在YII2框架中使用UEditor編輯器發布文章
創建文章數據表
文章數據表主要有4個字段
- id 主鍵(int)
- title 標題(varchar)
- content 內容(text)
- created_time 創建時間(int)
創建文章模型
創建文章模型,不要忘記設置驗證規則和字段的名稱
namespace backend\models; class Article extends \yii\db\ActiveRecord {
public function rules()
{
return [
[['title', 'content'], 'required'],
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => '名稱',
'content' => '內容',
];
}
}
創建控制器
創建文章控制器並編寫發布文章功能
namespace backend\controllers; use backend\models\Article; class ArticleController extends \yii\web\Controller { /* * 發布文章 */ public function actionAdd() { $article = new Article(); if($article->load(\Yii::$app->request->post()) && $article->validate()){
$article->created_time = time(); $article->save(); \Yii::$app->session->setFlash('success','文章添加成功'); return $this->refresh(); } return $this->render('add',['article'=>$article]); }
}
安裝UEditor小部件
使用composer命令安裝
composer require kucha/ueditor "*"
在控制器中定義處理上傳文件的動作
在控制器中定義動作,用於處理UEditor上傳的文件。
可以配置域名,上傳路徑,上傳文件命名格式等等
public function actions() { return [ 'upload' => [ 'class' => 'kucha\ueditor\UEditorAction', 'config' => [ "imageUrlPrefix" => "",//圖片訪問路徑前綴 "imagePathFormat" => "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}" //上傳保存路徑 "imageRoot" => Yii::getAlias("@webroot"), ], ] ]; }
在視圖中顯示UEditor編輯器
在視圖表單中使用如下代碼顯示UEditor編輯器
$form = \yii\bootstrap\ActiveForm::begin(); echo $form->field($article,'title'); echo $form->field($article,'content')->widget('kucha\ueditor\UEditor',[ 'clientOptions' => [ //編輯區域大小 'initialFrameHeight' => '200', //設置語言 'lang' =>'en', //中文為 zh-cn //定制菜單 'toolbars' => [ [ 'fullscreen', 'source', 'undo', 'redo', '|', 'fontsize', 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', '|', 'lineheight', '|', 'indent', '|' ], ] ]); echo \yii\bootstrap\Html::submitButton('提交',['class'=>'btn btn-info']); \yii\bootstrap\ActiveForm::end();
最終頁面效果
以下是發布文章功能編寫完成后的效果,是不是很炫?