peace_love
peace_love

Reputation: 6461

How can I replace a variable in my Symfony 4 function?

I created a function in my Controller that is working with the Entity Members. What I want to do now is make the function flexible, so that I can use it for all my other entities too. The name of the entity should therefore be dependent on the slug. So in this case the slug = members:

/**
  * @Route("/pages/{slug}/forms", name="forms", methods={"POST", "GET"})
  */

  public function form($slug, Request $request){
     $item = new Members();    
     $item= $this->getDoctrine()->getRepository(Members::class)->find($id);
 }

So what I am trying to do is replace the entityname with the slug:

/**
  * @Route("/pages/{slug}/forms", name="forms", methods={"POST", "GET"})
  */

  public function form($slug, Request $request){
     $item = new $slug();    
     $item= $this->getDoctrine()->getRepository($slug::class)->find($id);
 }

But I get an error message:

Attempted to load class "members" from the global namespace. Did you forget a "use" statement?

Does this has something to do with the uppercase/lowercase of the slug?

Upvotes: 0

Views: 239

Answers (1)

delboy1978uk
delboy1978uk

Reputation: 12355

All our entities are probably in something like src\Entity, and depending how you set up each entity will be in some namespace or other, like App\Entity.

Also, members in your slug is in lowercase, but your class begins with a captital however.

All you need to do is make sure members becomes Members, and where you say

$item = new $slug()

You probably want:

$fullClassName = 'App\\Entity\\' . ucwords($slug);
$item = new $fullClassName()`

Give it a try and let me know how you get on!

Upvotes: 5

Related Questions