Необходимо отправлять данные формы (название поля + значение) на email. Но не могу разобраться как подключить шаблоны твиг в сервисе.
Ошибка:
Attempted to call an undefined method named "render" of class "AppBundle\Helper\Notification".
// SomeController.php
...
if ($form->isSubmitted()) {
if ($form->isValid()) {
$this->get('app.send.notification')
->send('Заголовок', $form);
}
}
// services.yml
services:
app.send.notification:
class: AppBundle\Helper\Notification
arguments:
service: ["@service_container"]
<?php
// AppBundle\Helper\Notification
namespace AppBundle\Helper;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
class Notification {
/**
* admin email address
*/
const EMAIL_FROM = 'admin@examle.com';
/**
* my email address
*/
const EMAIL_TO = 'my@example.ru';
/*
* @var array
*/
protected $dataMail = [];
/**
* service container
*
* @var object
*/
protected $service;
/**
* init service
*
* @param object $service
* @return $this
*/
public function __construct($service) {
$this->service = $service;
return $this;
}
/**
* Send notification
*
* @param string $subject
* @param array $form
*/
public function send($subject, $form) {
$data_form = $form->all();
array_pop($data_form);
foreach ($data_form as $value) {
$label = $value->getConfig()
->getOption("label");
$data = $value->getData();
$res = ($data instanceof \DateTime) ? ($data->format('d.m.Y')) : $data;
$this->dataMail[$label] = $res;
try {
$message = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom(self::EMAIL_FROM)
->setTo(self::EMAIL_TO)
->setBody(
$this->render(
'Emails/request.html.twig', array('form' => $dataMail)
), 'text/plain');
$this->service->get('mailer')->send($message);
} catch (Swift_TransportException $e) {
return $e->getMessage();
} catch (Exception $e) {
return $e->getMessage();
}
}
}
// request.html.twig
{% for value in form %}
{{ value }}
{% endfor %}