用户
 找回密码
 入住 CI 中国社区
搜索
查看: 6427|回复: 1
收起左侧

[分享][翻译]官方教程第六篇:Quick Form Generation

[复制链接]
发表于 2008-1-13 09:40:01 | 显示全部楼层 |阅读模式
Quick Form Generation
快速表单生成

[注1:为了防止部分名词翻译之后反而觉得不好理解,在文中就保留了原字,比如model、view等等。]
[注2:其中有一段我也没看明白,文中 74-76 行,望高手指点。]

Easily set up and validate forms with a custom model and view.
通过模型[model]和外观[view]简单生成并验证表单。

This tutorial will focus on showing you how to setup an easy and reusable form generator using models and views. The example here is for a user login form. This tutorial does not deal with database interaction, but only building, validating, and fetching the form data.
这个教程主要向你展示如何使用 models 和 views 设置一个简单的、可再利用的表单生成器。这个例子展示了用户登录表单。这个教程并未处理数据库交互,而只是生成、验证并获取表单数据。

This tutorial does not use the PEAR package HTML_QuickForm2, but uses built-in Kohana functionality.
这个教程并未使用 PEAR 包 HTML_QuickForm2,使用的是 Kohana 自己的函数。

The Model
模型

First, we need to create a model. Our model will allow us to set the form title and action, the Validation rules, and inputs. It will also handle validation automatically.

首先,我们需要创建一个 model。我们的 model 将允许我们设置表单的标题和动作、验证规则和输入。它还处理验证的自动化。

PHP复制代码
<?php defined('SYSPATH') or die('No direct script access');
 
class Form_Model extend Model {
        // Action attribute
        // 动作
        protected $action = '';
       
        // Title attribute
        // 标题
        protected        $title = '';
       
        // Input data
        // 输入的数据
        protected $inputs = array();
       
        // Validation library
        // 验证库
        protected $validation;
       
        // Validation status
        // 验证状态
        protected $status;
       
        public function __construct($title = NULL, $action = NULL, $inputs = NULL) {
                // Uncomment the following line if you want the database loaded;
                // 将下面的注视去掉就可以加载数据库了
               
                //parent::__construct();
               
                // Load validation
                // 加载验证
                $this->validation = new Validation();
               
                // Set title
                // 设置标题
                is_null($title) or $this->title($title);
               
                // Set action
                // 设置行为
                is_null($action) or $this->action($action);
               
                // Set input data
                // 设置输入数据
                is_array($inputs) and $this->inputs($inputs);
        }
        /**
         * Set the form action.
         * 设置表单动作
         */

        public function action($uri) {
                $this->action = $uri;
                return $this;
        }
               
        /**
         * Set the form tiile.
         * 设置表单标题
         */

        public function title($title) {
                $this->action = $title;
        }
       
        /**
         * Set input data.
         * 设置表单输入数据
         */

        public function inputs($inputs) {
                $rules = array();
                foreach($inputs as $name => $data) {
                        $rules = array();
                        foreach($inputs as $name => $data) {
                                if (strpos($name, '[') !== FALSE) {
                                        // I love POST array, but I hate accounting for them in PHP
                                        // [如果$name含有“[”,去除“[]”以及内面的字符串,]
                                        // [我确实不明白什么意思,$_POST 的 $kye 里有“[]”?]
                                        // [去除之后 $key 得到的值是啥?]
                                        $key = preg_replace('/\[(?:.+)?\]/', '', $name);
                                } else {
                                        $key = $name;
                                }
                                if (isset($data['rules'])) {
                                        // Remove the rules from the input data
                                        // 将规则从 data 中移出
                                        $rules[$key] = arr::remove('rules', $data);
                                       
                                        // Reset current item
                                        // 保存现有项目
                                        $inputs[$name] = $data;
                                }
                        }
                       
                        // Set validation rules
                        // 设置验证规则
                        $this->validation->set_rules($ules);
                       
                        // Merge input data
                        // 合并输入数据
                        $this->inputs = array_merge($this->inputs, $inputs);
                       
                        return $this;
                }
               
                /**
                 * Run validation
                 * 运行验证
                 */

                public function validate() {
                        if ($this->status === NULL AND !empty($_POST)) {
                                // Run validation now
                                // 现在运行验证
                                $this->status = $this->validation->run();
                        }
                       
                        return $this->status;
                }
        }
        /**
         * Retrun the validated data
         * 返回验证过的数据
         */

        public function data($key = NULL) {
                if ($key === NULL) {
                        return $this->validation->data_array;
                } else {
                        return $this->validation->$key;
                }
        }
               
        /**
         * Build the form and retrun it.
         * 生成表单并返回它
         */

