2017-05-05 42 views
0

我一直在使用aspnet一段時間,並且想要在php中實現aspnet viewstate(完全在codeigniter中)。有沒有辦法用Codeigniter實現ASP ViewState?在codeigniter中實現ViewState

+0

在php中沒有其他選擇viewstate的選擇。您可以自己編寫代碼或找到實現類似功能的框架。但是,personaly,asp.net webforms中的viewstate是我最討厭的東西(只是我的感覺,沒有別的)。 – shaggy

+0

如果您在失敗的字段驗證後查找表單,請仔細閱讀CI [表單驗證](https://www.codeigniter.com/user_guide/libraries/form_validation.html)類的文檔。該類的主要問題在於,驗證將無法實現您需要實現PRG模式的重定向。如果使用CI的表單驗證實施PRG是你想要的,我可以告訴你如何。 – DFriend

+0

我正在構建一個spa,重新加載頁面,如果你正在做一些事情(填充表單,編輯內容等),那麼在重新加載後部分地恢復頁面(使用查詢字符串在url中加載最後一個動作),但我無法恢復的數據(至少在我創建時,更新它很容易)。 ci表單驗證它不是一個替代方案。 –

回答

0

這個答案將完成Viewstate的一些目標,即保存表單提交之間的控件值。如果離開頁面,數據將丟失。但Viewstate也是如此。示例代碼大量使用CodeIgniter(CI)框架。

以下是一些與此處使用的CI部分相關的文檔。

的CI_Form_validation庫從不能夠保持跨重定向驗證結果受到影響。該類擴展了CI_Form_validation以克服該限制。

文件:應用程序/庫/ My_Form_validation.php

/** 
* Extends CI_Form_validation to facilitate using the Post/Redirect/Get pattern for form handling. 
* https://en.wikipedia.org/wiki/Post/Redirect/Get 
* http://solidlystated.com/design/best-way-to-process-forms-with-php/ 
* 
* The base class (CI_Form_validation) has the protected property $_field_data 
* which holds all the information provided by form_validation->set_rules() 
* and all the results gathered by form_validation->run(). 
* Form Helper and Form_Validation use the $_field_data to re-populate fields and present error messages. 
* 
* To use this class you must have CodeIgniter Session setup and working. 
* 
* This class stores $_field_data in session flash data for use in the controller method that is the 
* redirect target. 
* 
* Class is handy for defining custom validation methods which will NOT require the "callback_" prefix. 
* 
*/ 
defined('BASEPATH') OR exit('No direct script access allowed'); 

class MY_Form_validation extends CI_Form_validation 
{ 

    public function __construct($rules = array()) 
    { 
     parent :: __construct($rules); 
     $this->CI->load->library('session'); 
    } 

    /** 
    * Enhanced version of form_validation->run(). Sets a $_SESSION item with the contents of $this->_field_data 
    * 
    * @param string $group The name of the validation group to run 
    * @param bool $persistent If TRUE save the state of $_field_data even if validation passes 
    * @return boolean TRUE on success and FALSE on failure 
    */ 
    public function run($group = '', $persistent = FALSE) 
    { 
     if(parent:: run($group)) 
     { 
      if($persistent) 
      { 
       $this->CI->session->set_flashdata('validation_field_data', $this->_field_data); 
      } 
      return TRUE; 
     } 
     $this->CI->session->set_flashdata('validation_field_data', $this->_field_data); 
     return FALSE; 
    } 

    /** 
    * This is used in the redirect target defined in the form processing controller/method 
    * 
    * @return bool TRUE if $_SESSION['validation_field_data'] is set. It indicates that validation failed. 
    * Returns FALSE if there is no indication that validation has failed or even been run. 
    */ 
    public function is_failed_validation() 
    { 
     if(isset($_SESSION['validation_field_data'])) 
     { 
      // Validation failed or is being persisted. 
      $this->_field_data = $_SESSION['validation_field_data']; 
      return TRUE; 
     } 
     return FALSE; 
    } 

    /** 
    * A validation function to cleanup strings 
    * 
    * @param string $str Value of the field 
    * @return string|bool The sanitized string or FALSE if filter_var() fails 
    */ 
    public function sanitize_str($str) 
    { 
     return filter_var($str, FILTER_SANITIZE_STRING); 
    } 

    /** 
    * A do-nothing routine assigned to any field we want included in validation results 
    * @return boolean 
    */ 
    public function alwaysTrue($val) 
    { 
     return TRUE; 
    } 

} 

希望的註釋解釋發生了什麼事情。要理解的一件重要事情是form_validation僅捕獲具有驗證規則的控件的$ _POST數據。這就是「無所事事」驗證程序alwaysTrue()的原因。在您希望值持續存在的任何控件上使用此規則。

以下控制器顯示使用示例。

文件:應用程序/控制器/ Viewstate.php

class Viewstate extends CI_Controller 
{ 

    public function __construct() 
    { 
     parent::__construct(); 
     $this->load 
      ->library('form_validation', NULL, 'fv') //renames 'form_validation' to 'fv' 
      ->helper(['form', 'url']); 
     $this->fv->set_error_delimiters('<span class="error">', '</span>'); 
    } 

    public function index() 
    { 
     $this->fv->is_failed_validation(); //captures validation data if it's there 

     //Define some data for consumption by CI's Form Helper functions 
     $data['username_field'] = [ 
      'name' => 'username', 
      'id' => 'username', 
      'value' => $this->fv->set_value('username'), 
      'class' => 'your_css', 
     ]; 
     $data['confirm_username_field'] = [ 
      'name' => 'usernameconf', 
      'id' => 'usernameconf', 
      'value' => $this->fv->set_value('usernameconf'), 
      'class' => 'your_css', 
     ]; 
     $data['comment_field'] = [ 
      'name' => 'comment', 
      'id' => 'comment', 
      'value' => $this->fv->set_value('comment'), 
      'class' => 'comment', 
     ]; 
     $data['project_lead_field'] = [ 
      'name' => 'project_lead', 
      'value' => 1, 
      'checked' => $this->fv->set_radio('project_lead', 1, FALSE) 
     ]; 

     $selected_status = ['None' => "None"]; //default dropdown item 
     $status_items = ["None" => "None", "Good" => "Good", 'Bad' => 'Bad', "Ugly" => "Ugly"]; 
     //recover previously posted select item - if any 
     if($item = $this->session->validation_field_data['status']['postdata']) 
     { 
      $selected_status = [$item => $item]; 
     } 
     $data['status_field'] = [ 
      'name' => 'status', 
      'options' => $status_items, 
      'selected' => $selected_status 
     ]; 

     $this->load->view('testcase_view', $data); 
    } 

    /** 
    * This is the "action" that processes the form's posted data 
    */ 
    public function process() 
    { 
     //set rules and error messages at same time 
     $this->fv 
      ->set_rules('username', 'User Name', ['trim', 'required', 'matches[usernameconf]'], 
      ['required' => '<em>{field}</em> required.', 'matches' => "User Names don't match."]) 
      ->set_rules('usernameconf', '', ['trim', 'required'], ['required' => 'Retyping the User Name is required.']) 
      ->set_rules('comment', "", ['trim', 'sanitize_str']) 
      ->set_rules('project_lead', "", 'alwaysTrue') 
      ->set_rules('status', "", 'alwaysTrue') 
     ; 

     //So an uncheck checkbox will be part of the $_POST array 
     if(!isset($_POST['project_lead'])) 
     { 
      $_POST['project_lead'] = 0; 
     } 

     if(FALSE == $this->fv->run('', TRUE)) 
     { 
      redirect('viewstate'); 
     } 
     else 
     { 
      //do something with field values e.g. 
      //$this->model->instert($_POST); 
      redirect('viewstate'); //to prove the page state is persistent 
     } 
    } 
} 

我包括一些實際的現場驗證,以便讀者可以看到它是如何工作以及如何驗證結果堅持跨越重定向。

這裏是視圖

文件:應用/視圖/ textcase_view.php

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Test Persistent Page</title> 
     <style type="text/css"> 
      p{ 
       margin: 0; 
      } 
      .error { 
       color: #FF0000; 
       font-size: small; 
      } 
      .fld-label{ 
       color: #555; 
       font-size: .9em; 
      } 
      .comment{ 
       color: Blue; 
       font-weight: bold; 
      } 
      div{ 
       margin-bottom: 1em; 
      } 
      div + .fld-label 
      /*div + .error*/ 
      { 
       margin-bottom: 0; 
      } 
     </style> 
    </head> 
    <body> 
     <?= form_open('viewstate/process'); ?> 

     <span class="fld-label">User Name</span> 
     <div><?= form_input($username_field) ?> 
      <p><?= form_error('username'); ?></p> 
     </div> 

     <div class="fld-label">Retype User Name</div> 
     <div><?= form_input($confirm_username_field) ?> 
      <p><?= form_error('usernameconf'); ?></p> 
     </div> 

     <div class="fld-label">Comment</div> 
     <div><?= form_input($comment_field); ?></div> 

     <div class="fld-label">Project Lead?</div> 
     <div><?= form_checkbox($project_lead_field); ?></div> 

     <div class="fld-label">Status</div> 
     <div><?= form_dropdown($status_field); ?></div> 

     <p><input type="submit" value="Submit"></p> 
     <?= form_close(); ?> 
    </body> 
</html> 

視圖大量使用的表單輔助功能,諸如form_openform_closeform_input等等。