Issue
I try to create a Form in my Service:
namespace App\Service;
class FormGenerator
{
public function createForm($slug,$request)
{
$item = new $EntityName();
$formBuilder = $this->createFormBuilder($item);
....
But I get the error message:
Attempted to call an undefined method named "createFormBuilder" of class "App\Service\FormGenerator".
Solution
The form builder instance is present in the AbstractController
(Where most of the controllers extend it). So that's why you are able to use $this->createFormBuilder()
. But in this case, you have created a separate service so you need to resolve the form builder yourself.
I'm not sure about how you would do it in Symfony but according to the documentation and this link you can typehint the form builder class and you will get the instance in your method. something like below
The code has been updated to import the FormBuilderInterface via constructor injection
use Symfony\Component\Form\FormBuilderInterface;
class FormGenerator
{
private $builder;
public function __construct(FormBuilderInterface $builder) {
$this->builder = $builder;
}
public function createForm($slug,$request)
{
$this->builder
->add('name')
->add('speciesCount')
->add('funFact')
}
}
Then you will have to resolve this class (FormGenerator
) via DI into your logic of choice preferably by type-hinting it in the constructor of the subscriber of this service class. Hope it makes a little more sense
Answered By - Shobi Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.