저는 aspnet을 꽤 오랫동안 사용해 왔습니다. PHP로 viewstate를 aspnet으로 구현하고 싶습니다. (정확히 codeigniter에서). Codeigniter로 ASP ViewState를 구현하는 방법이 있습니까?codeigniter의 Viewstate 구현
0
A
답변
0
이 대답은 양식 제출간에 제어 값을 보존하는 Viewstate의 목표 중 일부를 수행합니다. 페이지에서 다른 곳으로 이동하면 데이터가 손실됩니다. 그러나 Viewstate에서도 마찬가지입니다. 예제 코드는 CodeIgniter (CI) 프레임 워크를 많이 사용합니다.
여기에 사용 된 CI의 일부와 관련된 설명서가 있습니다. Form Helper
-
. 이 클래스는 그 한계를 극복하기 위해 CI_Form_validation을 확장합니다.
파일 : 응용 프로그램/라이브러리/
/**
* 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;
}
}
My_Form_validation.php이 희망 코멘트는 무슨 일이 일어나고 있는지 설명한다. 이해해야 할 중요한 점은 form_validation은 유효성 검사 규칙이있는 컨트롤에 대한 $ _POST 데이터 만 캡처한다는 것입니다. 이것이 무효 검증 루틴 alwaysTrue()
의 이유입니다. 값을 유지하려는 모든 컨트롤에서이 규칙을 사용하십시오.
다음 컨트롤러는 사용 예를 보여줍니다.
파일 : 응용 프로그램/컨트롤러/
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 } } }
Viewstate.php
나는 어떻게 작동 방법과 검증 결과를 리디렉션을 통해 지속 독자들이 볼 수 있도록 몇 가지 실제 현장 검증을 포함했다. 여기 는보기이다파일 : 애플리케이션 /보기/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_open
, form_close
, form_input
등
php에서 viewstate에 대한 대안은 없습니다. 직접 코딩하거나 유사한 기능을 구현하는 프레임 워크를 찾을 수 있습니다. 그러나 개인적으로, asp.net 웹 폼의 viewstate는 내가 가장 싫어하는 것 (단지 내 느낌, 그 밖의 것)이 아니었다. – shaggy
필드 검증에 실패한 후 양식을 다시 채우려는 경우 CI의 [양식 유효성 검사] (https://www.codeigniter.com/user_guide/libraries/form_validation.html) 클래스에 대한 설명서를 자세히 살펴보십시오. 이 클래스의 주된 문제점은 PRG 패턴을 구현하는 데 필요한 리디렉션에서 유효성 검사가 유지되지 않는다는 것입니다. CI의 양식 유효성 검사를 사용하여 PRG를 구현하면 원하는 것을 보여줄 수 있습니다. – DFriend
나는 스파를 만들고, 페이지를 다시로드한다. ** 당신이 뭔가를하고 있다면 (폼을 채우고, 뭔가를 편집하는 등), 리로드 후에 페이지를 부분적으로 복원한다. (쿼리 문자열을 사용한다. 마지막 작업을로드 할 URL)하지만 데이터를 복원 할 수 없습니다 (적어도 내가 만들고있을 때 쉽게 업데이트 할 수 있습니다). ci 형식 검증은 대안이 아닙니다. –