Search code examples
phpemailsymfonyswiftmailer

Attempted to call an undefined method named "getRequest" of class . Sendind e-mail in SwiftMailer Symfony


I'm trying to sen an e-mail by SwiftMailer in Symfony 3. I'm going through that tutorial: http://tutorial.symblog.co.uk/docs/validators-and-forms.html#sending-the-email and I've got the problem in "Creating the form in the controller" : "Attempted to call an undefined method named "getRequest" of class "AppBundle\Controller\DefaultController". "

That's my contactAction() in src/AppBundle/DeffaultController:

/**
 * @Route("/contact"), name="cont")
 */
public function contactAction()
{

    $enquiry = new Enquiry();
    $form = $this->createForm(EnquiryType::class, $enquiry);

    $request = $this->getRequest();
    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        if ($form->isValid()) {
            // Perform some action, such as sending an email

            // Redirect - This is important to prevent users re-posting
            // the form if they refresh the page
            return $this->redirect($this->generateUrl('app_default_contact'));
        }
    }


    return $this->render(':default:contact.html.twig', array(
        'form' => $form->createView()
    ));
}

Help please!


Solution

  • getRequest was a method of the Symfony\Bundle\FrameworkBundle\Controller\Controller base class. It was deprecated since version 2.4 and it's been removed in 3.0.

    To get it in your controller, just add it as an argument and type-hint it with the Request class:

    use Symfony\Component\HttpFoundation\Request;
    
    public function contactAction(Request $request)
    {
    
        // ...
    

    Documentation here.