FOSMessageBundle in Symfony2

How to set when I create a stream so that the message is read by the stream creator?

I have this piece of code

$composer = $this->get('fos_message.composer'); $message = $composer->newThread() ->setSender($this->getUser()) ->setSubject('myThread') ->setBody($request->get('createThread')['my_thread']); $sender = $this->get('fos_message.sender'); $sender->send($message); 

But when I send the message on the last line, the database value is_read is set to 0, when the sender should be set to 1. Thus, I need to configure the author to read when he sends the message.

Anyone? :)

+4
source share
1 answer

Message metadata does not exist until the message is saved. This is why you need to set the read status after saving the message to the database.

The easiest way to do this is to register an EventSubscriber. Working code example:

 <?php namespace Acme\DemoBundle\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use FOS\MessageBundle\Event\MessageEvent; use FOS\MessageBundle\Event\FOSMessageEvents as Event; use FOS\MessageBundle\ModelManager\MessageManagerInterface; class MessageSendSubscriber implements EventSubscriberInterface { private $messageManager; public function __construct(MessageManagerInterface $messageManager) { $this->messageManager = $messageManager; } public static function getSubscribedEvents() { return array( Event::POST_SEND => 'markAsReadBySender' ); } public function markAsReadBySender(MessageEvent $event) { $message = $event->getMessage(); $sender = $message->getSender(); $this->messageManager->markAsReadByParticipant($message, $sender); $this->messageManager->saveMessage($message); } } 

In services.yml:

 message_send_listener: class: Acme\DemoBundle\EventListener\MessageSendSubscriber arguments: [@fos_message.message_manager] tags: - { name: kernel.event_subscriber } 

Here you can check what events you can subscribe to: https://github.com/FriendsOfSymfony/FOSMessageBundle/blob/master/Event/FOSMessageEvents.php

+6
source

Source: https://habr.com/ru/post/1485659/


All Articles