symfony - 在表单中选择选项下拉列表

标签 symfony symfony-forms dropdown dropdownchoice

我想从 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/

相关文章:

javascript - 更改另一个日期类型字段时如何修改日期类型字段

Symfony Forms CollectionType,按 ID 索引

php - 使用自定义查询生成器的多对多实体的 Symfony 表单

python - 在 Python 中使用 XLWings 创建下拉列表

reactjs - 在reactJS中的react-select中使用不同的键来搜索而不是值或标签

php - websocket.ERROR:发生连接错误警告:SessionHandler::read(): session 未激活

javascript - 从 Base64 下载 Javascript(或 Symfony)的 CSV 文件

javascript - 当您将鼠标悬停在图像的特定区域上时如何显示下拉菜单? (HTML, CSS)

使用 liip imagine_filter 的 Symfony 5 Mailer 嵌入图像

Symfony 表单 : how to include in the Doctrine entity form a form for a Doctrine embeddable used by the entity itself