Page 1 of 1

Fehlende Daten nach dem Selbst-Update eines benutzerdefinierten Symfony-Untertyps

Posted: 19 Aug 2025, 16:31
by Anonymous
In Symfony versuche ich, einen auf EntityType basierenden Typ zu erstellen. Die Idee ist, ein EntityType -Feld zu haben, dessen Optionen über AJAX geladen werden (unter Verwendung der Selectize -Bibliothek). Sobald eine Option ausgewählt wurde, muss ich sie dynamisch zu meinem Typ hinzufügen. Dazu verwende ich ein EventListener unter FormEvents :: post_submit , um mein Feld mit der Option zu aktualisieren. Leider ist das Feld nicht mehr in $ form-> getData () nach dem Senden vorhanden.
Mein Typ:

Code: Select all

class ClientEntityType extends AbstractType
{
public function __construct(
private readonly ClientsRepository $clientsRepository,
private readonly RouterInterface $router,
) {
}

public function getParent(): string
{
return EntityType::class;
}

public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults($this->getOptions());
}

public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event): void {
$data = $event->getData();
$form = $event->getForm();

$options = $this->getOptions();

if ($data) {
$client = $this->clientsRepository->find($data);

$choices = [];
$choices[(string) $client] = $client;

$options['choices'] = $choices;
$options['data'] = $client;
}

$form->getParent()->add(
$form->getName(),
self::class,
$options
);
});
}

private function getOptions(): array
{
return [
'class' => Clients::class,
'label' => 'Client',
'required' => false,
'attr' => [
'class' => 'clientSelect',
'data-search-url' => $this->router->generate('admin_client_search'),
],
'placeholder' => 'Choisir une société',
'choices' => [],
];
}
}
< /code>
Mein Formulartyp: < /p>
class InvoiceListType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
// ...
->add('client', ClientEntityType::class);
}
}
< /code>
Mein Controller: < /p>
$form = $this->createForm(InvoiceListType::class, $data);

if (
$form->handleRequest($request)->isSubmitted()
&& $form->isValid()
) {
$data = $form->getData();

$data['client'] // Is missing!

// But I get the value with:
$form->get('client')->getData();
}