Unknown Entity namespace alias 'entity name'

Viewed 209

I looked at the similar questions but couldn't find a solution to my problem.

In my project symfony, I get the information from my database with this code

$backup = $this->getDoctrine()->getRepository(LocalInformations::class)->findByRegion('west');

But only, the LocalInformation entity, its region attribute and the value of this attribute 'west', are variable and obtained from an ajax request. So I have

$value = trim($data['value']);
$property = trim($data['property']);
$entity = trim($data['entity']);
 
$class = ucfirst($entity) . '::class';
$findByProperty = 'findBy' . ucfirst($property);
 
dump($class);
dump($property);
dump($value);
 
$backup = $this->getDoctrine()->getRepository($class)->$findByProperty($value);

I am getting the following error: 'Unknown Entity namespace alias 'LocalInformations'.

And when I comment the last line, the dumps give me "LocalInformations::class", "region", "west"

I noticed the first problem, I have

$backup = $this->getDoctrine()->getRepository("LocalInformations::class")->findByRegion('west');

instead of

$backup = $this->getDoctrine()->getRepository(LocalInformations::class)->findByRegion('west');

"LocalInformations::class" is a string not a class name. Now the problem becomes, how do you remove quotes around a string?

1 Answers

The ::class wouldn't be so helpful since you would need to have the class in your use statements for this to work. The ::class would normally return the FQCN so why not using it directly.

$class = sprintf('\App\Entity\%s', ucfirst($entity));
$findByProperty = 'findBy' . ucfirst($property);
 
$backup = $this->getDoctrine()->getRepository($class)->$findByProperty($value);

Make sure to use the proper namespace for your entities...

Also, make sure to validate that the user should be able to request the entity. Never trust user input as it can be forged easily in most cases.

Related