
日期:2006-11-08 作者:喜騰小二 來源:PHPChina
【PHPChina訊】程式設計人員們往往被告之不要去重複地編寫程式, 而且最好的程式設計人員在寫他們自己的程式的時候都會藉鑒別人的。PHP,作為一個基本的Web語言,常見於form的顯示,處理和驗證(確認)。然而,有一個強大的PEAR包需要更多的關注:它就是HTML_QuickForm,它促使圖的提交和form的顯示,而且更有用的是,用戶端和伺服器端都能夠得到驗證,即快又簡單。這篇文章會讓妳瞭解PEAR包的基本知識。他假定妳已有HTML表格基礎,並且有基本的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(連結http://pear.php.net/manual/en/package.html.html-quickform.php)页面上,有API和更多的PEAR包,還有使用者文檔。而且不要忘記當HTML_QuickForm2發佈的時候,去檢視這個包關於PHP5東西。
原文地址:http://www.phpbuilder.com/columns/ian_gilfillan20061024.php3?page=2