Answer the question
In order to leave comments, you need to log in
symfony2. How to address the mailer correctly?
Hello dear experts!
Please tell me what I'm doing wrong (I'm a noob, don't swear). Here is a piece of code:
public function showAction(Request $request)
{
$dataMail = [
'name' => '',
'subject' => '',
'email' => '',
'message' => '',
];
$form = $this->formFactory->create('send_mail_form', $dataMail);
if ($request->getMethod() == 'POST') {
$form->bind($request);
$dataMail = $form->getData();
$message = \Swift_Message::newInstance()
->setSubject($dataMail['subject'])
->setFrom($dataMail['email'])
->setTo('[email protected]')
->setBody($this->renderView('AllergoMainBundle:Service:body_mail.html.twig', [
'name' => $dataMail['name'],
'message' => $dataMail['message'],
]));
$this->get('mailer')->send($message);
}
return [
'form' => $form->createView(),
];
}
Error: Call to a member function get() on a non-object
Answer the question
In order to leave comments, you need to log in
Everything should work if the class inherits from the symphony controller
In addition to shoomyst 's answer , if you don't want to inherit from Symphony's controller, implement the ContainerAwareInterface interface for your controller and fetch from the container yourself. You can also connect a trait.
class MyController implements ContainerAwareInterface
{
use \Symfony\Component\DependencyInjection\ContainerAwareTrait;
function myAction(Request $request) {
// ...
$this->container->get('mailer')->send($message);
}
}
Use Dependency Injection.
Get an object of the Mailer class in the constructor.
You forgot at the beginning of the file, where the class name is to indicate inheritance from the symphonic class extends Controller
It is done like this
class YourController extends Controller
{
public function showAction(Request $request) {
// your actions
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question