本文介绍了详解在 YII2 框架中使用 UEditor 编辑器发布文章 , 分享给大家, 具体如下:
创建文章数据表
文章数据表主要有 4 个字段
1.id 主键 (int)
2.title 标题 (varchar)
3.content 内容 (text)
4.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();
最终页面效果
来源: https://www.jb51.net/article/150022.htm