2010-03-01 48 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