2010-03-01 65 views
0

在action.class.php:如何重構這個symfony代碼?

$form = new NewsForm(); 
$form->setWidget('thumbnail', new sfWidgetFormSelect(array('choices' => $news['images']))); 
$form->getWidget('summarize')->setDefault($news['summarize']); 
$form->getWidget('title')->setDefault($news['title']); 

凡在前面的步驟中生成$news;

它看起來多餘,如何重構它?

回答

0

那麼你的代碼是不會冗餘的,直到你在多行動中使用相同的代碼。
爲了使其可重複使用,您可以利用在該form constructoroptions參數和改變形式如下:

class NewsForm extends ... { 

    public function configure() { 
     //Whatever you do here 
     //.... 

     // if a news is set we configure certain fields 
     if($news = $this->getOption('news', false)) { 
      $this->setWidget('thumbnail', new sfWidgetFormSelect(array('choices' => $news['images']))); 
      $this->setDefault('summarize', $news['summarize']); 
      $this->setDefault('title', $news['title']); 
     } 
    } 
} 

的,您可以創建表格:

$form = new NewsForm(array(), array('news' => $news)); 

參考: sfForm - getOption