2011-03-05 110 views
3

我一直在使用Symfony的表單框架。但想知道是否有人有更好的方法來動態地嵌入表單。動態嵌入表單symfony的更好方法是什麼?

問題出在我嵌入表單時(見底部),我需要給它一個數組索引,因爲Fabian解釋了sfForm對象如何在本文Advanced forms中像多維數組。

如果我想給用戶點擊一個按鈕,並嵌入另一種形式的能力,我怎麼能實現以下,如果他們點擊按鈕多次:

<input type="parent[child][]" /> 
<input type="parent[child][]" /> 
<input type="parent[child][]" /> 

...重複多少時間用戶點擊一個按鈕。我可以使用快速的JavaScript來複制和粘貼DOM中的表單元素。

而不是這樣的:

<input type="parent[child][1]" /> 
<input type="parent[child][2]" /> 
<input type="parent[child][3]" /> 

...反覆多次的用戶怎麼點擊一個按鈕。需要JavaScript方法來計算用戶單擊按鈕的次數,即設置正確的數組索引。還需要Ajax調用一個嵌入了此數組索引的PHP函數。如果可能,我想避免使用這種方法。

如何嵌入表單:

$parentForm = new ParentForm($parent)   

$child = new child(); 
$child->setParent($parent); 

$sfForm = new sfForm(); 
$sfForm ->embedForm($someIndex, new ChildForm($child)); 

$parentForm->embedForm('child', $sfForm); 
+0

根據我的經驗,我只聽到了AJAX方法 - 事實上,我的工作這樣的模塊上了。你爲什麼避免這個動機? – yitznewton 2011-03-06 02:42:01

+0

我意識到可以在不使用AJAX的情況下複製JS代碼中的AJAX功能 - 所有的AJAX都會返回一堆帶有表單域的HTML,例如, http://pastebin.com/KwXHcJ3Q。不知道這是否解決您的問題。 – yitznewton 2011-03-06 03:20:08

回答

0

嘿,我找到了一種方法!這裏棘手的部分是重寫sfWidgetFormSchema :: generateName方法。

class myWidgetFormSchema extends sfWidgetFormSchema 
{ 

    /** 
    * Generates a name. 
    * 
    */ 
    public function generateName($name) 
    { 
    $name = parent::generateName($name); 
    //match any [number] and replace it with [] 
    $name = preg_replace('/\[\d+\]/','[]', $name); 
    return $name; 
    } 
} 

現在,您只需要將其設置爲您的'包裝'形式。下面是我的例子有「法師有許多奴隸」模式:

public function configure() 
    { 
    $this->getWidgetSchema()->setFormFormatterName('list'); 
    $this->widgetSchema->setNameFormat('master[%s]'); 

    $slavesForm = new sfForm(); 
    $slavesForm->setWidgetSchema(new myWidgetFormSchema); 
    $slavesCount = $this->getOption('slaves_count', 2); 
    for ($i = 0; $i < $slavesCount; $i++) 
    { 
     $slave = new Slave(); 
     $slave->Master = $this->getObject(); 
     $form = new SlaveForm($slave); 
     $slavesForm->embedForm($i, $form); 
    } 
    $this->embedForm('new_slaves', $slavesForm); 
    } 

注意「slaves_count」選項,我從executeCreate經過是這樣的:

public function executeCreate(sfWebRequest $request) 
    { 
    $schema = $this->getRequest()->getParameter('master'); 

    $this->form = new MasterNewForm(null, array('slaves_count'=> count($schema['new_slaves']))); 

    $this->processForm($request, $this->form); 

    $this->setTemplate('new'); 
    } 

現在你可以很容易地使用jQuery克隆行不用擔心索引!乾杯。

+0

謝謝你。 Geeez抱歉花了我很長時間來投票。我更喜歡允許用戶使用jQuery克隆行。更好的..... – 2011-05-21 00:46:02

相關問題