php symfony2 - 从数据库中添加选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15836875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:03:40  来源:igfitidea点击:

symfony2 - adding choices from database

phpformssymfonydrop-down-menupopulate

提问by Robbo_UK

I am looking to populate a choice box in symfony2 with values from a custom query. I have tried to simplify as much as possible.

我希望用自定义查询中的值填充 symfony2 中的选择框。我试图尽可能地简化。

Controller

控制器

class PageController extends Controller
{

    public function indexAction()
    {
      $fields = $this->get('fields');
      $countries =  $fields->getCountries(); // returns a array of countries e.g. array('UK', 'France', 'etc')
      $routeSetup = new RouteSetup(); // this is the entity
      $routeSetup->setCountries($countries); // sets the array of countries

      $chooseRouteForm = $this->createForm(new ChooseRouteForm(), $routeSetup);


      return $this->render('ExampleBundle:Page:index.html.twig', array(
        'form' => $chooseRouteForm->createView()
      ));

    }
}

ChooseRouteForm

选择路线表格

class ChooseRouteForm extends AbstractType
{

  public function buildForm(FormBuilderInterface $builder, array $options)
  {

    // errors... ideally I want this to fetch the items from the $routeSetup object 
    $builder->add('countries', 'choice', array(
      'choices' => $this->routeSetup->getCountries()
    ));

  }

  public function getName()
  {
    return 'choose_route';
  }
}

回答by qooplmao

You could pass the choices to your form using..

您可以使用..将选项传递给您的表单。

$chooseRouteForm = $this->createForm(new ChooseRouteForm($routeSetup), $routeSetup);

Then in your form..

然后以你的形式..

private $countries;

public function __construct(RouteSetup $routeSetup)
{
    $this->countries = $routeSetup->getCountries();
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('countries', 'choice', array(
        'choices' => $this->countries,
    ));
}

Updated (and improved) for 2.8+

更新(和改进)为 2.8+

Firstly you don't really need to pass in the countries as part of the route object unless they are going to be stored in the DB.

首先,除非它们将存储在数据库中,否则您实际上不需要将国家作为路线对象的一部分传递。

If storing the available countries in the DB then you can use an event listener. If not (or if you don't want to use a listener) you can add the countries in the options area.

如果将可用国家/地区存储在数据库中,则可以使用事件侦听器。如果没有(或者如果您不想使用侦听器),您可以在选项区域中添加国家/地区。

Using Options

使用选项

In the controller..

在控制器..

$chooseRouteForm = $this->createForm(
    ChooseRouteForm::class,
    // Or the full class name if using < php 5.5
    $routeSetup,
    array('countries' => $fields->getCountries())
);

And in your form..

并以你的形式..

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('countries', 'choice', array(
        'choices' => $options['countries'],
    ));
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver
        ->setDefault('countries', null)
        ->setRequired('countries')
        ->setAllowedTypes('countries', array('array'))
    ;
}

Using A Listener(If the countries array is available in the model)

使用侦听器(如果模型中的国家/地区数组可用)

In the controller..

在控制器..

$chooseRouteForm = $this->createForm(
    ChooseRouteForm::class,
    // Or the full class name if using < php 5.5
    $routeSetup
);

And in your form..

并以你的形式..

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
            $form = $event->getForm();
            /** @var RouteSetup $routeSetup */
            $routeSetup = $event->getData();

            if (null === $routeSetup) {
                throw new \Exception('RouteSetup must be injected into form');
            }

            $form
                ->add('countries', 'choice', array(
                    'choices' => $routeSetup->getCountries(),
                ))
            ;
        })
    ;
}

回答by Loial

I can't comment or downvote yet, so I'll just reply to Qoop's answer here: What you proposed will work unless you start using your form type class as a service. You should generally avoid adding data to your form type object through constructor.

我还不能发表评论或否决票,所以我将在这里回复 Qoop 的回答:除非您开始将表单类型类用作服务,否则您提出的建议将起作用。 您通常应该避免通过构造函数向表单类型对象添加数据。

Think of form typeclass like a Class- it's a kind of description of your form. When you make an instance of form(by building it) you get the Objectof form that is build by the description in form type and then filled with data.

表单类型类视为- 它是对表单的一种描述。当您创建表单实例(通过构建它)时,您将获得由表单类型中的描述构建的表单对象,然后填充数据。

Take a look at this: http://www.youtube.com/watch?v=JAX13g5orwo- this situation is described around 31 minute of the presentaion.

看看这个:http: //www.youtube.com/watch?v=JAX13g5orwo- 这种情况在演示的 31 分钟左右描述。

You should use form event FormEvents::PRE_SET_DATA and manipulate fields when the form is injected with data. See: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#customizing-your-form-based-on-the-underlying-data

您应该使用表单事件 FormEvents::PRE_SET_DATA 并在表单注入数据时操作字段。请参阅:http: //symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#customizing-your-form-b​​ased-on-the-underlying-data