yii表單驗證規則

對yii深入瞭解總結出:希望對初學者有些幫助

Active Record (AR) 是一個流行的 對象-關係映射 (ORM) 技術。 每個 AR 類代表一個數據表(或視圖),數據表(或視圖)的列在 AR 類中體現爲類的屬性,一個 AR 實例則表示表中的一行。 常見的 CRUD 操作作爲 AR 的方法實現。因此,我們可以以一種更加面向對象的方式訪問數據。 例如,我們可以使用以下代碼向 tbl_post 表中插入一個新行。

yii 表單驗證規則

<?php
classContactFormextendsCFormModel
{
    public$_id;
    public$contact;//聯繫人
    public$tel;//電話
    public$fax;//傳真
    public$zipcode;//郵編
    public$addr;//地址
    public$mobile;//手機
    public$email;//郵箱
    public$website;//網址
    public$qq;//QQ
    public$msn;//MSN
    publicfunctionrules()
    {
        returnarray(
            array('contact','required','on'=>'edit','message'=>'聯繫人必須填寫.'),
            array('contact','length','on'=>'edit','min'=>2,'max'=>10,'tooShort'=>'聯繫人長度請控制在2-10個字符.','tooLong'=>'聯繫人長度請控制在2-10個字符.'),
             
            array('tel','match','pattern'=>'/^(\d{3}-|\d{4}-)(\d{8}|\d{7})?$/','message'=>'請輸入正確的電話號碼.'),
            array('fax','match','pattern'=>'/^(\d{3}-|\d{4}-)(\d{8}|\d{7})?$/','message'=>'請輸入正確的傳真號碼.'),
            array('mobile','match','pattern'=>'/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/','message'=>'請輸入正確的手機號碼.'),
 
            array('email','email','on'=>'edit','message'=>'郵箱輸入有誤.'),
             
            array('zipcode','required','on'=>'edit','message'=>'郵編必須填寫.'),
            array('zipcode','numerical','on'=>'edit','message'=>'郵編是6位數字.'),
            array('zipcode','length','on'=>'edit','min'=>6,'max'=>6,'tooShort'=>'郵編長度爲6位數.','tooLong'=>'郵編長度爲6位數.'),
             
            array('website','url','on'=>'edit','message'=>'網址輸入有誤.'),
            array('qq','match','pattern'=>'/^[1-9]{1}[0-9]{4,11}$/','message'=>'請輸入正確的QQ號碼.'),
            array('msn','email','on'=>'edit','message'=>'MSN輸入有誤.'),
        );
    }
 
}

$post=Post::model()->find(array(
    'select'=>'title',
    'condition'=>'postID=:postID',
    'params'=>array(':postID'=>10),
));
// 查找 postID=10 的那一行
$post=Post::model()->find('postID=:postID', array(':postID'=>10));
$criteria = new CDbCriteria();
$criteria->select = 'table_name,model_id,sum(amount) total';
$criteria->group = 'table_name,model_id';
$criteria->addCondition("$nIdcId=4");//也可以$criteria->condition = "$nIdcId=4";
$aResult = accessory_info::model()->findAll($criteria);


$c = new CDbCriteria();
$c->select = 't.id, t.created_at, t.outsource_id, t.user_id, t.operate, t.content';
$c->join = 'LEFT JOIN outsource ON outsource.id=t.outsource_id';
$c->condition = 'outsource.idc_id IN(' . implode(',', $idc_ids)  . ')';

if($last_log_id) {
$c->condition .= " AND t.id > $last_log_id";
}

$c->limit = 20;
$c->order = 't.id DESC';

$logs = OutsourceProcessLog::model()->findAll($c);

array(
'header'=>'支付渠道',
'name'=>'buy_method_id',
'value'=>'$data->buyMethod->title',
'filter'=>CHtml::listData(CoinBuyMethod::model()->findAll(), 'id', 'title'),//filter過濾篩選
),
array(
'name' => 'admin.username',
'filter' => CHtml::activeDropDownList($model, 'admin_id', CHtml::listData(Admin::model()->findAll(), 'id', 'username'), array('empty' => '-全部管理員-')),
),


$post=new Post;
$post->title='sample post';
$post->content='post body content';
$post->save();

$User = User::model();
$User->setIsNewRecord(true);
$User->name='wangliweid';
$User->sex=1;
$User->insert(); 

$User = new User;
$User->name='wangdsdfliweid';
$User->insert(); 

$User = User::model()->findByPk(1);
$User->name='wangliwei';
$User->sex=1;
$User->save();

