如何在symfony中设置所选选项?

时间:2019-02-16 12:19:14

标签: html twig symfony-forms

这是我的表格:

{
    $builder
        ->add('price', ChoiceType::class, [
            'label' => false,
            'required' => false,
            'choices' => [
              '0 - 1000 €' => 1,
              '1000 - 2000 €' => 2,
              '2000 - ∞' => 3,
            ],
            'attr' => [
                'class' => 'main-dropdown',
            ],
        ])
    ;
}

那么如何在树枝上传递选定的值?有人可以给个建议吗?

1 个答案:

答案 0 :(得分:0)

我认为您可以单独构建表单。使用此方法,您可以在需要的任何地方使用表单。

例如,它是您的表格

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;///To use this field, you must add ChoiceType in form.


    class yournameFormType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
           $builder
            ->add('price', ChoiceType::class, [
                'label' => false,
                'required' => false,
                'choices' => [
                  '0 - 1000 €' => 1,
                  '1000 - 2000 €' => 2,
                  '2000 - ∞' => 3,
                ],
                'attr' => [
                    'class' => 'main-dropdown',
                ],
            ])
        ;
        }
    }

您可以在控制器中使用此表单,例如下面的示例

使用AppBundle \ Form \ yournameFormType;

public function newAction()
{
    $YourEntityName = ...;
    $form = $this->createForm(yournameFormType ::class, $YourEntityName );

    // ...
  return $this->render('@App/YourNameTwig.html.twig', array(
            'form' => $form->createView()

        ));
}

最后使用树枝文件中的表格

  {{ form_start(form) }}
  .
  .
  {{ form_widget(form.price) }}
  .
  .
  .
  {{ form_end(form) }}

Read more about this