このような設定をすべてのZendフォームに適用するには、Zend_Formを拡張する基本フォームクラスを作成する必要があります。これは、すべての他のフォームが拡張されます。
基本フォームのコンストラクタでは、さまざまなタイプの要素に異なるデコレータを設定したり、アプリケーションのデコレータをカスタマイズしたり、ヘルパーやバリデータなどのプレフィックスパスを指定したりします。
このメソッドについて注意する重要な点は、ベースフォーム__constructメソッドの場合は、最後の行にparent::__construct()
を呼び出す必要があります。これは、メソッドがZend_Form::__construct()
によって呼び出され、その後にコンストラクタのほかのものが実行されないためです。ここで
は一例です。
<?php
class Application_Form_Base extends Zend_Form
{
// decorator spec for form elements like text, select etc.
public $elementDecorators = array(
'ViewHelper',
'Errors',
array('Description', array('tag' => 'p', 'class' => 'description', 'escape' => false)),
array('HtmlTag', array('class' => 'form-div')),
array('Label', array('class' => 'form-label', 'requiredSuffix' => '*'))
);
// decorator spec for checkboxes
public $checkboxDecorators = array(
'ViewHelper',
'Errors',
array('Label', array('class' => 'form-label', 'style' => 'display: inline', 'requiredSuffix' => '*', 'placement' => 'APPEND')),
array('HtmlTag', array('class' => 'form-div')),
array('Description', array('tag' => 'p', 'class' => 'description', 'escape' => false, 'placement' => 'APPEND')),
);
// decorator spec for submits and buttons
public $buttonDecorators = array(
'ViewHelper',
array('HtmlTag', array('tag' => 'div', 'class' => 'form-button'))
);
public function __construct()
{
// set the <form> decorators
$this->setDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'div', 'class' => 'form')),
'Form'));
// set this as the default decorator for all elements added to the form
$this->setElementDecorators($this->elementDecorators, array('submit', 'button'), true);
// add prefix paths for decorators and validators
$this->addElementPrefixPath('My_Decorator', 'My/Decorator', 'decorator');
$this->addElementPrefixPath('My_Validator', 'My/Validator', 'validate');
parent::__construct();
// parent::__construct must be called last because it calls $form->init()
// and anything after it is not executed
}
}
おかげで、私は最終的にだけでなく、基本クラスの実装になってしまいました。次のリストでは、オートローダーでセットアップした名前空間を使用してaddElementPrefixPath呼び出しを自動的に実行するようにします。ありがとう – Ryan