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(); ?>
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 個以上');
}
}
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));
}
表單元素名稱與資料庫欄位對應,模型層集中驗證邏輯,控制器僅處理資料轉換與儲存。