'How to display data received on FormEvents:pre_set_data Symfony
I'm trying to display data received on endpoint in twig.
{
$builder
->add('refundType', ChoiceType::class, [
'label' => 'form.transaction.refund.refundType',
'choices' => [
'Total' => 'total',
'Partial' => 'partial',
],
'data' => 'total',
'expanded' => true,
'multiple' => false,
])
->add('submerchants', CollectionType::class, [
'entry_type' => SubmerchantSplitsEmbeddedForm::class,
]);
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
/** @var SubmerchantSplit|null $data */
$data = $event->getData();
if(!$data['data']['submerchantSplits']) {
return;
}
$this->getSubmerchantSplits($event->getForm(), $data['data']['submerchantSplits']);
});
}
public function configureOptions(OptionsResolver $resolver)
{
}
private function getSubmerchantSplits(FormInterface $form, mixed $submerchantSplits)
{
dd($submerchantSplits);
}
When I try dd($submerchantSplits) I get a response with all data that I need, but I don't know how to associate keys of that array with my Model Class(SubmerchantSplit which is in the CollectionType) so I can display it in twig.
My SubmerchantSplitsEmbeddedForm looks like that:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, [
'label' => 'form.common.labels.name',
])
->add('amount', NumberType::class, [
'label' => 'page.transaction.settlement.show.submerchant_amount',
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => SubmerchantSplit::class,
]);
}
And this is my Model class (SubmerchantSplit)
{
protected ?string $name;
protected ?string $amount;
public function __construct()
{
}
/**
* @return string|null
*/
public function getName(): ?string
{
return $this->name;
}
/**
* @param string|null $name
*/
public function setName(?string $name): void
{
$this->name = $name;
}
/**
* @return string|null
*/
public function getAmount(): ?string
{
return $this->amount;
}
/**
* @param string|null $amount
*/
public function setAmount(?string $amount): void
{
$this->amount = $amount;
}
}
If I try to use foreach loop in twig, it doesn't show me name & amount because I don't know how to map array. Can someone help me with that?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
