ayoub_007
ayoub_007

Reputation: 63

Symfony 4 : Call to a member function get() on null

class EtudiantController extends AbstractController
{

    private $etudiant ;
    private  $form ;

    public function  __construct()
    {
        $this->etudiant = new Etudiant();
        $this->form = $this->createForm(EtudiantType::class, new Etudiant());

    }
}

** i'v got an error when instantiate a form in a constructor using the createForm() function **enter image description here

Upvotes: 0

Views: 2992

Answers (1)

Cerad
Cerad

Reputation: 48865

Here is the wrong way to solve your problem:

class EtudiantController extends AbstractController
{
    private $form;

    public function __construct(FormFactoryInterface $formFactory)
    {
        $this->form = $formFactory->create(TextType::class, new Etudiant());
    }
}

I say it is wrong (even though it will work) because creating things like forms really should be done in individual controller actions, not hidden in the constructor. You might be trying to apply Dont Repeat Yourself (DRY) but in cases like this, Don't Confuse Your Future Self takes precedence.

And as far as why injecting the form factory is necessary, I would once again urge you to look at the Symfony source code for AbstractController as well as ControllerTrait. Understanding how dependency injection works is critical to being able to effectively use the framework.

Upvotes: 1

Related Questions