开发者

How to refactor this symfony code?

开发者 https://www.devze.com 2022-12-21 08:16 出处:网络
In action.class.php: $form = new NewsForm(); $form->setWidget(\'thumbnail\', new sfWidgetFormSelect(array(\'choices\' => $news[\'images\'])));

In action.class.php:

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

Where $news is generated in previous steps;

It looks redunda开发者_StackOverflownt,how to refactor it?


Well your code is not redunant until you use the same code in mutliple actions.
To make it reusable, you can make use of the options parameter in the the form constructor and change the form as follows:

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']);
        }
    }
}

The you can create the form with:

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

Reference: sfForm - getOption

0

精彩评论

暂无评论...
验证码 换一张
取 消