gpt4 book ai didi

PHP 代码点火器 : Passing dynamic form data to a view without having to refetch from the database upon validation errors

转载 作者:行者123 更新时间:2023-11-30 01:16:54 25 4
gpt4 key购买 nike

我正在使用 PHP Codeigniter 制作一个基本的注册页面。

在注册页面上,我要求用户从一系列类别中进行选择(通过 <select> html 元素)。这些类别存储在我的 MySQL 数据库的列表中。

我当前的方法是当用户调用函数加载页面时从数据库中获取此列表,然后将其显示给他们。但是,如果用户输入的数据不正确并且页面必须重新加载并出现验证错误,则保存列表中数据的变量似乎被清除,并且我必须在重新显示页面之前从数据库重新获取列表数据。

我相信文档中有一些关于如何将此变量设置为永久可用的内容,但再次查看时,我没有找到它。

有人能指出我正确的方向吗?对我来说,每次都需要重新获取这些数据似乎很愚蠢(我知道人们不会经常输入错误的信息,但这在某些情况下会派上用场)。

注意:这不是记住用户选择的问题。

最佳答案

此示例适用于使用 ci 表单助手的选择下拉列表(我正在从另一种形式修改它,希望它全部正确)

the Array of select values is: $categoryarray
the drop down field name is 'category'
the default value is $defaultcategory
a css class to style (bootstrap etc): $dropclass = 'class="input-medium"';

代码行是:

  form_dropdown('category',$categoryarray,set_value('category',$defaultcategory),$dropclass).form_error('category');

form_error('类别');最后用于显示验证错误消息即使有默认值 - 如果表单未通过表单中另一个字段的验证 - 这将“记住”用户选择的内容。

编辑!

好的,有好消息也有坏消息。坏消息 - 如果类别来自数据库,那么您需要再次获取它们。好消息 - CI 会记住用户从下拉列表中选择的类别。

坏消息实际上并不是什么大问题 - 如果您在模型中创建类别数组。那么只需添加一行代码即可进行验证。

// In the Model 

function makedropdown() {

// get your category list
$cats = $this->getAllCategories() ;

$categoryarray = array();

// make the array
foreach ( $cats->result() as $row ) {

$categoryarray[$row->category] = $row->category ; }

return $categoryarray ;

}

有人填写了表单,我们运行验证,验证失败。在 Controller 中:

if ( $this->form_validation->run($formrules) == FALSE ) {

// get the categoryarray
$data['categoryarray'] = $this->categorymodel->makedropdown() ;

// load form again
$this->load->view( 'myform', $data ); }

因此,即使我们再次从数据库获取类别以动态填充选择列表 - CI 仍然会记住用户第一次填写表单时的选择。

下拉列表的默认类别怎么样?如果它不会改变,那么它可以设置为配置。如果类别值来自数据库并且可以更改 - 那么可以在模型中创建默认类别。

编辑2

天哪,无论如何我总是这样做,所以为什么我没有想到这一点。所以是的,这是制定特定方法来显示您的 View 的另一个原因

 function _showCategoryForm(){

// get the categoryarray
$data['categoryarray'] = $this->categorymodel->makedropdown() ;

// anything else thats needed for the view

// load form view
$this->load->view( 'myform', $data ); }

现在我们没有任何重复的代码,并且如果需要,可以轻松地使用错误消息自定义验证失败。

// since i'm grinding on this - the validation should happen in a model 
// and that method returns true or false
if ( $this->somemodel->validateCategoryForm() == FALSE ) {

// custom obnoxious error message
$this->formerrormessage = "What part of required is eluding you?" ;

$this->_showCategoryForm() ; }

这要好得多,因为如果表单的需求发生变化 - 更改仅在一个地方。此外,我添加了一个下划线来提醒我们所有人,私有(private)方法是一种很好的做法。并且表单验证应该在模型中分开,由 Controller 调用。

关于PHP 代码点火器 : Passing dynamic form data to a view without having to refetch from the database upon validation errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18970808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com