4

How do i set, when i create a thread, that the message is read by the creator of the thread?

I have this portion 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 in the last line, in the database the value of is_read is set to 0, when the sender should be set to 1. So, i need to set the author to is read when he send the message.

Anyone? :)

Nico
  • 1,241
  • 1
  • 13
  • 29
  • what entity's propertie is `is_read`? – cheesemacfly Jun 11 '13 at 18:27
  • is the message_metadata, but i cannot set it directly from message, there is a method for $message->setIsreadbyParticipant, but this method search in the database for the metadata and then set it. I want to set it before the entity persists. – Nico Jun 11 '13 at 18:50

1 Answers1

6

Message metadata doesn't exist until message is persisted. That's why you have to set read status after saving message to database.

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

<?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

gregory90
  • 569
  • 5
  • 5