我想我可能需要延長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沒有效果,據我所知,因爲它已經被處理。
我已經看到,是的,事實上我在我的回答中引用了它,它在我的示例中有特徵,但在我的情況下,對於這種形式,空值永遠不會傳遞,所以爲了簡單。 – Steve 2012-08-13 10:10:34