How to make a symfony abstract type with different objects?

by cali_green , in category: PHP Frameworks , 10 months ago

How to make a symfony abstract type with different objects?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 10 months ago

@cali_green 

To create an abstract type with different objects in Symfony, you need to follow these steps:

  1. Create an abstract form type: Create a new class extending AbstractType within your Symfony project, for example, AbstractObjectType. Override the configureOptions method and set the required options for the form. Implement the getParent method and return TextType::class, which is a basic form type that you can modify based on your needs. This abstract type will serve as the base for your specific object forms.
  2. Create specific object form types: Create a new form type class for each specific object form you want to create, extending the AbstractObjectType you defined in step 1. Override the configureOptions method to set any specific options required for the object form. Implement the getBlockPrefix method to return a unique prefix for each specific object form type.


Here is an example of how the code might look:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentOptionsResolverOptionsResolver;

abstract class AbstractObjectType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'class' => null, // Specific option for each object form
        ]);
    }

    public function getParent()
    {
        return TextType::class;
    }
}


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use SymfonyComponentOptionsResolverOptionsResolver;

class Object1Type extends AbstractObjectType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults([
            'class' => Object1::class,
        ]);
    }

    public function getBlockPrefix()
    {
        return 'object1';
    }
}


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use SymfonyComponentOptionsResolverOptionsResolver;

class Object2Type extends AbstractObjectType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults([
            'class' => Object2::class,
        ]);
    }

    public function getBlockPrefix()
    {
        return 'object2';
    }
}


Now, you can use the Object1Type and Object2Type form types in your forms, which will inherit the basic behavior defined in the AbstractObjectType, while allowing you to configure specific options for each object type.