PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 11, 2022

[FIXED] How can I resolve FormBuilder inside a service (Symfony4)?

 May 11, 2022     formbuilder, oop, php, service, symfony     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing