1

我正在使用 Zend Framework 和 Zend_Form 来呈现我的表单。但由于我发现很难定制它,我决定单独打印元素。

问题是,我不知道如何在显示组中打印单个元素。我知道如何打印我的显示组(字段集),但我需要在其中添加一些东西(比如<div class="spacer"></div>取消float:left.

有没有办法只显示没有内容的组,以便我自己单独打印它们?

感谢您的帮助。

4

1 回答 1

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 构建的任何表单。因此,将任何元素添加到您自己的字段集中都很简单。

于 2012-04-27T11:23:03.477 回答