'Call to a member function createView() on null

I am using symfony 5, within my Controller I have this :

$devisFrais = $devisRepository->getDevisPosteFDFrais($idDevis);
$formFrais = $this->createForm(DevisDisciplineQualifType::class, $devisFrais, [
        'AT' => $AtNotAt,
         'type' => 'FRAIS'
        ]);
return $this->render('devis.html.twig', [
        'formFrais' => $formFrais->createView(),
    ]);

As $devisFrais is Null so formFrais is Null. I can't create a form because I have this error : "Call to a member function createView() on null".

Is it possible to create a blank form, in this case how to manage it within the Twig



Solution 1:[1]

You are getting an error that your variable $formFrais is null.

What you need to do is to simply check your value for being null / empty, with a ternary operator, and if it is give it is, execute the method, and if not, implement whatever logic you need after the ":".

You can do it in the Controller, no need to do any manipulation at the level of twig.

The basic logic is:

//...
return $this->render('devis.html.twig', [
    'formFrais' => $formFrais ?  $formFrais->createView() : $formFrais = "some_value",
]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dennis Kozevnikoff