在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();

 

最終頁面效果

以下是發布文章功能編寫完成后的效果,是不是很炫?

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM