在我正在处理的表单中,它会在注册时检查用户名是否为空,并在用户刊登评论之前提示输入用户名。
我累了在我的unique
课程的规则中添加comment
,但它没有在ajax帖子上验证
class Comment extends CActiveRecord
{
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
return array(
array('username', 'unique','className'=>'User','attributeName'=>'username','message'=>"Username already exists"),
);
}
在我看来
echo '<div class="form-group">
'.$form->labelEx($user,'username', array('class'=>'col-md-3 control-label')).'
<div class="col-md-9">
'.$form->textField($user,'username',array('class'=>'form-control input-md')).'
'.$form->error($user,'username').'
</div>
</div>';
//the output looks like this
/*<label class="col-md-3 control-label" for="User_username">Username</label>
<div class="col-md-9">
<input class="form-control input-md" name="User[username]" id="User_username" type="text" value="" />
<div class="errorMessage" id="User_username_em_" style="display:none"></div>
</div>*/
在我的控制器中
public function actionCreate()
{
/** @var Comment $comment */
$comment = Yii::createComponent($this->module->commentModelClass);
// Uncomment the following line if AJAX validation is needed
$a=new User;
$b=new Comment;
$this->performAjaxValidation(array($a,$b));
//end of Ajax validation
.....
.....
.....
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='ext-comment-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
返回Json是
{"Comment_username":["Nick Name cannot be blank."],"Comment_title":["Review Title cannot be blank."]}
知道我做错了什么?
答案 0 :(得分:0)
问题解决了。
必须添加
array('username', 'unique'),
在我的User
课程中,不是在我的comment
课程中