public function tableName()
{
    return '{{post}}'; //使用表前綴功能
}

$post=Post::model()->findByPk(10); // 假設有一個帖子,其 ID 爲 10
$post->delete(); // 從數據表中刪除此行

AR 依靠表中良好定義的主鍵。如果一個表沒有主鍵,則必須在相應的 AR 類中通過如下方式覆蓋 primaryKey() 方法指定哪一列或哪幾列作爲主鍵。

public function primaryKey()
{
    return 'id';
    // 對於複合主鍵,要返回一個類似如下的數組
    // return array('pk1', 'pk2');
}

3. 創建記錄 
要向數據表中插入新行,我們要創建一個相應 AR 類的實例,設置其與表的列相關的屬性,然後調用 save() 方法完成插入:

$post=new Post;
$post->title='sample post';
$post->content='content for the sample post';
$post->create_time=time();
$post->save();


記錄在保存(插入或更新)到數據庫之前,其屬性可以賦值爲 CDbExpression 類型。 例如,爲保存一個由 MySQL 的 NOW() 函數返回的時間戳,我們可以使用如下代碼:

$post=new Post;
$post->create_time=new CDbExpression('NOW()');
// $post->create_time='NOW()'; 不會起作用,因爲
// 'NOW()' 將會被作爲一個字符串處理。
$post->save();
提示: 由於 AR 允許我們無需寫一大堆 SQL 語句就能執行數據庫操作, 我們經常會想知道 AR 在背後到底執行了什麼 SQL 語句。這可以通過開啓 Yii 的 日誌功能 實現。例如,我們在應用配置中開啓了 CWebLogRoute ,我們將會在每個網頁的最後看到執行過的 SQL 語句。

4. 讀取記錄 
要讀取數據表中的數據,我們可以通過如下方式調用 find 系列方法中的一種:

// 查找滿足指定條件的結果中的第一行
$post=Post::model()->find($condition,$params);
// 查找具有指定主鍵值的那一行
$post=Post::model()->findByPk($postID,$condition,$params);
// 查找具有指定屬性值的行
$post=Post::model()->findByAttributes($attributes,$condition,$params);
// 通過指定的 SQL 語句查找結果中的第一行
$post=Post::model()->findBySql($sql,$params);


$criteria=new CDbCriteria;
$criteria->select='title';  // 只選擇 'title' 列
$criteria->condition='postID=:postID';
$criteria->params=array(':postID'=>10);
$post=Post::model()->find($criteria); // $params 不需要了
注意,當使用 CDbCriteria 作爲查詢條件時,$params 參數不再需要了,因爲它可以在 CDbCriteria 中指定,就像上面那樣。

一種替代 CDbCriteria 的方法是給 find 方法傳遞一個數組。 數組的鍵和值各自對應標準(criterion)的屬性名和值,上面的例子可以重寫爲如下:

$post=Post::model()->find(array(
    'select'=>'title',
    'condition'=>'postID=:postID',
    'params'=>array(':postID'=>10),
));



// 獲取滿足指定條件的行數
$n=Post::model()->count($condition,$params);
// 通過指定的 SQL 獲取結果行數
$n=Post::model()->countBySql($sql,$params);
// 檢查是否至少有一行復合指定的條件
$exists=Post::model()->exists($condition,$params);

直接更新數據表中的一行或多行而不首先載入也是可行的。 AR 提供瞭如下方便的類級別方法實現此目的:

// 更新符合指定條件的行
Post::model()->updateAll($attributes,$condition,$params);
// 更新符合指定條件和主鍵的行
Post::model()->updateByPk($pk,$attributes,$condition,$params);
// 更新滿足指定條件的行的計數列
Post::model()->updateCounters($counters,$condition,$params);
在上面的代碼中, $attributes 是一個含有以 列名作索引的列值的數組; $counters 是一個由列名索引的可增加的值的數組;$condition 和 $params 在前面的段落中已有描述。

如果一個 AR 實例被一行數據填充,我們也可以刪除此行數據。

$post=Post::model()->findByPk(10); // 假設有一個帖子,其 ID 爲 10
$post->delete(); // 從數據表中刪除此行
注意,刪除之後, AR 實例仍然不變,但數據表中相應的行已經沒了。

使用下面的類級別代碼,可以無需首先加載行就可以刪除它。

// 刪除符合指定條件的行
Post::model()->deleteAll($condition,$params);
// 刪除符合指定條件和主鍵的行
Post::model()->deleteByPk($pk,$condition,$params);



當調用 save() 時, AR 會自動執行數據驗證。 驗證是基於在 AR 類的 rules() 方法中指定的規則進行的。 關於驗證規則的更多詳情,請參考 聲明驗證規則 一節。 下面是保存記錄時所需的典型的工作流。

if($post->save())
{
    // 數據有效且成功插入/更新
}
else
{
    // 數據無效,調用  getErrors() 提取錯誤信息
}
當要插入或更新的數據由最終用戶在一個 HTML 表單中提交時,我們需要將其賦給相應的 AR 屬性。 我們可以通過類似如下的方式實現:

$post->title=$_POST['title'];
$post->content=$_POST['content'];
$post->save();

如果有很多列,我們可以看到一個用於這種複製的很長的列表。 這可以通過使用如下所示的 attributes 屬性簡化操作。 更多信息可以在 安全的特性賦值 一節和 創建動作 一節找到。

// 假設 $_POST['Post'] 是一個以列名索引列值爲值的數組
$post->attributes=$_POST['Post'];
$post->save();


CActiveRecord 提供了幾個佔位符方法,它們可以在子類中被覆蓋以自定義其工作流。

beforeValidate 和
beforeSave 和 afterSave: 這兩個將在保存 AR 實例之前和之後被調用。
beforeDelete 和 afterDelete: 這兩個將在一個 AR 實例被刪除之前和之後被調用。
afterConstruct: 這個將在每個使用 new 操作符創建 AR 實例後被調用。
beforeFind: 這個將在一個 AR 查找器被用於執行查詢(例如 find(), findAll())之前被調用。 1.0.9 版本開始可用。
afterFind: 這個將在每個 AR 實例作爲一個查詢結果創建時被調用。

10. 使用 AR 處理事務 
每個 AR 實例都含有一個屬性名叫 dbConnection ,是一個 CDbConnection 的實例,這樣我們可以在需要時配合 AR 使用由 Yii DAO 提供的 事務 功能:

$model=Post::model();
$transaction=$model->dbConnection->beginTransaction();
try
{
    // 查找和保存是可能由另一個請求干預的兩個步驟
    // 這樣我們使用一個事務以確保其一致性和完整性
    $post=$model->findByPk(10);
    $post->title='new post title';
    $post->save();
    $transaction->commit();
}
catch(Exception $e)
{
    $transaction->rollBack();
}

$url=$this->createUrl($route,$params);
$this指的是控制器實例; $route指定請求的route 的要求;$params 列出了附加在網址中的GET參數。

默認情況下,URL以get格式使用createUrl 創建。例如,提供$route='post/read'和$params=array('id'=>100) ,我們將獲得以下網址:

/index.php?r=post/read&id=100

$user = Yii::app()->db->createCommand()->select('id, username, profile')->from('tbl_user u')->join('tbl_profile p', 'u.id=p.user_id')->where('id=:id', array(':id'=>$id))->queryRow();

$command = Yii::app()->db->createCommand('SELECT * FROM tbl_user');
$user = $command->queryRow();

$command = Yii::app()->db->createCommand();
$users = $command->select('*')->from('tbl_users')->queryAll();
$command->reset();  // clean up the previous query
$posts = $command->select('*')->from('tbl_posts')->queryAll();

// build and execute the following SQL:
// INSERT INTO `tbl_user` (`name`, `email`) VALUES (:name, :email)
$command->insert('tbl_user', array(
    'name'=>'Tester',
    'email'=>'[email protected]',
));

// UPDATE `tbl_user` SET `name`=:name WHERE id=:id
$command->update('tbl_user', array(
    'name'=>'Tester',
), 'id=:id', array(':id'=>1));

4. Building Schema Manipulation Queries 
Besides normal data retrieval and manipulation queries, the query builder also offers a set of methods for building and executing SQL queries that can manipulate the schema of a database. In particular, it supports the following queries:

createTable(): creates a table
renameTable(): renames a table
dropTable(): drops a table
truncateTable(): truncates a table
addColumn(): adds a table column
renameColumn(): renames a table column
alterColumn(): alters a table column
dropColumn(): drops a table column
createIndex(): creates an index
dropIndex(): drops an index

如果瀏覽器重定位到登錄頁面,而且登錄成功,我們將重定位瀏覽器到引起驗證失敗的頁面。我們怎麼知道這個值呢?我們可以通過用戶部件的returnUrl 屬性獲得。我們因此可以用如下執行重定向:

Yii::app()->request->redirect(Yii::app()->user->returnUrl);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章