        public fuction build($template = 'kohana_form') {
                if ($this->status === NULL AND !empty(_$POST)) {
                        // Run validation now
                        // 运行验证
                        $this->status = $this->validation->run();
                }
               
                // Required data for the template
                // 模板所需的数据
                $form = array(
                          'action' => $this->action,
                          'title'  => $this->title,
                          'inputs' => array()
                   );
               
                foreach ($this->inputs as $name => $data) {
                        // Error name
                        // 错误名称
                        $error = $name . '_error';
                       
                        // Append the value and error to the input, if it does not
                        // already exit
                        // 将值和错误绑定到输入,如果它还不存在的话
                        $data += array(
                                  'value' => $this->validation->$name,
                                  'error' => $this->validation->$error
                          );
                       
                        $form['inputs'][$name] = $data;
                }
                return Kohana::instance()->load->view($template, $form);
        }
}
?>
复制代码


This file is included in Kohana by default as system/models/form.php.
这个文件作为 system/models/form.php 被默认包含在 Kohana 中。

[ 本帖最后由 cchaha 于 2008-1-13 09:41 编辑 ]

评分

参与人数 1威望 +5 收起 理由
Hex + 5 精品文章

查看全部评分

 楼主| 发表于 2008-1-13 09:44:11 | 显示全部楼层
<续>

One thing to note about our model is that most of the methods use return $this;. This allows chaining:
对于这个 model 需要注意的一件事是大部分方法是用返回 $this; 。这允许链式写法:

PHP复制代码
<?php
        $form = $this->load->model('form', TRUE)
      ->title('User Login')
      ->action('user/login');
?>
 
复制代码

All of the form methods except validate and build can be chained together.
所有的表单方法,除了验证和生成[build],可以链在一起。
The View
外观
In order to display our form, we need a view. By default, the model will load a view called kohana_form, but you are free to change the default name, or use a custom template with the generate($template_name) method.
为了显示我们的表单,我们需要一个外观。默认情况下,该 model 会夹在一个叫做 kohana_form 的外观,但是你可以随意更改默认的名字,或者通过方法 generate($template_name)  使用一个自定义的模板。
PHP复制代码
 
<?php echo form::open($action)?>
 
        <h4><?php echo $title ?></h4>
        <ul>
        <?php
                foreach ($inputs as $name => $data):
                // Generate label
                // 生成 label
                $label = empty($data['label'])
                    ? ''
                    : form::label($name, arr::remove('label',$data)) . "\n";
                   
                // Generate error
                // 生成错误
                $error = arr::remove('error', $data);
               
                // Set input name and id
                // 设置名称和id
                $data['name'] = $name;
               
                if (!empty($data['options'])) {
                        // Get options and selected
                        // 获取设置和选项
                        $options  = arr::remove('options', $data);
                        $selected = arr::remove('selected', $data);
                       
                        // Generate dropdown
                        // 生成下拉菜单
                        $input = form::dropdown($data, $option, $selected);
                } else {
                        switch(@data['type']) [
                                case 'textarea':
                                        // Remove the type, textarea doesn't need it
                                        // 不需要textarea类型,移除
                                        arr::remove('type', $data);
                                        $input form::textarea($data);
                                        break;
                                case 'submit':
                                        // Generate a submit button
                                        // 生成提交按钮
                                        $input = form::button($data);
                                        break;
                                default:
                                        // Generate a generic input
                                        // 生成常规的 input
                                        $input = form::input($data);
                                        break;
                        }
                }
        ?>
                <li>
                        <?php echo $label . $input . $error; ?>
                </li>
        <?php endforeach ?>
        </ul>
        <?php echo form::close()?>
 
复制代码


This file is included in Kohana by default as system/views/kohana_form.php. You can override the default form by creating application/views/kohana_form.php.
这个文件 system/views/kohana_form.php 是 Kohana 默认包含的文件。你可以通过创建 application/views/kohana_form.php 来覆盖默认文件。
That concludes the entire tutorial. From here, you can expand the Form model to handle database connections, or even extend the model with another model, to handle specific forms. You can modify the view to suit your preferred way of templating forms, or use a custom view for specific forms.
这里包含了全部的教程。从这里,你可以拓展表单模型进行数据库交互,或者通过另外一个模型来拓展此模型来处理特殊的表单。你可以修正外观以适合你的表单,或者为特殊表单使用自定义外观。
For more information about handling database interaction in your forms, I recommend looking at the Model Validation tutorial.
若需要更多的关于在表单中应用数据库交互的信息,我建议你看看Model Validation tutorial。
Questions or Comments?
Feel free to send me questions and comments, my email address is woody.gilk@kohanaphp.com.
有问题或者需要讨论?
随便发给我就行了,我的email地址:woody.gilk@kohanaphp.com

题外话:
这是我现阶段翻译 Kohana 官方教程的最后一篇,
因为其他的几篇和 Kohana 的编程无直接关系,
其中,第三篇教程 xss 攻击的防范,基本上可以不考虑官方的方法,因为太费资源。
以及后面两篇,
第七篇教程,如何去除 index.php ,这个在所有框架都是类似的,在本论坛 ci 版里已经有中文教程。
第八篇教程,多国语言版网站的设立,有这个需求的大大们就不需要我来翻译了,呵呵。
祝你学习愉快,再会:)

本版积分规则