Home > Software design >  Api-platform string given, must be type of Entity
Api-platform string given, must be type of Entity

Time:07-09

i have i guess simple problem, but i cant get it working properly:

Im getting this error: App\Entity\Commands::setServerID(): Argument #1 ($serverID) must be of type ?App\Entity\Servers, string given And when i try to do add new element via api-platform its working correctly:

enter image description here

And here is result:

enter image description here

But when i try to do it via postman or in my controller in symfony im getting error mentioned in begining:

        $commandDB = new Commands();
        $commandDB->setCommand($command);
        $commandDB->setStatusCode(1);
        $commandDB->setOutput("added to DB");
        $commandDB->setCreatedAt($date);
        $commandDB->setServerID($serverid);

My guess is that apiplatform was able to take '/api/servers/1' and understand that this is IRI and it is entity, and controller is not, but is there's any way to fix it?

Thanks

CodePudding user response:

The error says that you must pass in an entity, not an id. Do something like this:

Inject a ManagerRegistry instance into your controller

private ManagerRegistry $managerRegistry;

public function __construct(ManagerRegistry $managerRegistry)
{
    $this->managerRegistry = $managerRegistry;
}

Then get your Servers object and set it into the Commands entity

$server = $this->managerRegistry->getRepository(Servers::class)->find($serverid);
$commandDB->setServerID($server);

CodePudding user response:

Well then, i solved it with help of @Harvey Dent my main problem was to get object to pass it in setServerID(); Harvey suggested ManagerRegistry but i used EntityManagerInterface instead becouse it was not working properly for me(null response).

this is part of code that is working for me:

$server = $em->getRepository(Servers::class)->findOneBy(['id' => $serverid,])

Thanks again Harvey for idea!

  • Related