2017-05-05 3 views
0

Ich habe mit Aspnet für eine ganze Weile gearbeitet, und ich möchte aspnet Viewstate mit in PHP implementieren (genau in Codeigniter). Gibt es eine Möglichkeit, ASP ViewState mit Codeigniter zu implementieren?Implement Viewstate in Codeigniter

+0

Es gibt keine Alternative zu Viewstate in PHP. Sie können es selbst programmieren oder ein Framework finden, das ähnliche Funktionen implementiert. Aber persönlich, viewstate in asp.net Webforms war das, was ich am meisten hasste (nur mein Gefühl, nichts anderes). – shaggy

+0

Wenn Sie nach der fehlgeschlagenen Feldüberprüfung nach einem Formular erneut suchen möchten, sehen Sie sich die Dokumentation der CI-Klasse [Formularüberprüfung] (https://www.codeigniter.com/user_guide/libraries/form_validation.html) an. Das Hauptproblem dieser Klasse besteht darin, dass die Validierung in eine Umleitung nicht überlebt, die Sie benötigen, um ein PRG-Muster zu implementieren. Wenn Sie PRG mit der Formularvalidierung von CI implementieren möchten, kann ich Ihnen zeigen, wie. – DFriend

+0

Ich baue ein Spa, laden Sie die Seite neu, es ist ein Schmerz in der a ** wenn Sie etwas tun (ein Formular ausfüllen, bearbeiten, etc.), ich die Seite teilweise nach dem Neuladen wiederherstellen (verwenden Sie die Abfragezeichenfolge) in der URL, um die letzte Aktion zu laden, aber die Daten kann ich nicht wiederherstellen (zumindest wenn ich erstelle, Aktualisierung ist einfach). ci Formvalidierung ist keine Alternative. –

Antwort

0

Diese Antwort wird einige der Ziele von Viewstate erreichen, indem Steuerwerte zwischen Formularübergaben beibehalten werden. Wenn Sie von der Seite weg navigieren, gehen die Daten verloren. Das gleiche gilt für Viewstate. Der Beispielcode verwendet stark das CodeIgniter (CI) Framework.

Hier finden Sie einige Dokumentation zu den hier verwendeten Teilen von CI.

Die CI_Form_validation Bibliothek in der Lage, leidet nicht Validierungsergebnisse über eine Umleitung zu halten. Diese Klasse erweitert CI_Form_validation, um diese Einschränkung zu überwinden.

Datei: application/Bibliotheken/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; 
    } 

} 

Hoffentlich werden die Kommentare zu erklären, was los ist. Eine wichtige Sache zu verstehen ist, dass form_validation nur die $ _POST-Daten für Steuerelemente mit Validierungsregeln erfasst. Das ist der Grund für die Validierungsroutine "do-nothing" alwaysTrue(). Verwenden Sie diese Regel für jedes Steuerelement, für das die Werte beibehalten werden sollen.

Der folgende Controller zeigt ein Anwendungsbeispiel.

Datei: application/controllers/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 
     } 
    } 
} 

enthalten ich einige aktuelle Feldvalidierung, damit die Leser sehen, wie das funktioniert und wie die Validierungsergebnisse bleiben in einer Umleitung. Hier

ist die Ansicht

Datei: application/views/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> 

Der Blick macht intensiven Gebrauch von Form Helper-Funktionen wie form_open, form_close, form_input usw.