详解在YII2框架中使用UEditor编辑器发布文章

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了详解在YII2框架中使用UEditor编辑器发布文章脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

本文介绍了详解在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();

最终页面效果

以下是发布文章功能编写完成后的效果,是不是很炫?希望对大家的学习有所帮助,也希望大家多多支持脚本宝典。

脚本宝典总结

以上是脚本宝典为你收集整理的详解在YII2框架中使用UEditor编辑器发布文章全部内容,希望文章能够帮你解决详解在YII2框架中使用UEditor编辑器发布文章所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:YII2