I just want to create a contact page but I got this error : Variable “contactForm” does not exist when Im sure that I render the variable to the twig page.
this is my contactcontroller .php
<?php
namespace AppController;
use AppFormContactFormType;
use SymfonyComponentMimeEmail;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentMailerMailerInterface;
use SymfonyComponentRoutingAttributeRoute;
class ContactController extends AbstractController
{
#[Route('/contact', name: 'app_contact')]
public function index(Request $request, MailerInterface $mailer): Response
{
$form = $this->createForm(ContactFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$formData = $form->getData();
// Send email using Symfony Mailer
$email = (new Email())
->from($formData['email'])
->to('[email protected]') // Replace with your email address
->subject('New Contact Message')
->html($this->renderView(
'emails/contact.html.twig',
['formData' => $formData]
));
$mailer->send($email);
// Flash message to indicate successful submission (optional)
$this->addFlash('success', 'Your message has been sent!');
// Redirect to prevent form resubmission
return $this->redirectToRoute('app_home');
}
return $this->render('contact/contact.html.twig', [
'contactForm' => $form->createView(),
]);
}
}
and this is my contact.html.twig
{% extends 'admin/admin.html.twig' %}
{% block title %}Contact{% endblock %}
{% block stylesheets %}
<link rel="stylesheet" href={{asset('styles/css/contact.css')}}>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.3.0/css/all.min.css">
{% endblock %}
{% block main %}
<h1>Contact Us</h1>
{{ form_start(contactForm) }}
{{ form_row(contactForm.name) }}
{{ form_row(contactForm.email) }}
{{ form_row(contactForm.message) }}
<button type="submit" class="btn btn-primary">Send Message</button>
{{ form_end(contactForm) }}
{% endblock %}
Im getting an error Variable “contactForm” does not exist when I want to send a message via the contact form.