使用Decorator編輯Zend_Form

很多人覺得使用zend_form相當麻煩,由其是對一些不熟悉css的人來說,zend_form絕對是麻煩的東西,還有人說zend_form違反了mvc的原則,因為它將vc集合在一起。雖然這樣,但是如果對zend_form和css的操作熟悉的話,它絕對可以幫我們節省很多時間。我們來看看怎樣使用Decorator來編輯Zend_Form的格式。(對css不熟悉的人,可以使用這些方式將tags修改為table)

現在假設我們都懂得建立zend_form,Zend_Form_Element_Text建立出來的基本格式應該是:
<dt><label for="name" class="required">類別名稱</label></dt>
<dd>
<input type="text" name="name" id="name" value="" />
</dd>
1.刪除
$name=new Zend_Form_Element_Text('name');
$name->setLabel('類別名稱')
->setRequired(true)
->addFilter('StringTrim')
->addFilter('StripTags')
->addValidator('NotEmpty')
->removeDecorator('label');
執行結果:
<dd>
<input type="text" name="name" id="name" value="" />
</dd>

2.次序設定
$name=new Zend_Form_Element_Text('name');
$name->setLabel('類別名稱')
->setRequired(true)
->addFilter('StringTrim')
->addFilter('StripTags')
->addValidator('NotEmpty')
->getDecorator( 'label' )->setOption( 'placement','append');
執行結果:
<dd>
<input type="text" name="name" id="name" value="" />
</dd>
<dt><label for="name" class="required">類別名稱</label></dt>

3.Tag修改
$name=new Zend_Form_Element_Text('name');
$name->setLabel('類別名稱')
->setRequired(true)
->addFilter('StringTrim')
->addFilter('StripTags')
->addValidator('NotEmpty')
->setDecorators(array('ViewHelper','Description','Errors',array('HtmlTag',array('tag' =>'ul')),array('Label',array('tag' =>'li'))));
執行結果:
<li><label for="name" class="required">類別名稱</label></li>
<ul>
<input type="text" name="name" id="name" value="" />
</ul>
ViewHelper - 可以加插一些view helper
Description - 加入說明文字
Errors - 當有錯誤時,系統顯示的錯誤文字
依上,所以我們可以加插說明文字和設定錯誤:
->setErrors(array('test'));
->setDescription('test');

4.Element內的次序設定,留意Description,Errors和ViewHelper的次序
->setDecorators(array('Description','Errors','ViewHelper',array('HtmlTag',array('tag' =>'ul')),array('Label',array('tag' =>'li'))));

5.統一設定
//for element
$this->setElementDecorators(array(
array('ViewHelper'),
array('Errors'),
array('Description'),
array('Label',array('separator'=>' ')),
array('HtmlTag',array('tag'=>'li','class'=>'class_name')),));

//for button
$submit->setDecorators(array(
array('ViewHelper'),
array('Description'),
array('HtmlTag',array('tag'=>'li','class'=>'submit-group')),));

沒有留言: