クイックスタートガイド

クイックスタートガイド -- HTML_QuickForm チュートリアル

イントロダクション

このチュートリアルは、QuickForm を初めて使うユーザに対して、 機能と使用法の概要を紹介するものです。 ここでは、利用できる機能の内のほんの一部だけについて解説しますが、 より広く深く知るために本マニュアルのどこを見れば良いかについても示していきます。

Keith Edmunds によって書かれた、QuickForm の使用法についての いくぶん長めのチュートリアル も参考となるでしょう。

はじめてのフォーム

例 40-1基本的な使用方法


<?php
// メインクラスの読み込み
require_once 'HTML/QuickForm.php';

// HTML_QuickForm オブジェクトを生成
$form = new HTML_QuickForm('firstForm');

// フォーム要素のデフォルト値を設定
$form->setDefaults(array(
    'name' => 'Joe User'
));

// フォームに要素をいくつか追加
$form->addElement('header', null, 'QuickForm tutorial example');
$form->addElement('text', 'name', 'Enter your name:', array('size' => 50, 'maxlength' => 255));
$form->addElement('submit', null, 'Send');

// フィルタと検証ルールを追加
$form->applyFilter('name', 'trim');
$form->addRule('name', 'Please enter your name', 'required', null, 'client');

// フォームの妥当性検証
if ($form->validate()) {
    echo '<h1>Hello, ' . htmlspecialchars($form->exportValue('name')) . '!</h1>';
    exit;
}

// フォームの出力
$form->display();
?>

では、順を追って上記の例を検討して行きましょう。

フォームの構築


<?php
$form = new HTML_QuickForm('firstForm');
?>

の行で、HTML_QuickForm オブジェクトが生成されています。 後で、このHTML_QuickForm オブジェクトに、要素に対応したオブジェクトや他の必要な情報を加えていくこととなります。 ここで、コンストラクタには、 フォームの名称のみを渡し、他のパラメータはデフォルト値が使われています。 フォームの method 属性には POST が、action 属性には現在のファイル名となります。 When using QuickForm, it is easier to keep all the form related logic in one file.

You might guess that


<?php
$form->setDefaults(array(
    'name' => 'Joe User'
));
?>

sets the default value for name element to 'Joe User'. QuickForm has the concept of default values (set via setDefaults() method) and constant ones (set via setConstants()). The difference between them is that user's input overrides default values but not constant ones.

Our form will consist of three elements:


<?php
$form->addElement('header', null, 'QuickForm tutorial example');
$form->addElement('text', 'name', 'Enter your name:', array('size' => 50, 'maxlength' => 255));
$form->addElement('submit', null, 'Send');
?>

The first one is not the 'real' element, it is just a heading to improve presentation. The second one actually is a text input box and the third is a submit button. Note that parameters for addElement() method have different meanings for different elements. That is so because they are actually passed to these elements' constructors.

Checking input

The line


<?php
$form->applyFilter('name', 'trim');
?>

defines a filter for the 'name' element value - the function that will be applied to it after form submit. In this case it is a builtin trim() function, but can be any valid callback. Thus we will strip all whitespace from the name, as we do not actually need it and as we want to be sure that a name was entered, not just some spaces.

Next we define a rule for the name field:


<?php
$form->addRule('name', 'Please enter your name', 'required', null, 'client');
?>

This means that QuickForm will display an error message if the name was not entered. The 'client' modifier is here to switch on client-side JavaScript validation in addition to server-side one. Note also that QuickForm will automatically mark required fields in the form.

Validating and processing

We now have the form built and rules defined and need to decide whether to process it or display:


<?php
if ($form->validate()) {
    // Do some stuff
}
?>

The validate() method will consider the form valid (i.e. return TRUE) if some data was actually submitted and all the rules defined for the form were satisfied. In our case this means that 'name' element was not empty.

If the form is validated we need to process the values


<?php
echo '<h1>Hello, ' . htmlspecialchars($form->exportValue('name')) . '!</h1>';
exit;
?>

This is an example, in your scripts you'll usually want to store the values somewhere and to redirect to some other page to prevent a duplicate submit. The process() and exportvalues() methods may be of interest here.

The last line is pretty easy:


<?php
$form->display();
?>

If the form is not valid, which means that it either was not yet submitted or that there were errors, it will be displayed. Error messages (if any) will be displayed near the corresponding elements.

Advanced features

You now should have an understanding of basic QuickForm functionality, but there are many more features in the package, each of them deserving a separate tutorial. This section will give a short overview of them and point you to the complete documentation.

Groups allow to combine several individual elements into one entity and to use it as one element. This is also used to create pseudo-elements like date and hierselect.

QuickForm offers a lot of possibilities to customize form layout and appearance. Form output is done via renderers - special classes containing necessary logic. There are renderers that directly output HTML and those that use template engines for this.

And finally, you can extend QuickForm by adding your own element types, rules and renderers.