Search code examples
phpformssymfonysymfony-2.7

Symfony 2.7: Could not load type "Symfony\Component\Form\Extension\Core\Type\TextType"


I am working on an application based on Symfony 2.7. I have a custom form type containing the following code:

namespace MyCompany\AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Validator\Constraints\NotBlank;

class ContactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class,
                [
                    'attr'=>
                        [
                            'placeholder' => 'Your name'
                        ],
                    'constraints' =>
                        [
                            new NotBlank(['message' => 'Please provide your name'])
                        ]
                ]
            )
        ;
    }
...

... and when I load the form, I get the following InvalidArgumentException:

Could not load type "Symfony\Component\Form\Extension\Core\Type\TextType"

I have verified that the TextType class exists.

I tried using composer dump, and it didn't seem to help. In addition, I tried removing the vendor directory and redoing composer install, and that didn't help either.

What else can I try?


Solution

  • You can't use fully qualified class names to denote form types in Symfony v2.7 - that was added in v2.8. You need to denote your types by passing an instance instead:

    $builder
        ->add('name', new TextType(),
            [
                'attr'        =>
                    [
                        'placeholder' => 'Your name',
                    ],
                'constraints' =>
                    [
                        new NotBlank(['message' => 'Please provide your name']),
                    ],
            ]
        );
    

    Or by using the shorthand name e.g text:

    $builder
        ->add('name', 'text',
            [
                'attr'        =>
                    [
                        'placeholder' => 'Your name',
                    ],
                'constraints' =>
                    [
                        new NotBlank(['message' => 'Please provide your name']),
                    ],
            ]
        );
    

    Symfony v2.7 isn't maintained anymore though, so I'd highly recommend upgrading to at least v2.8