我想从 Controller 的下拉列表中选择一个选项。我正在尝试使用以下代码:
$form = $this->createForm(new SearchAdvancedType());
$form->get('option')->setData($session->get('option'));
但它在下拉列表中没有执行任何操作。页面加载时未选择任何内容。
要检查该值是否设置正确,我使用以下方法打印它:
$form->get('brand')->Data();
结果是一个数字(它会根据我之前在下拉列表中选择的内容而变化)。
我需要知道如何正确选择下拉列表的值。
最佳答案
要预设一个选择选项,我会将值传递到表单中。
class MyFormType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', 'choice', [
'required' => true,
'choices' => ['yes' => 'Yes', 'no' => 'No'],
'data' => $options['select_option']
])
;
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => null,
'select_option' => null
));
}
/**
* @return string
*/
public function getName()
{
return 'my_form';
}
}
然后在你的 Controller 中,传入值;
$form = $this->createForm(new MyFormType(), null, ['select_option' => 'no');
关于symfony - 在表单中选择选项下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33955144/