2012-08-10 31 views
0

我想我可能需要延長LazyChoiceList和實施新的FormType,所以到目前爲止,我有:如何在Symfony 2.1的FormEvent中更新ChoiceType的值?

/** 
* A choice list for sorting choices. 
*/ 
class SortChoiceList extends LazyChoiceList 
{ 
    private $choices = array(); 

    public function getChoices() { 
     return $this->choices; 
    } 

    public function setChoices(array $choices) { 
     $this->choices = $choices; 
     return $this; 
    } 

    protected function loadChoiceList() { 
     return new SimpleChoiceList($this->choices); 
    } 
} 

/** 
* @FormType 
*/ 
class SortChoice extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder->getParent()->addEventListener(FormEvents::PRE_SET_DATA, function($event) use ($options) { 
      $options = (object) $options; 

      $list = $options->choice_list; 

      $data = $event->getData(); 

      if ($data->getLocation() && $data->getDistance()) { 
       $list->setChoices(array(
        '' => 'Distance', 
        'highest' => 'Highest rated', 
        'lowest' => 'Lowest rated' 
       )); 
      } else { 
       $list->setChoices(array(
        '' => 'Highest rated', 
        'lowest' => 'Lowest rated' 
       )); 
      } 
     }); 
    } 

    public function getParent() 
    { 
     return 'choice'; 
    } 

    public function getName() 
    { 
     return 'sort_choice'; 
    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array(
      'choice_list' => new SortChoiceList 
     )); 
    } 
} 

我試過這種方法對所有的可用的FormEvent的,但我沒有訪問數據(空值)或更新choice_list沒有效果,據我所知,因爲它已經被處理。

回答

1

原來我並不需要在所有定義一個新類型或LazyList和更好的做法是,直到我有數據,在我的主要形式,像這樣不加場:

$builder->addEventListener(FormEvents::PRE_BIND, function($event) use ($builder) { 
    $form = $event->getForm(); 
    $data = (object) array_merge(array('location' => null, 'distance' => null, 'sort_by' => null), $event->getData()); 

    if ($data->location && $data->distance) { 
     $choices = array(
      '' => 'Distance', 
      'highest' => 'Highest rated', 
      'lowest' => 'Lowest rated' 
     ); 
    } else { 
     $choices = array(
      '' => 'Highest rated', 
      'lowest' => 'Lowest rated' 
     ); 
    } 

    $form->add($builder->getFormFactory()->createNamed('sort_by', 'choice', $data->sort_by, array(
     'choices' => $choices, 
     'required' => false 
    ))); 
}); 

見:http://symfony.com/doc/master/cookbook/form/dynamic_form_generation.html

1

你讀過這個:http://symfony.com/doc/master/cookbook/form/dynamic_form_generation.html

的例子有:

if (!$data) return; 

而這是因爲這些事件似乎在窗體被構建時被多次觸發。我在您的發佈代碼中沒有看到相應的行。

+0

我已經看到,是的,事實上我在我的回答中引用了它,它在我的示例中有特徵,但在我的情況下,對於這種形式,空值永遠不會傳遞,所以爲了簡單。 – Steve 2012-08-13 10:10:34