2012-04-27 65 views
1

我正在使用Zend框架和Zend_Form來呈現我的表單。但由於我發現很難定製它,我決定單獨打印元素。如何從其內容中單獨打印組顯示?

問題是,我不知道如何打印顯示組中的單個元素。我知道如何打印我的顯示組(字段集),但我需要補充的東西里面(如<div class="spacer"></div>取消float:left

有什麼辦法來顯示該組唯一沒有它的內容,所以我可以單獨打印出來我自己?

謝謝你的幫助。

回答

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構建的表單。因此,將任何元素添加到自己的字段集中將很簡單。

+0

謝謝,這就是我最終做的,我在我看來設置了自己的fieldset。謝謝 :) – 2012-04-27 11:37:58