Search code examples
phpformssymfonysymfony7

Symfony 7 How to transform FormType all fields into concatenated string


I have a custom FormType called EffectType created as below and this FormType is used in another FormType as a ->add('effect', EffectType::class) and I would like to transform all the data from the EffectType (action, element and effect_str) into a string to persist the result in the database.

class EffectType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {

        $builder
            ->add('action', ChoiceType::class, [
                'choices' => [
                    'Test' => [
                        'Take'=> 'Take',
                        'Ok'=> 'Ok'
                    ]
                ]
            ])
            ->add('element', ChoiceType::class, [
                'choices' => [
                    'Other' => [
                        'Test'=>'Test',
                    ]
                ]
            ])
            ->add('effect_str', TextType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'project' => null
        ]);
    }

    public function getBlockPrefix(): string
    {
        return 'effect';
    }
}

For more context, this EffectType has the goal to format strings like If {action} {element} Then {effect_str}

I tried to use the DataTransformers but I don't really know how to deal with them. Do I have to add it to the parent form or should I use it on the EffectType form ?

I also tried to find inspiration on the DateType but this is a really complex FormType and as I don't really understand the DataTransformers flow it was unsuccessful.


Solution

  • I retried to add a DataTransformer in the EffectType and it worked perfectly. I don't know why it was not working earlier