我想我可能需要扩展 LazyChoiceList 并实现一个新的 FormType,到目前为止我有:
/**
* 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 无效,据我所知,因为它已经处理。