我正在使用 Zend Framework 和 Zend_Form 来呈现我的表单。但由于我发现很难自定义它,所以我决定单独打印元素。
问题是,我不知道如何在显示组中打印单个元素。我知道如何打印我的显示组(字段集),但我需要在其中添加一些内容(例如 <div class="spacer"></div>
以取消 float:left
。
有什么方法可以只显示组而不显示其内容,以便我自己单独打印它们?
感谢您的帮助。
最佳答案
您正在寻找的是“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>
最后是 Controller 代码:
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;
}
在您的 View 脚本中使用正常的 <?php $this->form ?>
显示此表单.
您可以将此方法用于您想要使用 Zend_Form 构建的任何表单。因此,将任何元素添加到您自己的字段集中都会很简单。
关于html - 如何从内容中单独打印组显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10349340/