老实说,考虑到PHP有一些成熟的表单包,我不会自己动手.
我为PHP4站点使用PEAR的HTML_QuickForm包(http://pear.php.net/manual/en/package.html.html-quickform.php).
对于PHP5,我将查看Zend_Form(http://framework.zend.com/manual/en/zend.form.html).
对于我的quickform代码,我使用了一个帮助器类,它允许我使用配置数组定义表单.例如:
echo QuickFormHelper::renderFromConfig(array(
'name' => 'area_edit',
'elements' => array(
'area_id' => array('type' => 'hidden'),
'active' => array('type' => 'toggle'),
'site_name' => array('type' => 'text'),
'base_url' => array('type' => 'text'),
'email' => array('type' => 'text'),
'email_admin' => array('type' => 'text'),
'email_financial' => array('type' => 'text'),
'cron_enabled' => array('type' => 'toggle'),
'address' => array('type' => 'address'),
),
'groups' => array(
'Basic Details' => array('site_name', 'base_url'),
'Address Details' => array('address'),
'Misc Details' => array(), // SM: Display the rest with this heading.
),
'defaults' => $site,
'callback_on_success' => array(
'object' => $module,
'function' => 'saveSite',
),
));
Run Code Online (Sandbox Code Playgroud)
请注意,上面的元素类型'address'和'toggle'实际上是多个表单字段(基本上是元类型).这就是我喜欢这个帮助类的方法 - 我可以用它们的规则定义一组标准字段(例如地址,credit_card等),它们可以以一致的方式用于许多页面.
你绝对可以.考虑用于存储有关窗体本身信息的表单类:对method,action,enctype的属性.还可以在顶部输入类似可选标题和/或描述文本的内容.当然,您还需要一组输入元素.这些可能会被放入他们自己的类中(虽然它们为InputText,InputCheckbox,InputRadio的子类化可能有点超过顶部).这是一个模糊的骨架设计:
class Form {
var $attributes, // array, with keys ['method' => 'post', 'action' => 'mypage.php'...]
$heading,
$description,
$inputs // array of FormInput elements
;
function render() {
$output = "<form " . /* insert attributes here */ ">"
. "<h1>" . $this->heading . "</h1>"
. "<p>" . $this->description . "</p>"
;
// wrap your inputs in whatever output style you prefer:
// ordered list, table, etc.
foreach ($this->inputs as $input) {
$output .= $input->render();
}
$output .= "</form>";
return $output;
}
}
Run Code Online (Sandbox Code Playgroud)
FormInput类只需要存储基础知识,例如类型,名称,值,标签.如果你想变得棘手,那么你可以应用验证规则,然后在渲染时将其转换为Javascript.
| 归档时间: |
|
| 查看次数: |
8857 次 |
| 最近记录: |