2010-09-23 216 views
0

嗨,我有兩種形式,一個規範表單和一個源表單。Symfony合併兩個具有相同名稱字段的表單

我正在將兩種形式合併爲一種,以便用戶可以同時提交規範和規範的來源。

問題是規格表有一個名爲name的字段,而源表有一個名爲name的字段。所以,在創建表單和合並時,我有兩個名稱字段應該引用兩個不同的東西,規範名稱和源名稱。任何方式來解決這個問題,而不重構模型/數據庫?

class NewsLinkForm extends BaseNewsLinkForm 
{ 
    public function configure() 
    { 
    unset($this['id']); 

    $link = new SourceForm(); 
    $this->mergeForm($link); 

    $this->useFields(array('name', 'source_url')); 

    $this->setValidators(array(
     'source_url' => new sfValidatorUrl(), 
    )); 

    $this->validatorSchema->setOption('allow_extra_fields', true); 
    } 
} 

class SourceForm extends BaseLimelightForm 
{ 
    public function configure() 
    { 
    $this->useFields(array('name')); 

    $this->setWidgets(array(
     'name' => new sfWidgetFormInputText(array(), 
     array(
      'class'  => 'source_name rnd_3', 
      'maxlength' => 50, 
      'data-searchahead' => url_for('populate_sources_ac'), 
      'data-searchloaded' => '0' 
     )), 
    )); 

    $this->setValidators(array(
     'name'   => new sfValidatorString(array('trim' => true, 'required' => true, 'min_length' => 3, 'max_length' => 50)), 
    )); 

    $this->widgetSchema->setNameFormat('source[%s]'); 
    } 
} 

<h5>add specification</h5> 
    <div class="item"> 
     <?php echo $specificationForm['name']->renderLabel() ?> 
     <?php echo $specificationForm['name']->render(array('data-searchahead' => url_for('populate_lime_specifications_ac'), 'data-searchloaded' => '0')) ?> 
    </div> 
    <div class="item"> 
     <?php echo $specificationForm['content']->renderLabel() ?> 
     <?php echo $specificationForm['content']->render(array('data-searchahead' => url_for('populate_specifications_ac'), 'data-searchloaded' => '0')) ?> 
    </div> 
    <div class="clear"></div> 
    <div class="item"> 
     <?php echo $specificationForm['name']->renderLabel() ?> 
     <?php echo $specificationForm['name']->render() ?> 
    </div> 
    <div class="item"> 
     <?php echo $specificationForm['source_url']->renderLabel() ?> 
     <?php echo $specificationForm['source_url']->render() ?> 
    </div> 

回答

3

你可以試試這段代碼:

// rename the name field of the first form 
$sourceForm->setWidget('source_name', $sourceForm->getWidget('name')); 
unset($this['name']); 

// merge 
$newsLinkForm->mergeForm($sourceForm); 
+0

嗯,我嘗試這樣做,得到錯誤「字段必須sfWidget的一個實例。」 – Marc 2010-09-23 12:27:48

+0

@Marc:奇怪... $ newsLinkForm ['name']的類是什麼? – greg0ire 2010-09-23 12:48:53

+0

所以最終成爲sfFormInput類。 getWidget('name')將獲得小部件類。我最終在合併的源表單中使用以下名稱將其重命名爲source_name:$ this-> setWidget('source_name',$ this-> getWidget('name')); 未設置($ this ['name']); – Marc 2010-09-23 14:53:49

相關問題