Home  >  Article  >  Backend Development  >  yii的ActiveForm表单工具怎么用

yii的ActiveForm表单工具怎么用

WBOY
WBOYOriginal
2016-06-06 20:32:451203browse

最近在用yii开发,他的表单验证功能也很强大,可是发现这个activeform表单工具用不来,谁能帮忙讲解下,谢谢!

回复内容:

最近在用yii开发,他的表单验证功能也很强大,可是发现这个activeform表单工具用不来,谁能帮忙讲解下,谢谢!

不知道题主有没有简单的应用场景。ㄟ( ▔, ▔ )ㄏ
我这里就举个 超超超简单·用户发表评论·的表单提交的例子:

正如@鸟语花香说的,ActiveForm 要和 Model/ActiveRecord 配合使用的。
所以 先要张表 像这样 ↓

<code>+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| username | varchar(20)  | NO   |     | NULL    |                |
| comment  | text         | NO   |     | NULL    |                |
| add_time | datetime     | YES  |     | NULL    |                |
| gender   | tinyint(3)   | YES  |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
</code>

有了表,那我们就建立model咯,这里我直接用gii脚手架生成了名为 Comments 的model。

表单里需要的信息:
1. 用户名(varchar类型数据)
2. 评论内容 (text类型数据)
3. 性别(int类型数据)

我想在你的控制器的action中,至少应该这么写:

<code>/*action*/
$model = new Comments(); //实例化 Comments model
return $this->render('msg',['model'=>$model]); //将 comments model 作为参数 推进我要的视图页面
</code>

render中的 「msg」就是对应的视图页面

那接下去看下msg视图:
在msg视图中,我们常用的方法和属性大都包含在了两个关键的类中,分别是 yii\helpers\Html 和 yii\bootstrap\ActiveForm,前者负责将一些常用的html标签方法化,方便统一。 后者就是我们的主角 ActiveForm。为了让我们接下去表单中的代码简洁益与阅读,我们就在视图头部加入引用:

<code><!--msg.php文件-->
<?php use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
</code>

普通表单我们用 <form>...</form> 作为开头和结尾,ActiveForm也一样,只不过换了个更加酷炫的方法:

<code><!--msg.php文件-->
 <?php $form = ActiveForm::begin([...]);?>
    ...
    ...
    ...
 <?php ActiveForm::end();?>   
</code>

ActiveForm就是这种结构啦!(≖ ‿ ≖)✧,begin中的省略号是我们要配置的参数,一会我们再把他替换掉,
先来看看表单要填写的条目:

<code><!--msg.php文件-->
= $form->field($model,'username')->textInput(); //用户名输入框 ?>
= $form->field($model,'comment')->textarea(); //评论内容输入框 ?>
= $form->field($model,'gender')->radioList(['1'=>'男','2'=>'女'])->label('性别'); //性别选择框 ?>
</code>

没错,只要一行。
一行一条目,因为field自动帮你打包了(1个默认label,1个默认input,1个默认error提示)。
你需要提供的参数也就是
1.我们从action推进来的 comments model。
2.model 中的属性(对应表中的字段)。
label从哪里读出来的?Comments model 中的 attributeLabels。
error显示的规则哪里来的?Comments model 中的 rules 规则验证。

<code>field($model,'xxx')
</code>

后面哪些紧跟的是啥?
就是那要选用的输入框类型。
ActiveForm 的 field() 方法,返回的是一个 根据你给定的 model和model属性 生成的
ActiveField对象 ,field()后紧跟的方法则是根据你的需求选择输入框的类型,还有一些自定义配置。
拿上面gender的栗子讲:
如果 只是这样写的话,则会返回给我一个默认的 textInput输入框,所以我加了 ->radioList(['1'=>'男','2'=>'女']) 把textInput改成了一个 radio单选框 ,radioList中的数组就是对应选项的值和标签。->label('性别'),我觉得我不想用 Comments model 中写好的属性翻译,所以我把label也重写了一下。

有了输入的条目,那接下来的就是提交的按钮咯:

<code><!--msg.php文件-->
= Html::submitButton('发表评论', ['class' => 'btn btn-primary', 'name' => 'submit-button']) ?>
</code>

第一个参数就是你要显示的button的文字,第二个数组同样是配置,增加了button的class和name。

接下来再回到ActiveForm::begin([...])方法,看下begin中的一般参数配置:

<code>[
    'id'=>'msg-form',
    'options' => ['class'=>'form-horizontal'],
    'enableAjaxValidation'=>false,
    'fieldConfig' => [
                'template' => "{label}\n<div class='\"col-lg-3\"'>{input}</div>\n<div class='\"col-lg-8\"'>{error}</div>",
                'labelOptions' => ['class' => 'col-lg-1 control-label'],
    ]
]
</code>

1.'id'=>'msg-form' 表单form 的id ,除了唯一标识的作用外,如果你开启了表单异步规则验证,这个也会作为$_POST[ajax]参数提交到action中。
2.'options' => ['class'=>'form-horizontal']给form 加的一些属性
3.'enableAjaxValidation'=>false这个就是「是否进行异步验证」的配置。其实它默认是false的,完全可以不用列出来,之所以这里列出是觉得有必要知道这个属性的存在,因为在复杂的表单中一般都是 设置为true。同时,在你的action中还要增加对于异步验证的方法。
4.'fieldConfig'对表单中 将要生成的 ActiveField对象 进行配置,上面讲的是在input条目中进行配置,而这里就是统一配置。
'template' => "{label}\n

{input}

\n

{error}

", 顾名思义,模板。 也就是让一个输入框套餐(label+input+error)按照我要求的样式显示出来。如果不设置,那yii会采用默认的模板 "{label}\n{input}\n{hint}\n{error}"(实在太难看(`・д・´) )。'labelOptions' => ['class' => 'col-lg-1 control-label'], 就是增加套餐中{label}的属性(以美化样式)。

下面是整个msg.php的样子:

<code><!-- msg.php -->
<?php use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>



<div class="container">
<!--    开始帅气的表单组件-->
    <?php $form = ActiveForm::begin([
            'id' => 'msg-form',
            'options' => ['class'=>'form-horizontal'], 
            'enableAjaxValidation'=>false,
            'fieldConfig' => [
                'template' => "{label}\n<div class='\"col-lg-3\"'>{input}</div>\n<div class='\"col-lg-8\"'>{error}</div>",
                'labelOptions' => ['class' => 'col-lg-1 control-label'],
            ]
    ]);
    ?>
<!--表单条目-->
    = $form->field($model,'username')->textInput(); ?>

    = $form->field($model,'comment')->textarea(); ?>

    = $form->field($model,'gender')->radioList(['1'=>'男','2'=>'女'])->label('性别'); ?>

<!--提交按钮-->
    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            = Html::submitButton('发表评论', ['class' => 'btn btn-primary', 'name' => 'submit-button']) ?>
        </div>
    </div>

<!--结束帅气的表单组件-->
    <?php ActiveForm::end();?>

</div>


</code>

到这里,如果点了提交后,post 的内容将会是这样的

<code>    [_csrf] => RHFOTmg1TUpwNX0sKQ0CEnQ/ES8uQyM9HhIcFhBxHnM1QhQELnR9BA==
    [Comments] => Array
        (
            [username] => cookedsteak
            [comment] => Here comes the comment !
            [gender] => 2
        )

    [ajax] => msg-form
    [submit-button] => undefined
</code>

之后就是在action中按照你自己的需求处理数据啦。


以上是个人对ActiveForm的理解,可能有些地方过于简单,只希望能帮到同是初学者的yiier(づ ̄ ³ ̄)づ

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn