memo.xight.org

日々のメモ

Smarty + HTML_QuickForm で 簡単フォーム生成

HTML_QuickFormのインストール

# pear install HTML_Common HTML_QuickForm

Sample (index.php)

HTML_QuickForm利用の手引きより
<?php
// ページを作成するのに使うライブラリの読み込み
require_once 'HTML/QuickForm.php';
require_once 'HTML/QuickForm/Renderer/ArraySmarty.php';
require_once 'smarty/libs/Smarty.class.php';

// Formの作成
$form = new HTML_QuickForm('secondForm');
$form->setDefaults(array(
	'name' => 'Namahage'
));

$form->addElement('header','second','QuickForm second example');
$form->addElement('text','name','Enter your name:', array('size' => 50, 'maxlength' => 255));
$form->addElement('submit','submit','Send');
$form->addElement('reset','reset','Reset');
$form->addRule('name','Please enter your name','required',null,'client');

if ($form->validate()) {
	// Formが正しかったらfreezeする
	$form->freeze();
}

// Smartyの設定
$smarty = new Smarty;
$smarty->template_dir = "./templates";
$smarty->compile_dir = "./templates_c";
$smarty->cache_dir = "./cache";

// Render関連の設定
$renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);
$form->accept($renderer);
$smarty->assign('form',$renderer->toArray());

// 表示
$smarty->display('index.tpl');
?>


Sample (templates/index.tpl)

HTML_QuickForm利用の手引きより
{* Smarty *}
<html>
	<head>
		{$form.javascript}
	</head>
	<body>
		<form {$form.attributes}>
			{$form.hidden}
			<h1>{$form.header.second}</h1>
			{$form.name.label}: {$form.name.error}{$form.name.html}<br>
			{$form.reset.html}
			{$form.submit.html}
		</form>
	</body>
</html>


Reference

PEAR初心者ガイド - HTML_QuickForm入門
http://www.planewave.org/translations/quickform/html_quickform.html
HTML_QuickForm利用の手引き
http://www.is.titech.ac.jp/~yanagis0/kei/quickform.html

Smarty : Template Engine
http://smarty.php.net/

HTML_QuickForm
HTML_QuickForm