Zend Framework 1 的 `Zend_Form` 元件提供強大的表單建構、驗證、過濾與裝飾功能。本文以「留言板表單」為例,完整示範從自動載入配置、表單類別建立、控制器處理到視圖渲染的標準流程。
<?php
// public/index.php 或 Bootstrap.php
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->registerNamespace('Application_'); // 應用命名空間
$loader->registerNamespace(['Foo_', 'Bar_']); // 第三方庫命名空間
// 關鍵:確保 forms 目錄在 include_path 中
set_include_path(implode(PATH_SEPARATOR, [
realpath(APPLICATION_PATH . '/../library'),
realpath(APPLICATION_PATH . '/forms/'), // ← 表單類別目錄
get_include_path(),
]));
路徑:application/forms/Guestbook.php
<?php
class Application_Form_Guestbook extends Zend_Form
{
public function init()
{
$this->setMethod('post');
// Email 欄位
$this->addElement('text', 'email', [
'label' => '您的 Email:',
'required' => true,
'filters' => ['StringTrim'],
'validators' => [
['EmailAddress', true],
],
]);
// 留言內容
$this->addElement('textarea', 'comment', [
'label' => '留言內容:',
'required' => true,
'validators' => [
['StringLength', false, [0, 2000]],
],
]);
// 驗證碼
$this->addElement('captcha', 'captcha', [
'label' => '請輸入下方 5 位字元:',
'required' => true,
'captcha' => [
'captcha' => 'Figlet',
'wordLen' => 5,
'timeout' => 300,
],
]);
// 送出按鈕
$this->addElement('submit', 'submit', [
'ignore' => true,
'label' => '送出留言',
]);
// CSRF 保護
$this->addElement('hash', 'csrf', ['ignore' => true]);
}
}
路徑:application/controllers/GuestbookController.php
<?php
class GuestbookController extends Zend_Controller_Action
{
public function signAction()
{
$request = $this->getRequest();
$form = new Application_Form_Guestbook();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
// 驗證通過,取得過濾後資料
$data = $form->getValues();
// 儲存邏輯(示意)
$comment = new Application_Model_Guestbook($data);
$mapper = new Application_Model_GuestbookMapper();
$mapper->save($comment);
// PRG 模式重導向
return $this->_helper->redirector('index');
}
// 驗證失敗:$form 內含錯誤訊息,直接渲染視圖
}
// 指派表單給視圖
$this->view->form = $form;
}
}
路徑:application/views/scripts/guestbook/sign.phtml
<h1>留言板</h1>
<?php
$this->form->setAction($this->url()); // 設定提交網址
echo $this->form; // 自動輸出完整表單 HTML
?>
預設輸出為 `
<?php
// 在表單 init() 中
$this->setDecorators([
'FormElements',
['HtmlTag', ['tag' => 'div', 'class' => 'form-container']],
'Form',
]);
// 元素層級裝飾器
$this->setElementDecorators([
'ViewHelper',
'Errors',
['HtmlTag', ['tag' => 'div', 'class' => 'form-group']],
['Label', ['tag' => 'label', 'class' => 'control-label']],
]);
// 按鈕特殊處理
$submit = $this->getElement('submit');
$submit->setDecorators(['ViewHelper', ['HtmlTag', ['tag' => 'div', 'class' => 'form-group']]]);
| 問題 | 解決方案 |
|---|---|
| Class 'Application_Form_Guestbook' not found | 確認 `forms/` 在 `include_path`,且檔名 `Guestbook.php`、類別名 `Application_Form_Guestbook` 符合 PSR-0 |
| 驗證碼不顯示 | 確認 GD + FreeType 已啟用;`Figlet` 需安裝 `php-pear/Text_CAPTCHA` 套件 |
| CSRF 驗證失敗 | 確認 Session 已啟動(`Zend_Session::start()`),且表單包含 `hash` 元素 |
遵循此標準流程,能建立結構清晰、可測試、易維護的 ZF1 表單系統。