------------------------------------------------------------------------------------------

表单页面

------------------------------------------------------------------------------------------

第一: 先使用一下类

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\validators\Volidator;
use yii\captcha\Captcha;

第二: Yii 框架自带的各种表单的写法

$form = ActiveForm::begin(['action'=>'index.php?r=form1/index','method'=>'post','options' => ['enctype' => 'multipart/form-data'] ]); ?>
    <?= $form->field($model, 'username',['enableAjaxValidation'=>true]) ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    <?= $form->field($model, 'okpassword')->passwordInput() ?>
    <?= $form->field($model, 'age') ?>
    <?= $form->field($model, 'sex')->radioList(['男' => '男', '女' => '女']); ?>
    <?= $form->field($model, 'hobby[]')->checkboxList(['游泳' => '游泳', '跑步' => '跑步', '音乐' => '音乐', '学习' => '学习']) ?>

    <?= $form->field($model, 'phone',['enableAjaxValidation'=>true]) ?>
    <?= $form->field($model, 'captcha')->widget(Captcha::className(), ['captchaAction'=>'form1/captcha',
    'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
    <?= $form->field($model, 'email',['enableAjaxValidation'=>true]) ?>
    <?= $form->field($model, 'image')->fileInput() ?>
    
    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
        </div>
    </div>
<?php ActiveForm::end() ?>

----------------------------------------------------------------------------------------------

模型层

----------------------------------------------------------------------------------------------

先使用一下文件上传类  use yii\web\UploadedFile;

    public $captcha;

    /**
     * @验证规则
     */
    public function rules()
    {
        return [
            [['age'], 'integer'],
            [['image'], 'file','skipOnEmpty'=>false, 'extensions'=>'png,jpg,gif'],

            //验证不为空
            ['username', 'required', 'message' => '{attribute}不能为空'],
            ['password', 'required', 'message' => '{attribute}不能为空'],
            ['phone', 'required', 'message' => '{attribute}不能为空'],
            ['email', 'required', 'message' => '{attribute}不能为空'],
            ['age', 'required', 'message' => '{attribute}不能为空'],
            ['sex', 'required', 'message' => '{attribute}不能为空'],
            ['hobby', 'required', 'message' => '{attribute}不能为空'],

            //去掉空格
            ['username', 'filter', 'filter' => 'trim'],
            ['password', 'filter', 'filter' => 'trim'],
            ['okpassword', 'filter', 'filter' => 'trim'],
            ['phone', 'filter', 'filter' => 'trim'],
            ['email', 'filter', 'filter' => 'trim'],
            ['age', 'filter', 'filter' => 'trim'],

            //唯一性验证
            [['phone'], 'unique','message'=>'{attribute}已经被占用'],
            [['username'], 'unique','message'=>'{attribute}已经被占用'],
            [['email'], 'unique','message'=>'{attribute}已经被占用'],

            //正则匹配验证
            [['password'],'match','pattern'=>'/^[a-zA-Z_]\w{6,20}$/','message'=>'{attribute}6-20位数字字母下划线组成,不能以数字开头'],
            [['username'],'match','pattern'=>'/^[a-zA-Z_]\w{6,20}$/','message'=>'{attribute}6-20位数字字母下划线组成,不能以数字开头'],
            [['age'],'match','pattern'=>'/^18|19|([2-4]\d)|50$/','message'=>'{attribute}为18-50以内整数'],
            //['age', 'integer','min'=>18,'max'=>50],
            [['phone'],'match','pattern'=>'/^1[3,5,8]\d{9}$/','message'=>'{attribute}为11位13,15,18开头'],
            ['okpassword', 'required', 'message' => '{attribute}不能为空'],
            ['okpassword','compare','compareAttribute'=>'password','message'=>'{attribute}与{attribute}一致'],
            ['captcha', 'captcha', 'message'=>'请输入正确地{attribute}','captchaAction'=>'form1/captcha'],           
        ];
    }

---------------------------------------------------------------------------------------------

控制器层

---------------------------------------------------------------------------------------------

<?php

namespace backend\controllers;

use Yii;
use yii\web\Controller;
use app\models\Form1;
use yii\web\UploadedFile;

class Form1Controller extends Controller
{
    public function actionIndex()
    {
        $model=new Form1();

        $model->load(Yii::$app->request->post());      
        if (Yii::$app->request->isAjax)
        {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model);
        }

        if($model->load(Yii::$app->request->post()))
        {
            //var_dump($_POST);die;
            $model->image = UploadedFile::getInstance($model, 'image');
            $model->image->name = time().$model->image->name;
            //print_r($model);die;
            if ($model->validate()){
                $model->image->saveAs('./upload/form1/' . $model->image->baseName . '.' . $model->image->extension);
                //print_r($img);die;
                //获取上传文件的名称   
                $img=$model->image;
                $image=$img->name;
                //print_r($image);die;
                $username=$_POST['Form1']['username'];
                //echo $username;die;
                $password=$_POST['Form1']['password'];
                $okpassword=$_POST['Form1']['okpassword'];
                $age=$_POST['Form1']['age'];
                $phone=$_POST['Form1']['phone'];
                $email=$_POST['Form1']['email'];
                $sex=$_POST['Form1']['sex'];
                //print_r($sex);die;
                $hobby1=$_POST['Form1']['hobby'];
                //print_r($hobby1);die;
                $hobby=implode(',',$hobby1);
                //print_r($hobby);die;
                //添加入库
                $connection = \Yii::$app->db;
                $query = $connection->createCommand()->insert("form1",['username'=>$username,'password'=>$password,'okpassword'=>$okpassword,'age'=>$age,'phone'=>$phone,'email'=>$email,'sex'=>$sex,'hobby'=>$hobby,'image'=>$image]);
                if($query->execute())
                {
                    //echo '成功';
                    // $this->redirect(array('form1/index'));
                    echo "<script>
                        alert('ok');
                        location.href='index.php?r=form1/index';
                    </script>";
                }
                else
                {
                    //echo '失败';
                    echo "<script>
                        alert('no');
                        location.href='index.php?r=form1/index';
                    </script>";
                }
            }
        }
        else
        {
            return $this->render('form',['model'=>$model]);
        }
       
    }
        /**
     * 生成验证码的方法
     */
    public function actions() {
        parent::actions();
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                //'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                'maxLength' => 3,
                'minLength' => 3
            ],
        ];
    }

}

posted on 2016-03-31 14:16  夏沫忆香  阅读(408)  评论(0编辑  收藏  举报