如何在 Symfony 表单中指定默认值 [英] How do I specify default values in a Symfony form

查看:25
本文介绍了如何在 Symfony 表单中指定默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在表单中指定一个默认值,因此在创建实体时,表单字段有一个值(非 null 或空).然而,当实体被编辑时,它显然应该显示存储的值而不是默认值.

I am trying to specify a default value in a form so when creating an entity the form field has a value (not null or empty). However when the entity is being edited it should obviously show the stored value and not the default.

我的实体将自身初始化为构造的一部分 - 因此当实体是新的且尚未持久化时,应设置这些值.

My entity initializes itself as part of the construction - so when an entity is new and not yet persisted these values should be set.

如何通知 FormType 在持久状态上使用默认值?我尝试的一切似乎都表明它是一个或另一个而不是两者?

How do I inform the FormType to use the default value over the persisted state? Everything I try seems to suggest it's one or the other not both?

Symfony 3.2+ 是怎么做的???

How is this done Symfony 3.2+???

编辑|

控制器:

public function newAction (Request $request)
{
    $quoteItem = new QuoteItem();

    $form = $this->createForm('UniflyteBundle\Form\QuoteItemType', $quoteItem, ['allow_extra_fields' => true]);
    $form->add('QuoteFlight', QuoteFlightType::class);
}

表格类型:

public function configureOptions (OptionsResolver $resolver)
{
    $resolver->setDefaults([
      //'data' => new \UniflyteBundle\Entity\QuoteFlight()
      'data_class' => QuoteFlight::class
    ]);
}


public function buildForm (FormBuilderInterface $builder, array $options)
{
      $builder
      ->add('specMajorSetupCharge', null, [
        //'empty_data' => QuoteFlight::SPEC_MAJOR_SETUP_CHARGE,
        'data'  => QuoteFlight::SPEC_MAJOR_SETUP_CHARGE,
        'label' => '* Setups Charge'
      ])
      // ...
}

推荐答案

http://symfony.com/doc/current/components/form.html#setting-default-values

如果您需要使用一些默认值加载表单(或者您正在构建编辑"表单),只需在创建表单构建器时传入默认数据即可.

If you need your form to load with some default values (or you're building an "edit" form), simply pass in the default data when creating your form builder.

$quoteItem = new QuoteItem();
$quoteItem->getQuoteFlight()->setSpecMajorSetupCharge(QuoteFlight::SPEC_MAJOR_SETUP_CHARGE).

$form = $this->createForm(QuoteItemType::class, $quoteItem);
// ...

使用 data 选项不好,因为:

Using data option is no good, because:

http://symfony.com/doc/current/reference/forms/types/form.html#data

数据选项在渲染时始终覆盖从域数据(对象)中获取的值.这意味着当表单编辑一个已经持久化的对象时,对象值也会被覆盖,导致它在提交表单时丢失它的持久化值.

The data option always overrides the value taken from the domain data (object) when rendering. This means the object value is also overriden when the form edits an already persisted object, causing it to lose it's persisted value when the form is submitted.

因此,建议在初始化时在带下划线的对象中显式设置数据,在 __constructor() 中或在将对象绑定到表单之前.

So the recomendation is to set explicitly the data in the underlined object on initialization, either in __constructor() or before bind the object to the form.

这篇关于如何在 Symfony 表单中指定默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