YII2.0使用ActiveForm表单

Controller控制器层代码

<?php

namespace frontend\controllers;

use frontend\models\UserForm;
class UserController extends \yii\web\Controller
{
    public function actionIndex()
    {
		$model = new UserForm;
		if ($model->load(\Yii::$app->request->post()) && $model->validate())
		{
			echo "通过";
		}
		
        return $this->render('index',[
			"model" => $model,	
		]);
    }

}

VIEWS视图层代码

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

?>

<h1>YII2.0使用ActiveForm</h1>

<?php $form = ActiveForm::begin([
    'action' => ['log/login'], //提交地址(*可省略*)
    'method'=>'post',	//提交方法(*可省略默认POST*)
	'id' => 'login-form', //设置ID属性
	'options' => [
			'class' => 'form-horizontal', //设置class属性
			'enctype' => 'multipart/form-data' //文件上传时添加该编码
	],
	'fieldConfig' => [
			'template' => '<div class="form-group"><center><label class="col-md-2 control-label" for="type-name-field">{label}</label></center><div class="col-md-8 controls">{input}{error}</div></div>'
	],  //设置模板的样式
]); ?>

	<!--文本框 (*验证长度可在这里写 maxlength 这样就不用再 model 里面写了 *)-->
	<?= $form->field($model, 'username',['template'=>'<div class="form-group"><div class="col-md-8 controls">{label}{input}{error}</div></div>'])->textInput(['maxlength' => 20,"style"=>"width:200px; height:30px;"]) ?>
	
	<!--密码框 (*不使用他的lable只需要用false把他禁止, 然后你可以自己写*)-->
	<h4>密码</h4><?= $form->field($model, 'pwd')->label(false)->passwordInput(['maxlength' => 20,"style"=>"width:200px; height:30px;","placeholder"=>"请输入您的密码"]) ?>

	<?= $form->field($model, 're_pwd')->passwordInput(['maxlength' => 20,"style"=>"width:200px; height:30px;","placeholder"=>"请输入您的密码"]) ?>
	
	<!--单选按钮(*设置默认选中*)-->
	<?php $model->sex=1; echo $form->field($model, 'sex')->radioList(['1'=>'男','0'=>'女']) ?>

	<!--验证邮箱-->
	<?= $form->field($model, 'email')->textInput() ?>
	
	<!--下拉框的默认选中使用 prompt 设置 -->
	<?= $form->field($model, 'school')->dropDownList(['1'=>'大学','2'=>'高中','3'=>'初中'], ['prompt'=>'请选择','style'=>'width:120px']) ?>
	
	<!--文件上传-->
	<?= $form->field($model, 'photo')->fileInput() ?>
	
	<!--复选框 -->
	<?= $form->field($model, 'hobby')->checkboxList(['0'=>'篮球','1'=>'足球','2'=>'羽毛球','3'=>'乒乓球']) ?>
	
	<!--文本域-->
	<?= $form->field($model, 'remark')->textarea(['rows'=>3]) ?>
	
	<!--隐藏域-->
	<?= $form->field($model, 'userid')->hiddenInput(['value'=>3])->label(false); ?>

	<?= Html::submitButton('提交', ['class'=>'btn btn-primary','name' =>'submit-button']) ?>
	   
	<?= Html::resetButton('重置', ['class'=>'btn btn-primary','name' =>'submit-button']) ?>

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

MODELS层表单验证

<?php

namespace frontend\models;

use Yii;
class UserForm extends \yii\db\ActiveRecord
{
	/**
	*@param参数
	*/
	public $username;
	public $pwd;
	public $re_pwd;
	public $email;
	public $bobby;
	public $remark;
	public $photo;
	public $school;
	public $info;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
			//验证不能为空
			[['username', 'pwd', 'email', 'hobby'], 'required' ,"message"=>"{attribute}不能为空"], 
			
			//验证用户唯一
			['username', 'unique', 'targetClass' => '\frontend\models\User', 'message' => '用户名已存在.'],

			//验证密码不一致
			['re_pwd', 'compare', 'compareAttribute' => 'pwd', 'message' => '两次密码不一致'],

			//验证字符串长度
            [['username'],"string", "max"=>"10", "min"=>"5", "tooLong"=>"{attribute}不能大于10个字符", "tooShort"=>"{attribute}不能小于5个字符"],

			//采用rules 规则验证
			['email', 'email',"message"=>"{attribute}格式错误"], 
			//方法2: 
			//正则验证  ['tel','match','pattern'=>'/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})?$/','message'=>"{attribute}邮箱输入有误."],

            [['remark'], 'string', 'max' => 200],
			
			
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'user_id' => '自增ID',
            'username' => '用户名',
            'pwd' => '密码',
			 're_pwd' => '请再次输入密码',
            'sex' => '性别',
            'email' => '邮箱',
            'hobby' => '爱好',
			'school' => '学校',
            'remark' => '备注信息',
        ];
    }
}

相关的学习网站推荐

http://www.phpxs.com/post/2327

http://www.phpxs.com/post/3441

http://www.phpxs.com/post/4378

http://www.phpxs.com/post/3443

http://www.kuitao8.com/20140425/2334.shtml

你可能感兴趣的:(YII2.0使用ActiveForm表单)