我在SF4上挣扎,想做一件简单的事情。
注册用户后,我正在尝试根据用户区域设置(法语或英语)发送电子邮件。
使用$ subject,在接收人的电子邮件中设置了$ body文本。
现在,我想对主题和正文进行翻译。
肯定有些东西我在这里不能很好地控制,但是我尝试了SF文档here中描述的内容,它在控制器内部工作,但在我的订户内部工作。
我有一个很明显的错误,我不明白:(
有任何指导我的建议吗?
我知道,对于身体,我可以渲染一个树枝模板,但不能对电子邮件的主题进行渲染。
这是我的订户代码:(我不评论测试时的评论)
namespace App\EventSubscriber;
use App\Entity\User;
use App\Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
//use Symfony\Component\Translation\TranslatorInterface;
class RegistrationNotifySubscriber implements EventSubscriberInterface
{
private $mailer;
private $sender;
public function __construct(\Swift_Mailer $mailer, $sender)
{
$this->mailer = $mailer;
$this->sender = $sender;
}
public static function getSubscribedEvents(): array
{
return [
Events::USER_REGISTERED => 'onUserRegistrated',
];
}
public function onUserRegistrated(GenericEvent $event)
{
/** @var User $user */
$user = $event->getSubject();
//$subject = $translator->trans('registration.email.subject', array(), 'messages'); -- , TranslatorInterface $translator
$subject = "Your account for a product demonstration";
$body = "Hello, Your account has been created...";
$message = (new \Swift_Message())
->setSubject($subject)
->setTo($user->getUsername())
->setFrom($this->sender)
->setBody($body, 'text/html')
;
$this->mailer->send($message);
}
}
谢谢。
Fab
答案 0 :(得分:2)
您需要将Translator注入您的订户。为此,您需要
service.yml
文件来传递它// # service.yml #
//AppBundle\EventSubscriber\RegistrationNotifySubscriber:
// arguments: ['@translator', '@mailer']
// public: true
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Translation\TranslatorInterface;
class RegistrationNotifySubscriber implements EventSubscriberInterface
{
private $mailer;
private $sender;
private $translator;
public function __construct(TranslatorInterface $translator, \Swift_Mailer $mailer, $sender)
{
$this->mailer = $mailer;
$this->sender = $sender;
$this->translator = $translator;
}
public static function getSubscribedEvents(): array
{
return [
Events::USER_REGISTERED => 'onUserRegistrated',
];
}
public function onUserRegistrated(GenericEvent $event)
{
/** @var User $user */
$user = $event->getSubject();
$subject = $this->translator->trans('registration.email.subject', array(), 'messages');
$subject = "Your account for a product demonstration";
$body = "Hello, Your account has been created...";
$message = (new \Swift_Message())
->setSubject($subject)
->setTo($user->getUsername())
->setFrom($this->sender)
->setBody($body, 'text/html')
;
$this->mailer->send($message);
}
}