如何在 Symfony 表单中指定默认值

How do I specify default values in a Symfony form

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

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

如何通知 FormType 在持久化状态下使用默认值?我尝试的每件事似乎都表明它是其中之一,而不是两者兼而有之?

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 选项不好,因为:

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() 中或在将对象绑定到表单之前。

回答我自己的问题并避免将来对任何人造成混淆:

$quoteItem = new QuoteItem();

// THIS LINE WAS MISSING
$quoteItem->setQuoteFlight(new QuoteFlight()); 

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

如果没有添加行,则在创建期间呈现表单时,QuoteFlight 实体为 NULL。