[英]Symfony3.4 - Pre filled field on POST_SUBMIT Event
我有一個帶有聯系人列表的表單。 我想在提交后顯示所選聯系人值字段“名字”。 我的問題是該字段出現但我無法設置好的數據,該字段始終保持為空。
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('contacts', ChoiceType::class, [
'label' => 'Contact',
'placeholder' => 'Choose a contact',
'choices' => $this->getContacts(),
'mapped' => false,
])
->setMethod('POST')
;
$builder->get('contacts')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$contactId = $event->getData();
$parentForm = $event->getForm()->getParent();
$contactEntity = $exampleEm->getrepository(Contact::class)->find($contactId);
$firstName = $contactEntity->getFirstName();
// where can I set the 'contactFirstname' data ?
$parentForm
->add('contactFirstname', TextType::class, [
'label' => 'First name',
]);
})
;
}
如何輸入正確的數據以使字段顯示為預填?
編輯:我找到了一個方法,但並不可怕:
$parentForm
->add('contactFirstname', TextType::class, [
'label' => 'First name',
'empty_data' => $firstName,
]);
( 'data' => $firstName
對我不起作用。)
$parentForm->get('contactFirstname')->setData($firstName);
也不起作用
你不能簡單地設置TextType字段的'data'選項嗎?
// ...
$contactEntity = $exampleEm->getrepository(Contact::class)->find($contactId);
$firstName = $contactEntity->getFirstName();
$parentForm
->add('contactFirstname', TextType::class, [
'label' => 'First name',
'data' => $firstname //here?
]);
編輯:
根據github上提交的這篇文章 ,需要提交表單字段以便更改數據。
在他的一個解決方案中,他像你一樣使用“empty_data”。
在另一個中,他將該字段添加到構建器中。 用顯示隱藏它:“無”; 直到數據提交。
文檔說
還可以直接修改未映射字段的數據:
$form->get('agreeTerms')->setData(true);
試試這個:
$parentForm
->add('contactFirstname', TextType::class, [
'label' => 'First name',
]);
$parentForm->get('contactFirstname')->setData($firstName);
也許在創建表單之前使用setter?
https://symfony.com/doc/current/forms.html#building-the-form
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.