yii2.0 控制器方法 視圖表單 Form表單處理

假設咱們在ArticleController.php下面的actionForm方法中來處理提交的表單php

 

新創建一個 views/Article/article-form.php文件用來做爲輸入表單app

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'title') ?>

    <?= $form->field($model, 'content') ?>

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

<?php ActiveForm::end(); ?>

 

新創建一個 views/Article/article-confirm.php文件用來顯示錶單處理成功後的結果yii

<?php
use yii\helpers\Html;
?>
<p>You have entered the following information:</p>

<ul>
    <li><label>Name</label>: <?= Html::encode($model->title) ?></li>
    <li><label>Email</label>: <?= Html::encode($model->content) ?></li>
</ul>

 

需求:提交過來的數據須要驗證--title、content不能爲空post

新建models/ArticleForm.php測試

<?php

namespace app\models;

use yii\base\Model;

class ArticleForm extends Model
{
    public $title;
    public $content;

    public function rules()
    {
        return [
            [['title', 'content'], 'required'],
            //['email', 'email'],
        ];
    }
}

 

最後在ArticleController.php中完成actionForm方法ui

public function actionForm()
    {
        $model = new ArticleForm;
        if ($model->load(Yii::$app->request->post()) && $model->validate())
        {
            // 驗證 $model 收到的數據
            // 作些有意義的事 ...
            return $this->render('article-confirm', ['model' => $model]);
        }
        else
        {
            // 不管是初始化顯示仍是數據驗證錯誤
            return $this->render('article-form', ['model' => $model]);
        }

 

訪問http://www.basic.com/index.php?r=article/form便可測試this

相關文章
相關標籤/搜索