2011-06-11 40 views
1

我正在關注this線程來創建表單,並且當表單元素的數目已知時它正在工作。現在我必須根據用戶選擇創建表單域。如何在zend中創建表單

例如:

<?php 

class Form_MyForm extends Zend_Form { 

    public function __construct($options = null) { 

     parent::__construct($options); 

     // Set the method for the display form to POST 
     $this->setMethod('post'); 

     $elements = array(); 

     // Get user input to create elements 
     $fields = $options['columns']; 

     // Create form elements 
     for($i = 0; $i < count($fields); $i++) { 
      $element = $this->CreateElement('text', 'field'.$i); 
      $element->setLabel($fields[$i]['name']); 
      $elements[] = $element; 
     } 

     $this->addElements($elements); 
     $this->setElementDecorators(array('ViewHelper')); 
     $this->setDecorators(array(array('ViewScript', array('viewScript' => 'myform-form.phtml')))); 

    } // end construct 


} // end class 
?> 

I can render each element separately但現在我不知道如何通過循環來呈現myForm的-form.phtml這些元素。我不得不循環,因爲號字段沒有在開始時知道..

感謝

+0

我不完全Zend_Form的行家(其實我恨它),但也許你應該將你的代碼移動到另一個方法中(比如'configureForm()'並讓它接受一個字段數量的參數? – netcoder 2011-06-11 20:34:38

+0

你的'$ columns'變量是什麼?我看不到它在哪裏創建。 – Marcin 2011-06-12 01:39:23

+0

@Marcin :對不起,它是錯字,它實際上是** $ field **數組,它包含表單域的標籤,例如:'array('FirstName' ,'LastName','BirthDate');'請再次查看問題。謝謝 – Student 2011-06-12 04:46:44

回答

1

應該使用這樣的 (沒有測試)

<? 
foreach ($this->element->getElements() as $element){ 
    echo $this->{$element->helper}(
     $element->getName(), 1, $element->getAttribs() 
    ) 
} 
?> 

$this->element應該是你的形式

0

旁註開始:這是典型的做這一切在init()方法,而不是覆蓋表單構造函數。但這不是什麼大不了的事情。

回覆:在myform-form.phtml,好像你可以調用$this->getOption('columns'),然後執行foreach循環來再現元素,類似於用於創建等領域的循環:用ViewScript裝飾的視圖腳本領域的渲染。

相關問題