分类:
2008-04-14 19:56:16
【PHPChina讯】程序员们往往被告之不要去重复地编写程序, 而且最好的程序员在写他们自己的程序的时候都会借鉴别人的。:;" onClick="javascript:tagshow(event, 'PHP');" target="_self">PHP,作为一个基本的Web语言,常见于form的显示,处理和验证(确认)。然而,有一个强大的PEAR包需要更多的关注:它就是HTML_QuickForm,它促使图的提交和form的显示,而且更有用的是,客户端和服务器端都能够得到验证,即快又简单。这篇文章会让你了解PEAR包的基本知识。他假定你已有表格基础,并且有基本的PHP技能。
安装HTML_QuickForm
安装PEAR包只需要两个条件:PHP4.2版本以上,并且有HTML_Common包。现在为止HTML_QuickForm 3.2.7是最新的版本,它需要对应的HTML_Common 1.2.1。有人在为PHP5写这两个包(以HTML_QuickForm2和 HTML_Common2的形式),但是还没有发布。
你可以通过以下pear list检查PEAR是否已经安装:
pear list
Installed packages:
===================
Package Version State
Archive_Tar 1.1 stable
Console_Getopt 1.2 stable
DB 1.6.2 stable
Date 1.4.6 stable
HTTP 1.2.2 stable
Image_Canvas 0.3.0 alpha
Image_Color 1.0.2 stable
Image_Graph 0.7.2 alpha
Mail 1.1.3 stable
Net_SMTP 1.2.6 stable
Net_Socket 1.0.1 stable
PEAR 1.3.2 stable
Validate 0.6.3 beta
XML_Parser 1.0.1 stable
XML_RPC 1.1.0 stable
从以上可以知道,你的机器即没有HTML_QuickForm 也没有 HTML_Common,所以它们需要被安装:
pear install HTML_Common
downloading HTML_Common-1.2.3.tgz ...
Starting to download HTML_Common-1.2.3.tgz (4,746 bytes)
.....done: 4,746 bytes
install ok: HTML_Common 1.2.3
pear install HTML_QuickForm
downloading HTML_QuickForm-3.2.7.tgz ...
Starting to download HTML_QuickForm-3.2.7.tgz (102,475 bytes)
........................done: 102,475 bytes
install ok: HTML_QuickForm 3.2.7
显示form
使用代码去显示一个表单很简单,让我们以一个例子开始:
require_once "HTML/QuickForm.php"; // tell PHP to include the QuickForm package
$form = new HTML_QuickForm('register', 'post'); // instantiate the object
$form->addElement('text', 'firstName', 'Enter first name'); // add a text element
$form->addElement('password','password', 'Enter your password'); // add a password element
$form->addElement('textarea','ta','Description'); // add a textarea element
$form->addElement('submit','sb','Submit form'); // add a submit button element
$form->display();
?>
很明了这小段代码的意思:包的引入,的示例,然后加入元素(称作FirstName的:在它之后输入你的first name;password:在它之后输入你的password。)下面是HTML代码的样子:
因为你可以看到HTML_QuickForm允许你能够用更少的输入去得到同样的输出,所以即使没有其他的益处,它至少能节约你的一些时间(虽然在这个例子里我并没有介绍它!)。它同样加入了XHTML Strict-compliant(除了一点小例外是关于名字属性的遗留,这可以很容易地去除)。以上例子利用了一个text,一个textarea和一个password元素。以下有一个关于其它可添加的HTML_QuickForm 元素的列表,包括HTML_QuickForm 名称,和HTML equivalent。他们都给定为straighforward names,所以,如果你了解HTML,你就会理解它们:
element HTML
button
checkbox
file
hidden
image
password
radio
reset
select
还有许多常见的元素类型,我们不打算在这个指南里全做例子,作为参考把他们列出来:
advcheckbox An advanced checkbox type, allowing checkboxes to pass multiple values.
autocomplete A text field with autocomplete. It's a normal text element, but at each keypress JavaScript is used to read an array and autocomplete if there's anything matching.
date A group of elements for inputting dates and times
group Allows several elements to be grouped into a single new entity.
header Allows a heading to be added to the form.
hiddenselect A select element containing hidden elements for everything already selected with the methods setDefaults() or setConstants().
hierselect A select element where choosing one item from the first select will dynamically populate a linked second select element.
html Used to be used for adding raw HTML to a form, it's now deprecated.
link A link type field
static Static data
确认data
你已经发现了,我们在以前并没有太多的举例submit按钮事件。如果你查看form作用属性,你会发现相同的脚本命名。为了让使用更简单,HTML_QuickForm 自带参考,所以,同样的脚本是为了生成form,验证它,并且成功之后处理它。为了促使事件发生,我们需要添加logic去处理提交表单,并且确认数据。
验证是许多开发者的弱项,但是HTML_QuickForm使无论在客户端还是在服务器端的验证都非常的简单。它能做到这些是通过addRule()方式,之后,执行验证,用validate()方式。我们现在只能显示没有被验证的表单(因为在这个时候处理表单的代码能够被访问)。一切都很简单!这个例子有两个规则,一个是first name是必须填写的内容,第二个是first name必须只包含字母(并且不能是符号,所以就使得提交申请的人认真对待!):
require_once "HTML/QuickForm.php";
$form = new HTML_QuickForm('register', 'post');
$form->addElement('text', 'firstName', 'Enter first name');
$form->addElement('password','password', 'Enter your password');
$form->addElement('textarea','ta','Description');
$form->addElement('submit','sb','Submit form');
$form->addRule('firstName', 'Your name is required', 'required');
$form->addRule('firstName', 'Your name can only contain letters','lettersonly');
if ($form->validate()) {
// processing code goes here.
echo 'Success!';
}
else {
$form->display();
}
?>
试着去看看当你用无效数据提交这个表单时会发生什么,然后用有效数据试一次,一个红色的*指出first name是需要填写的。如果数据被不正确地填写(左边有空格,或有除了字母以外的其他符号)一个适当的出错信息会用红色显示出来。
以上例子应用了required和lettersonly规则。以下列出了可被应用到的所有的规则:
rule argument description
alphanumeric Can only contain alphanumeric characters (letters and numbers).
compare Compares two values.
email true (which applies a DNS check) Must be a valid email (in syntax) (checks for a valid hostname if the argument is set to true).
filename $regex The filename of the uploaded file must match the regular expression in $regex.
lettersonly Can only contain letters.
maxfilesize $maxsize The filename of the uploaded file cannot be larger than $maxsize bytes.
maxlength $maxlength Can be at most $maxlength characters in length.
mimetype $mimetype MIME type of the uploaded file must either be of type $mimetype (if $mimetype is scalar), or match one of the elements in $mimetype (if it's an array).
minlength $minlength Must be at least $minlength in length.
numeric Must contain a valid integer or decimal number.
nonzero Cannot be zero.
nopunctuation Cannot contain any punctuation characters, which include: ( ) . / * ^ ? # ! @ $ % + = , " ' > < ~ [ ] { }.
rangelength $minlength,$maxlength Must be inclusively between $minlength and $maxlength characters in length.
regex $regex Must match the regular expression $regex.
required Cannot be blank
uploadedfile Must contain a successfully uploaded file.
让我们看看一些例子和特列。一个非常有用的特列是,你也可以在客户端验证,用"client"标记。在客户端进行验证是很好的做法,因为可使得用户的使用更加的简单(他们不需要等待服务器的应答),但是你通常还是需要在服务器端进行验证,因为并不是所有客户端都有JavaScript激活功能。我们同样着眼于comparison规则(在这个例子中两个空格不能一样),和一个custom规则,它允许你用你的想要的标准去写一个函数:
require_once "HTML/QuickForm.php";
$form = new HTML_QuickForm('register', 'post');
$form->addElement('text', 'firstName', 'Enter first name');
$form->addElement('password','password', 'Enter your password');
$form->addElement('text','customer_email','Enter an email');
$form->addElement('textarea','ta','Description');
$form->addElement('submit','sb','Submit form');
$form->addRule('firstName', 'Your name is required', 'required');
$form->addRule('firstName', 'Your name can only contain letters','lettersonly');
$form->addRule('firstName', 'You must enter a first name', 'required', null, 'client');
$form->addRule('firstName', 'Your name cannot be less than two characters!','minlength',2,'client');
$form->addRule('customer_email', 'Please enter a valid email','email',true,'client');
$form->AddRule(array('password','firstName'),'Your password and first name cannot be the same!','compare','!=');
$form->registerRule('no_symbol','function','no_symbol_f');
$form->addRule('firstName','Sorry, your name cannot be Symbol','no_symbol');
if ($form->validate()) {
// processing code goes here.
echo 'Success!';
}
else {
$form->display();
}
function no_symbol_f($element_name,$element_value) {
if ($element_value == 'Symbol') {
return false;
}
else {
return true;
}
}
?>
以下是所要产生:
在这个例子中,compare规则允许其他操作者使用非等(!=),或者
处理表单数据
迄今为止,我们已经简单地成功显示了!如果表单已经被验证。虽然它看起来并不是特别的优秀。HTML_QuickForm 提供一个process()方式,它调用一个函数并审核提交值。以下是操作方式:
require_once "HTML/QuickForm.php";
$defaults_= array("firstName"=>"Ian",
"password"=>"abc",
"ta"=>"Describe yourself here");
$form = new HTML_QuickForm('register', 'post');
$form->addElement('text', 'firstName', 'Enter first name');
$form->addElement('password','password', 'Enter your password');
$form->addElement('textarea','ta','Description');
$form->addElement('submit','sb','Submit form');
$form->addRule('firstName','Your name is required', 'required');
if ($form->validate()) {
// processing code goes here.
$form->process('process_data', false);
}
else {
$form->setDefaults($defaults);
$form->display();
}
// For now just display the submitted vales, but you'll want to do a lot more
function process_data ($values) {
foreach ($values as $key=>$value) {
echo $key."=".$value."
";
}
}
?>
格式化表单
早期的HTML_QuickForm版本在改变layout的时候并没有那么灵活。但是,从3.0版本开始基于有 众所周知的Visitor设计样式。有8个renderer可用,而且有以下这些模板引擎直接支持:Smarty, HTML_Template_Sigma, HTML_Template_IT,HTML_Template_Flexy。要查看这些各式的renderer和模板引擎的细节必须在这篇文章之外,不过,在接下来的例子中简要地说明了HTML_QuickForm能够充分地定制你的表单输出。我的例子是凭空想象的,所以你一定要自己试试效果!确信无疑的是,如果你特别熟悉一个模板引擎,你会发现很快就能利用它。
require_once "HTML/QuickForm.php";
$defaults_= array("firstName"=>"Ian",
"password"=>"abc",
"ta"=>"Describe yourself here");
$form = new HTML_QuickForm('register', 'post');
$form->addElement('text', 'firstName', 'Enter first name');
$form->addElement('password','password', 'Enter your password');
$form->addElement('textarea','ta','Description');
$form->addElement('submit','sb','Submit form');
$form->addRule('firstName','Your name is required', 'required');
$renderer =& $form->defaultRenderer();
$special_element_template='
$renderer->setElementTemplate($special_element_template);
if ($form->validate()) {
// processing code goes here.
echo 'Success!';
}
else {
$form->setDefaults($defaults);
$form->display();
?>
结论
我确信你会发现它很容易使用,有关于这个包的更多的东西在官方的HTML_QuickForm(链接)页面上,有API和更多的PEAR包,还有用户文档。而且不要忘记当HTML_QuickForm2发布的时候,去查看这个包关于PHP5东西。
原文地址: