使用yii框架注册的麻烦

时间:2014-11-10 06:33:32

标签: php yii registration

我正在尝试使用yii ActiveRecord实现用户注册。问题是每次加载视图时我都会遇到以下异常:

User has an invalid validation rule. 
The rule must specify attributes to be validated and the validator name. 

这是Users模型的相关部分:

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('username, password,verifyCode,email','message'=>'Tidak boleh kosong'),
            //array('password','compare'),
            array('verifyCode', 'captcha', 'required', 'allowEmpty'=>!extension_loaded('gd')),
            array('level_id', 'numerical', 'integerOnly'=>true),
            array('username', 'length', 'max'=>20),
            array('password, email', 'length', 'max'=>50),
            //array('password_repeat','required'),
            array('avatar', 'file', 'types'=>'gif,png,jpg'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, username, password, email, joinDate, level_id, avatar', 'safe', 'on'=>'search'),
    );
}

控制器:

public function actionRegister() {
    $registration = new RegistrationForm("register");
    // collect user input data
    if (isset($_POST['RegistrationForm'])) {
        $registration->attributes = $_POST['RegistrationForm'];
        $registration->attributes = $_POST['RegistrationForm'];
        // validate user input and redirect to the previous page if valid
        if ($registration->validate()) {
            // create an account model
            $account = new User;
            $account->username = $registration->username;
            $account->password = $registration->password;
            $account->email = $registration->email;
            $account->joinDate = new CDbExpression('NOW()');
            //$account->level_id = 1;
            if ($account->save()) {
                $member = new Member;
                $member->attributes = $registration->attributes;
                $member->user_id = $account->id;
                if ($member->save()) { 
                    $this->redirect(array('index'));
                } else {
                    $registration->addErrors($member->getErrors());
                }
            } else {
                $registration->addErrors($account->getErrors());
            }
        }
    }
    $this->render('register', array('model' => $registration));
}

1 个答案:

答案 0 :(得分:0)

这是因为您错过了第一条规则中的验证码。我想,你错过了所需的验证器。

所以你需要改变这个:

array('username, password,verifyCode,email','message'=>'Tidak boleh kosong'),

对于这样的事情:

array('username, password,verifyCode,email','required','message'=>'Tidak boleh kosong'),

另一个错误是你使用captcha validator。验证码只能在包含CFormModelCCaptcha WidgetCCaptcha action的视图中使用。

如果您想要上传文件,则不需要添加allowEmpty

array('avatar', 'file', 'allowEmpty' => true, 'types'=>'gif,png,jpg'),