php - why it gives null to author_id in the same insert it is fetched by AuthorSubscriber

I am new tosymfony4
, I have two tablesuser
andcomment
and how between them aManyToOne
relation, it means there isauthor_id
incomment
table, I created a SubscriberAuthorSubscriber.php
to get user id calledauthor_id
to insertauthor_id
automatically when persisting acomment
, but when I use postman and execute queryhttp://127.0.0.1:8000/api/comments
it is persistcomment
but it gives null to author_id.
data postman
{
"content": "my new content for postman",
"published": "2021-01-09T16:40:21+00:00",
"post": "/api/posts/728"
}
**AuthorSubscriber.php**
<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Post;
class AuthorSubscriber implements EventSubscriberInterface
{
public $myToken;
public function __construct(TokenStorageInterface $myToken)
{
$this->myToken = $myToken;
}
public function getUserFromToken(GetResponseForControllerResultEvent $event)
{
$entity = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if(($entity instanceof Post || $entity instanceof Comment) && $method == Request::METHOD_POST) {
$author = $this->myToken->getToken()->getUser();
$entity->setAuthor($author);
}
}
public static function getSubscribedEvents()
{
return [
'kernel.view' => ['getUserFromToken', EventPriorities::PRE_WRITE],
];
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: string literal contains an unescaped line break
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.