本文介紹了詳解在YII2框架中使用UEditor編輯器發(fā)布文章 ,分享給大家,具體如下:
創(chuàng)建文章數(shù)據(jù)表
文章數(shù)據(jù)表主要有4個(gè)字段
1.id 主鍵(int)
2.title 標(biāo)題(varchar)
3.content 內(nèi)容(text)
4.created_time 創(chuàng)建時(shí)間(int)
創(chuàng)建文章模型
創(chuàng)建文章模型,不要忘記設(shè)置驗(yàn)證規(guī)則和字段的名稱(chēng)
namespace backend\models;
class Article extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['title', 'content'], 'required'],
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => '名稱(chēng)',
'content' => '內(nèi)容',
];
}
}
創(chuàng)建控制器
創(chuàng)建文章控制器并編寫(xiě)發(fā)布文章功能
namespace backend\controllers;
use backend\models\Article;
class ArticleController extends \yii\web\Controller
{
/*
* 發(fā)布文章
*/
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 "*"
在控制器中定義處理上傳文件的動(dòng)作
在控制器中定義動(dòng)作,用于處理UEditor上傳的文件。
可以配置域名,上傳路徑,上傳文件命名格式等等
public function actions()
{
return [
'upload' => [
'class' => 'kucha\ueditor\UEditorAction',
'config' => [
"imageUrlPrefix" => "",//圖片訪問(wèn)路徑前綴
"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' => [
//編輯區(qū)域大小
'initialFrameHeight' => '200',
//設(shè)置語(yǔ)言
'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();
最終頁(yè)面效果

以下是發(fā)布文章功能編寫(xiě)完成后的效果,是不是很炫?希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- yii2實(shí)現(xiàn)Ueditor百度編輯器的示例代碼