本文作者:心月

YII2高级版框架搭建完整博客系统教程——文章创建功能实现

心月IT博客 03-13
YII2高级版框架搭建完整博客系统教程——文章创建功能实现摘要:前面做了那么多的准备工作,现在终于可以开始准备实现文章创建功能了。

1、打开文章控制器(PostsController)

在文章控制器中添加文章创建方法actionCreate。

#在文章控制器中添加actionCreate方法
/**
 * 文章创建
 */
public function actionCreate()
{
    $model = new PostsForm();

    return $this -> render('create',['model' => $model]);

}

然后在frontend/views/posts下创建create.php渲染页面

<?php

$this->title = '创建';
$this->params['breadcrumbs'][] = ['label' =>'文章','url'=>['posts/index']];  #面包屑 对于数据的封装
$this->params['breadcrumbs'][] = $this->title;

use yiibootstrapActiveForm;
use yiihelpersHtml;

?>
<div class="row">
    <div class="col-lg-9">
        <div class="panel-title box-title">
            <span>创建文章</span>
        </div>
        <div class="panel-body">
            <?php $form = ActiveForm::begin() ?>

            <?= $form->field($model,'title')->textinput(['maxlength'=>true]) ?>

            <?= $form->field($model,'cat_id')->textInput(['maxlength'=>true]) ?>

            <?= $form->field($model,'label_img')->textInput(['maxlength'=>true]) ?>

            <?= $form->field($model,'content')->textInput(['maxlength'=>true]) ?>

            <?= $form->field($model,'tags')->textInput(['maxlength'=>true]) ?>

            <div class="form-group">
                <?= Html::submitButton('发布',['class'=>'btn btn-success'])?>
            </div>

            <?php ActiveForm::end() ?>
        </div>
    </div>

    <div class="col-lg-3"></div>
</div>

创建文章页面效果图

创建文章效果图

    文章创建功能基本实现了,不过从截图中可以看出,这跟我们印象中的不太一样,确实,这里的创建文章功能确实太单调了,没关系,在后面的分享的教程中会逐步完善文章创建功能。

    如果你的创建文章下面的属性是英文,那是因为你的文章表单模型中没有attributeLabels方法,只需加上就可以了

//语言包映射
public function attributeLabels()
{
    return [
        'id' => Yii::t('common','id'),
        'title' => Yii::t('common', 'title'),
        'content' => Yii::t('common', 'content'),
        'label_img' => Yii::t('common', 'label_img'),
        'cat_id' => Yii::t('common', 'cat_id'),
        'tags' => Yii::t('common', 'tags'),
    ];
}

actionCreate 添加代码截图:

actionCreate添加文章方法

attributeLabels 添加代码截图:

语言包映射

文章版权及转载声明:

本文由 心月IT技术博客 博主整理于 03-13
若转载请注明原文及出处:https://www.xinyueseo.com/yii/177.html

分享到:
赞(
发表评论
快捷输入:

验证码

    评论列表 (有 0 条评论,人围观)参与讨论