首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Yii 使用者註冊表單驗證完整實作:視圖、模型與控制器

     編輯:PHP 綜合知識

Yii 註冊表單從視圖到模型驗證的完整流程

視圖 register.php

beginWidget('CActiveForm'); ?>

labelEx($model, 'username'); ?>
textField($model, 'username'); ?>
error($model, 'username'); ?>
labelEx($model, 'password'); ?> passwordField($model, 'password'); ?> error($model, 'password'); ?>
labelEx($model, 'password2'); ?> passwordField($model, 'password2'); ?> error($model, 'password2'); ?>
labelEx($model, 'email'); ?> textField($model, 'email'); ?> error($model, 'email'); ?>
labelEx($model, 'sex'); ?> radioButtonList($model, 'sex', array(1 => '男', 2 => '女'), array('separator' => ' ')); ?>
labelEx($model, 'grade'); ?> dropDownList($model, 'grade', array(0 => '--請選擇--', 1 => '2010級', 2 => '2011級', 3 => '2012級')); ?> error($model, 'grade'); ?>
labelEx($model, 'hobby'); ?> checkBoxList($model, 'hobby', array(1 => '籃球', 2 => '足球', 3 => '排球'), array('separator' => ' ')); ?> error($model, 'hobby'); ?> endWidget(); ?>

模型 User.php

class User extends CActiveRecord {
    public $password2; // 非資料庫欄位

    public static function model($className = __CLASS__) { return parent::model($className); }
    public function tableName() { return '{{user}}'; }

    public function attributeLabels() {
        return array('username' => '姓名', 'password' => '密碼', 'password2' => '確認密碼', 'email' => '郵箱', 'sex' => '性別', 'grade' => '年級', 'hobby' => '愛好');
    }

    public function rules() {
        return array(
            array('username', 'required', 'message' => '用戶名不能為空'),
            array('password', 'required', 'message' => '密碼不能為空'),
            array('password2', 'compare', 'compareAttribute' => 'password', 'message' => '兩次密碼不一致'),
            array('email', 'email', 'allowEmpty' => false, 'message' => '郵箱格式不正確'),
            array('grade', 'in', 'range' => array(1,2,3), 'message' => '請選擇年級'),
            array('hobby', 'checkHobby'), // 自訂驗證
        );
    }

    public function checkHobby() {
        if (strlen($this->hobby) < 3) $this->addError('hobby', '愛好至少勾選 2 個以上');
    }
}

控制器 actionAdd

public function actionAdd() {
    $user = new User();
    if (isset($_POST['User'])) {
        if (is_array($_POST['User']['hobby'])) $_POST['User']['hobby'] = implode(',', $_POST['User']['hobby']);
        $user->attributes = $_POST['User'];
        if ($user->save()) echo 'success'; else echo 'error';
    }
    $this->renderPartial('new', array('model' => $user));
}

表單元素名稱與資料庫欄位對應,模型層集中驗證邏輯,控制器僅處理資料轉換與儲存。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved