Answer the question
In order to leave comments, you need to log in
Symfony2: How to use twig templates in service container?
It is necessary to send form data (field name + value) to email. But I can’t figure out how to connect twig templates in the service.
Mistake:
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 = '[email protected]';
/**
* my email address
*/
const EMAIL_TO = '[email protected]';
/*
* @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 %}
Answer the question
In order to leave comments, you need to log in
You need to pass a template engine to the service, i.e.
app.send.notification:
class: AppBundle\Helper\Notification
arguments:
service: ["@templating"]
public function __construct($templating) { //Класс по-моему Twig_Engine, могу ошибаться
$this->templating = $templating;
}
$this->templating->render(...);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question