控制器层
<?php
namespace frontendcontrollers;
use Yii;
use frontendmodelsFormsModel;
use yiiwebUploadedFile;
class FormsController extends yiiwebController
{
/**
* 生成验证码的方法
*/
public function actions() {
parent::actions();
return [
'captcha' => [
'class' => 'yiicaptchaCaptchaAction',
//'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
//'backColor'=>0x00ff00,//背景颜色
//'padding'=>5,//间距
//'height'=>40,//高度
//'width'=>150,//宽度
//'foreColor'=>0x000000,//字体颜色
//'offset'=>4,//设置字符偏移量 有效果
'maxLength' => 3,
'minLength' => 3
],
];
}
public function actionIndex()
{
$model = new FormsModel;
if($model->load(Yii::$app->request->post())){
//ajax验证唯一性
if (Yii::$app->request->isAjax)
{
Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
return yiiootstrapActiveForm::validate($model, ['username', 'email', 'phone']);
}
//上传图片
$model->userimg= UploadedFile::getInstance($model, 'userimg');
if($files = $model->upload()){
$post = Yii::$app->request->post();
//var_dump($post);die;
$hobbys = $post['FormsModel']['hobby'];
$model->hobby = implode(',',$hobbys);
$model->userimg = $files;
if($model->save(false)){
echo 'ok';
} else {
echo '添加失败';
}
} else {
//上传失败
print_r($model->errors);
}
} else {
return $this->render('index',['model'=>$model]);
}
}
}
验证模型层
<?php
namespace frontendmodels;
use Yii;
use yiicaptchaCaptcha;
/**
* This is the model class for table "forms".
*
* @property integer $id
* @property string $username
* @property string $password
* @property integer $age
* @property string $sex
* @property string $phone
* @property string $email
* @property string $userimg
* @property string $hobby
*/
class FormsModel extends yiidbActiveRecord
{
public $captcha;
public $repassword;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'forms';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username', 'password', 'repassword', 'workyear', 'age', 'sex', 'phone','email','hobby','selfdesc'], 'required', 'message'=>'{attribute}不能为空'],
[['username', 'password', 'repassword', 'workyear', 'age', 'sex', 'phone','email','selfdesc'], 'filter', 'filter'=>'trim'],
[['username'], 'match', 'pattern'=>'/^w{6,20}$/', 'message'=>'{attribute}为6-20位数字字母或下划线'],
//['username', 'unique', 'targetClass' => 'commonmodelsUser', 'message' => 'This username has already been taken.'],
['password','match','pattern'=>'/^[a-zA-z]w{5,20}$/','message'=>"{attribute}6-20位数字字母下划线组成,不能以数字开头"],
['repassword','compare','compareAttribute'=>'password','message'=>"两次密码不一致"],
['age','number','integerOnly'=>true,'max'=>50,'min'=>18,"tooBig"=>"18-50以内的整数","tooSmall"=>'18-50以内的整数'],
['sex', 'in', 'range'=>['男', '女'], 'message'=>'{attribute}只能是男或女'],
['phone', 'match', 'pattern'=>'/^1[3,5,8]d{9}$/','message'=>"{attribute}必须由13,15,18开头且11位数字组成"],
['selfdesc','match','pattern'=>'/^[x{4e00}-x{9fa5}]{3,18}$/u','message'=>"{attribute}必须由3到18个汉字组成"],
[['username','email','phone'],'unique','message'=>"{attribute}必须唯一"],
//['phone', 'checkPhone'],
['email', 'email'],
//['email', 'unique'],
['userimg', 'file', 'skipOnEmpty'=>false, 'extensions'=>'png,jpg,gif'],
['captcha', 'captcha', 'message'=>'请输入正确地{attribute}','captchaAction'=>'forms/captcha'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => '用户名',
'password' => '密码',
'age' => '年龄',
'sex' => '性别',
'phone' => '电话',
'email' => '邮箱',
'userimg' => '图片',
'hobby' => '爱好',
'repassword'=>'确认密码',
'captcha'=>'验证码',
'workyear'=>'工作经验',
'selfdesc'=>'自我描述',
];
}
//上传图片
public function upload()
{
if ($this->validate()) {
$this->userimg->saveAs('./upload/forms/' . $this->userimg->baseName . '.' . $this->userimg->extension);
return $this->userimg->baseName . '.' . $this->userimg->extension;
} else {
return false;
}
}
}
工作经验模型层
<?php
namespace frontendmodels;
use Yii;
/**
* This is the model class for table "workyear".
*
* @property integer $w_id
* @property integer $workyear
*/
class WorkyearModel extends yiidbActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'workyear';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['workyear'], 'string', 'max' => 50]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'w_id' => 'W ID',
'workyear' => '工作经验',
];
}
}
视图层
<?php
use yiihelpersHtml;
use yiiwidgetsActiveForm;
use yiicaptchaCaptcha;
use frontendmodelsWorkyearModel;
/* @var $this yiiwebView */
/* @var $model frontendmodelsFormsModel */
/* @var $form ActiveForm */
?>
<div class="forms-index">
<?php $form = ActiveForm::begin(['id'=>'sign-form', 'options'=>['action'=>'forms/index', 'method'=>'post', 'enctype'=>'multipart/form-data']]); ?>
<?= $form->field($model, 'username',['enableAjaxValidation' => true])->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($model, 'repassword')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($model, 'sex')->radioList(['男'=>'男','女'=>'女']) ?>
<?= $form->field($model, 'age')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'phone',['enableAjaxValidation' => true])->textInput(['maxlength' => true]) ?>
<?= $form->field($model,'workyear')->dropdownList(WorkyearModel::find()->select(['workyear', 'w_id'])->
indexBy('w_id')->column(),['prompt'=>'请选择工作经验']);?>
<?= $form->field($model, 'email',['enableAjaxValidation' => true]) ?>
<?= $form->field($model, 'hobby')->checkboxList(['唱歌'=>'唱歌','跳舞'=>'跳舞','看电影'=>'看电影']) ?>
<?= $form->field($model, 'selfdesc')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'userimg')->fileInput() ?>
<?= $form->field($model, 'captcha')->widget(Captcha::className(), ['captchaAction'=>'forms/captcha',
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div><!-- forms-index -->
解析:
Filter: 过滤,'filter'=>'trim',表示去空格
Required:必须的,表示不能为空
Match: 匹配正则,需要和pattern一起使用,定义正则表达式,'pattern'=>'/^w{6,20}$/',
Unique:验证数据唯一性,在注册时用到的比较多,这里需要注意的是,在rules规则里面定义的唯一性验证,只有在服务器端才能验证,
如果想要在表单页面显示,需要开启”enableAjaxValidation”=>ture;
例如:
<?php $form = ActiveForm::begin([
'id'=>'sign-form',
//'enableAjaxValidation' => true,//启用ajax验证,将属性值发送到服务器端进行验证并返回结果,默认为false
'enableClientValidation' => true,//启用客户端验证,默认值为true,关闭后表单无js验证
'options'=>['action'=>'usermessage/signform', 'method'=>'post', 'enctype'=>'multipart/form-data']]); ?>
这里需要注意的是,在这里启用的话,ajax验证是作用于所有的属性的,所以,还有另一种开启方式,在某一个field里面开启:
<?= $form->field($model, 'username', ['enableAjaxValidation'=>true])->textInput() ?>,这样就单独作用于username属性了。
要想实现表单ajax验证唯一性,后台还要一个ajax判断:
$model->load(Yii::$app->request->post());
if (Yii::$app->request->isAjax)
{
Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
return yiiootstrapActiveForm::validate($model);
}
在有数据提交时,最好先执行$model->load(Yii::$app->request->post()); 操作,不要做多余的处理,然后判断ajax,否则ajax验证的时候可能会报错500。如果有验证码,
这里就会有另一个问题:return yiiootstrapActiveForm::validate($model);这个验证的是所有的属性,而验证码执行validate后就会重新生成,
那么在表单提交时我们进行数据有效性验证时就会报错,
解决方式:yiiootstrapActiveForm::validate()这个方法其实是有两个参数的,$model,$attributes,我们可以指定ajax验证某一些特定的属性,
写法是:yiiootstrapActiveForm::validate($model, ['username', 'email', 'phone']);
这样ajax验证时就只验证username,email,phone这三个字段了,不会影响验证码。
Number:数字验证,加上'integerOnly'=>true,表示只能是整数,max,min分别表示最大最小值,tooBig和tooSmall分别是超过最大值和低于最小值时的错误提示信息
Compare:比较,用于两个属性之间的比较,'compareAttribute'=>'password',表示与password比较
In:和range连用,定义范围,表示属性值必须在这个范围内,通常用于验证某些固定值
Email:邮箱验证
File:文件验证 extensions可以定义上传文件的类型
Captcha:验证码验证,需要定义生成验证码的方法,'captchaAction'=>'usermessage/captcha',usermessage表示控制器名,captcha表示方法名
可以在控制器层定义一个actions方法添加captcha方法:
/**
* 生成验证码的方法
*/
public function actions() {
parent::actions();
return [
'captcha' => [
'class' => 'yiicaptchaCaptchaAction',
//'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'maxLength' => 3,
'minLength' => 3
],
];
}
每一个验证都可以添加应用场景:’on’=>’register’;
在控制器层实例化模型层
$model = new Usermessage();
$model->setScenario('register'); 定义使用应用场景为register
在模型层需要定义场景作用的对象
/**
* 定义验证场景
*/
public function scenarios()
{
return [
'register' => ['username', 'password', 'repassword', 'age', 'sex', 'phone','email'],
'login' => ['username', 'password','age', 'sex', 'phone','email'],
];
}
然后在对应的验证规则后面限定应用场景’on’=>’register’;
当表单验证时,为在作用场景以内的参数可以不受验证规则的限制
添加入库:复选框因提交过来后是一个数组,所以在执行save()前需要将复选框的值处理成字符串