Home > Software design >  Add field if certain value is selected from ChoiceType
Add field if certain value is selected from ChoiceType

Time:10-26

I'm trying to add a new TextType field to my form after I choose a value from my ChoiceType. I have no clue what to do. I tried a bit, but it's not working how I want to.

The exception thrown is:

Typed property App\Model\Software::$productType must not be accessed before initialization

final class ProductType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('productType', ChoiceType::class, [
                'choices' => [
                    'Software' => 'software',
                    'Television' => 'television',
                    'Giftcard' => 'giftcard',
                    'Bitte wählen' => '',
                ],
            ])
            ->add('productNumber', TextType::class)
            ->add('title', TextType::class)
            ->add('submit', SubmitType::class);

        $builder->addEventListener(
            FormEvents::POST_SET_DATA,
            function (FormEvent $event)
            {
                $form = $event->getForm();
                $data = $event->getData();

                if ($data->productType === 'giftcard') {
                    $form->add('value', TextType::class);
                }
            }
        );
    }
}

I tried it already with different FormEvents.

CodePudding user response:

The error you have "Typed property App\Model\Software::$productType must not be accessed before initialization" is because in you entity 'App\Model\Software', the attribute 'productType' has a type "string" or whatever but is not initialised to null or empty string or ..., and in your listener you are trying to access that attribute ($data->productType)

try init your attribute to null or empty string

  • Related