我正在使用Zend Framework和Zend_Form来呈现我的表单。但是当我发现很难定制它时,我决定单独打印元素。
问题是,我不知道如何在显示组内打印单个元素。我知道如何打印我的显示组(字段集),但我需要在其中添加一些内容(例如<div class="spacer"></div>
取消float:left
。
有没有办法只显示没有内容的组,所以我可以自己单独打印它们?
感谢您的帮助。
答案 0 :(得分:7)
您正在寻找的是'ViewScript'装饰器。它允许您以任何您需要的方式形成您的HTML。这是一个简单的例子:
表单,一个简单的搜索表单:
<?php
class Application_Form_Search extends Zend_Form
{
public function init() {
// create new element
$query = $this->createElement('text', 'query');
// element options
$query->setLabel('Search Keywords');
$query->setAttribs(array('placeholder' => 'Query String',
'size' => 27,
));
// add the element to the form
$this->addElement($query);
//build submit button
$submit = $this->createElement('submit', 'search');
$submit->setLabel('Search Site');
$this->addElement($submit);
}
}
接下来是'部分'这是装饰器,这里是你如何构建html的地方:
<article class="search">
<!-- I get the action and method from the form but they were added in the controller -->
<form action="<?php echo $this->element->getAction() ?>"
method="<?php echo $this->element->getMethod() ?>">
<table>
<tr>
<!-- renderLabel() renders the Label decorator for the element
<th><?php echo $this->element->query->renderLabel() ?></th>
</tr>
<tr>
<!-- renderViewHelper() renders the actual input element, all decorators can be accessed this way -->
<td><?php echo $this->element->query->renderViewHelper() ?></td>
</tr>
<tr>
<!-- this line renders the submit element as a whole -->
<td><?php echo $this->element->search ?></td>
</tr>
</table>
</form>
</article>
最后是控制器代码:
public function preDispatch() {
//I put this in the preDispatch method because I use it for every action and have it assigned to a placeholder.
//initiate form
$searchForm = new Application_Form_Search();
//set form action
$searchForm->setAction('/index/display');
//set label for submit button
$searchForm->search->setLabel('Search Collection');
//I add the decorator partial here. The partial .phtml lives under /views/scripts
$searchForm->setDecorators(array(
array('ViewScript', array(
'viewScript' => '_searchForm.phtml'
))
));
//assign the search form to the layout place holder
//substitute $this->view->form = $form; for a normal action/view
$this->_helper->layout()->search = $searchForm;
}
在您的视图脚本中使用正常<?php $this->form ?>
。
您可以将此方法用于要使用Zend_Form构建的任何表单。因此,将任何元素添加到您自己的字段集中都很简单。