2012-08-08 81 views
1

我使用這個DataMapper的http://datamapper.wanwizard.euDataMapper的驗證與表單驗證 - 笨

問題的DataMapper有笨的形式validation.but相似不是相同的驗證方法。

一個例子,一個模型管理員模型驗證陣列:

public $validation = array(
     'username' => array(
     'rules' => array('unique', 'required', 'trim', 'max_length' => 60, 'min_length' => 3), 
     'label' => 'User' 
    ), 
     'password' => array(
     'rules' => array('required', 'trim', 'encrypt', 'min_length' => 6), 
     'label' => 'Password' 
    ) 
); 

但表單驗證數組必須是這樣的:

public $form_validation = array(
    array(
     'field' => 'username', 
     'label' => 'User', 
     'rules' => 'unique|required|trim|max_length[60]|min_length[3]' 
    ), 
    array(
     'field' => 'password', 
     'label' => 'Password', 
     'rules' => 'required|trim|encrypt|min_length[6]' 
    ) 
); 

我並不想爲新的管理員兩次人工驗證添加(首先表單驗證,在datamapper驗證之後)。我認爲有一種方法可以通過一次手動驗證來實現。

對不起我英語不好,我希望你能理解。提前致謝。

回答

2

僅使用Datamapper的驗證就足夠了,沒有CI的表單庫。

當您嘗試保存模型時,save()方法將返回truefalse,具體取決於保存是否成功。如果不是該模型的error property應填寫爲驗證失敗生成的錯誤消息。消息可以從language files with keys named appropriately加載,也可以加載codeigniter的表單驗證庫的form_validaton_lang.php

在你的控制器,你可以利用他們的是這樣的:

Class TheController extends CI_Controller { 
    function save() { 
     // get the model object somehow 
     // ... 
     // update attributes 
     $model->prop0 = $this->input->post('prop0');    
     $model->prop1 = $this->input->post('prop1'); 
     // try to save it 
     if ($model->save()) { 
      // save successful 
      redirect(...); 
     } else { 
      // save failed load form again, with the model 
      $this->load->view('path/to/the/form', array('model' => $model)); 
     } 
    } 
} 

視圖可以工作是這樣的:

<form method="post" action="..."> 

    <label>prop0</label> 
    <input type="text" name="prop0" value="<?php print $model->prop0?> "> 
    <?php if (!empty($model->error->prop0)):?> 
     <div class="error"><?php print $model->error->prop1; ?></div> 
    <?php endif; ?> 

    <label>prop1</label> 
    <input type="text" name="prop1" value="<?php print $model->prop1?> "> 
    <?php if (!empty($model->error->prop0)):?> 
     <div class="error"><?php print $model->error->prop1; ?></div> 
    <?php endif; ?> 

    <buton type="submit">go</button> 
</form> 

可以使用相同的形式時,在不存在以前的型號數據庫,只需創建您需要的模型的空實例,並將其傳遞給表單。