Zend_Form 提供強大的表單定義、驗證、過濾、裝飾器渲染功能。本文完整演示:**自動加載配置 → 表單類定義 (元素、驗證器、過濾器、CSRF) → 控制器處理 (POST 驗證、保存) → 視圖渲染**,附最佳實踐與常見坑點。
<?php
// public/index.php 或 Bootstrap.php
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->registerNamespace('Application_'); // 表單類前綴
// include_path 包含 forms 目錄
set_include_path(implode(PATH_SEPARATOR, [
realpath(APPLICATION_PATH . '/../library'),
realpath(APPLICATION_PATH . '/forms/'), // 關鍵!
get_include_path(),
]));
?>
<?php
class Application_Form_Guestbook extends Zend_Form
{
public function init()
{
$this->setMethod('post')
->setAttrib('id', 'guestbook-form')
->setAttrib('class', 'form-horizontal');
// 1. Email 元素
$this->addElement('text', 'email', [
'label' => '您的郵箱:',
'required' => true,
'filters' => ['StringTrim', 'StringToLower'],
'validators' => [
['EmailAddress', true, ['messages' => ['emailAddressInvalidFormat' => '郵箱格式不正確']]],
['StringLength', false, [3, 254, 'messages' => ['stringLengthTooShort' => '郵箱過短']]],
],
'decorators' => $this->getDefaultElementDecorators(), // 統一裝飾器
]);
// 2. 留言內容 (textarea)
$this->addElement('textarea', 'comment', [
'label' => '留言內容:',
'required' => true,
'filters' => ['StringTrim'],
'validators' => [
['StringLength', true, [1, 500, 'messages' => ['stringLengthTooLong' => '留言不能超過 500 字']]],
],
'attribs' => ['rows' => 5, 'cols' => 50],
]);
// 3. 驗證碼
$this->addElement('captcha', 'captcha', [
'label' => '請輸入右側驗證碼:',
'required' => true,
'captcha' => [
'captcha' => 'Figlet', // 或 'Image' (需 GD)
'wordLen' => 5,
'timeout' => 300,
'font' => APPLICATION_PATH . '/../data/fonts/figlet.flf', // Figlet 字體
],
]);
// 4. 提交按鈕
$this->addElement('submit', 'submit', [
'ignore' => true, // 不參與驗證/獲取值
'label' => '提交留言',
'attribs' => ['class' => 'btn btn-primary'],
]);
// 5. CSRF 保護 (隱藏字段)
$this->addElement('hash', 'csrf', [
'ignore' => true,
]);
// 統一設置元素裝飾器 (可選,簡化輸出)
$this->setElementDecorators([
'ViewHelper',
'Errors',
['Description', ['tag' => 'span', 'class' => 'help-text']],
['HtmlTag', ['tag' => 'div', 'class' => 'form-group']],
['Label', ['tag' => 'label', 'class' => 'control-label']],
]);
$this->setDecorators([
'FormElements',
['HtmlTag', ['tag' => 'fieldset', 'class' => 'form-fieldset']],
'Form',
]);
}
}
?>
<?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');
}
// 驗證失敗:表單會自動填回用戶輸入並顯示錯誤信息
}
// 分配給視圖
$this->view->form = $form;
}
}
?>
<h2>給我們留言</h2>
<?php
// 設置表單提交地址 (當前 URL)
$this->form->setAction($this->url());
// 直接輸出表單 (使用裝飾器渲染)
echo $this->form;
?>
輸出將包含完整 `