zoukankan      html  css  js  c++  java
  • yii2.0 控制器方法 视图表单 Form表单处理

    假设我们在ArticleController.php下面的actionForm方法中来处理提交的表单

    新建立一个 views/Article/article-form.php文件用来作为输入表单

    <?php
    use yiihelpersHtml;
    use yiiwidgetsActiveForm;
    ?>
    <?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文件用来显示表单处理成功后的结果

    <?php
    use yiihelpersHtml;
    ?>
    <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不能为空

    新建models/ArticleForm.php

    <?php
    
    namespace appmodels;
    
    use yiibaseModel;
    
    class ArticleForm extends Model
    {
        public $title;
        public $content;
    
        public function rules()
        {
            return [
                [['title', 'content'], 'required'],
                //['email', 'email'],
            ];
        }
    }

    最后在ArticleController.php中完成actionForm方法

    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即可测试

  • 相关阅读:
    GDUFE ACM-1087
    背包九讲
    OJ4TH|Inverse number:Reborn
    OJ4TH|Let's play a game
    GG第四次作业
    OpenCV(3)其他常用数据类型
    OpenCV学习(2)读取视频和摄像头
    OpenCV(1)读写图像
    GG第三次作业
    GG第二次作业
  • 原文地址:https://www.cnblogs.com/jiufen/p/5086162.html
Copyright © 2011-2022 走看看