Thanks to visit codestin.com
Credit goes to github.com

Skip to content

TextType Field empty_data bug - Expected argument of type "string", "NULL" given. #29061

@dawsza

Description

@dawsza

The documentation for TextType form field says:

The default value is '' (the empty string).

https://symfony.com/doc/current/reference/forms/types/text.html#empty-data

But probably it isn't true because when we have entity:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\FooRepository")
 */
class Foo
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $stringField = 'default value to overwrite';

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getStringField(): ?string
    {
        return $this->stringField;
    }

    public function setStringField(string $stringField): self
    {
        $this->stringField = $stringField;

        return $this;
    }

the form:

namespace App\Form;

use App\Entity\Foo;
use http\Env\Request;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class FooType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('stringField', null, ['required' => false])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Foo::class,
        ]);
    }
}

and the controller like this:

namespace App\Controller;

use App\Form\FooType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class MainController extends AbstractController
{
    /**
     * @Route("/main", name="main")
     */
    public function index(Request $request)
    {
        $form = $this->createForm(FooType::class);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            dump($form->getData()->getStringField());
        }

        return $this->render('main/index.html.twig', [
            'controller_name' => 'MainController',
            'form' => $form->createView(),
        ]);
    }
}

Then is throw InvalidArgumentException by PropertyAccessor.php:

Expected argument of type "string", "NULL" given.

because $form->getData()->getStringField() is null instead empty string like default defined in documentation.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions