Reputation: 597
I needd to return a JsonResponse inside persist fuction.
this is an example of my DataPersister class, the goal it's return a JsonResponse, when i try, i get the error: The controller must return a \"Symfony\Component\HttpFoundation\Response\" object but it returned an object of type App\Entity\VerificationCodes.
<?php
// api/src/DataPersister/UsersDataPersister.php
namespace App\DataPersister;
use ApiPlatform\Core\DataPersister\DataPersisterInterface;
use App\Entity\Users;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
final class UsersDataPersister implements DataPersisterInterface
{
private $managerRegistry;
public function __construct(ManagerRegistry $managerRegistry)
{
$this->managerRegistry = $managerRegistry;
}
public function supports($data): bool
{
return $data instanceof Users;
}
public function persist($data){
$em = $this->managerRegistry->getManagerForClass(Users::class);
$user = new Users();
//Persist User with encode password
return $user;
return new JsonResponse(['response'=>'yes']);
}
public function remove($data)
{
throw new \RuntimeException('"remove" is not supported');
}
}
please help me or tell me what i can do, than you
Upvotes: 1
Views: 1228
Reputation: 21698
If you want that App\Entity\Users
class will be converted into a JSON you can implement JsonSerializable
inferface (is PHP native interface). This interface force you to implement the method jsonSerialized
that is automatically called when the object is converted to json (for example when you use json_encode($user);
.
Finally you can try with
class Users implements \JsonSerializable
{
public function jsonSerialize()
{
return []; // an array representation of your class
}
}
then you can ...
return new JsonResponse(json_encode($user));
or (maybe) ...
return new JsonResponse($user);
Upvotes: 2