Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Contact Bundle Laravel Package

dankempster/contact-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dankempster/contact-bundle:1.0.*
    

    Add to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 2/3):

    return [
        // ...
        \FrequenceWeb\Bundle\ContactBundle\FrequenceWebContactBundle::class,
    ];
    
  2. Basic Configuration (config/packages/frequence_web_contact.yaml):

    frequence_web_contact:
        send_mails: true
        to: "contact@example.com"
        from: "noreply@example.com"
        subject: "contact.message.new"  # Requires translation
    
  3. Routing: Import the default routes in config/routes.yaml:

    frequence_web_contact:
        resource: "@FrequenceWebContactBundle/Resources/config/routing.xml"
    

    Now access /contact for the form and submission.

  4. First Use Case:

    • Visit /contact to render the form.
    • Submit the form to trigger the ContactFormSubmittedEvent (if send_mails: true).
    • Check your inbox (to email) for the submitted message.

Implementation Patterns

Core Workflow

  1. Form Handling:

    • The bundle provides a pre-built Twig template (@FrequenceWebContact/contact/form.html.twig).
    • Customize it by overriding the template in your theme:
      {% extends '@FrequenceWebContact/contact/form.html.twig' %}
      {% block contact_form_fields %}
          {{ parent() }}
          <!-- Add custom fields here -->
      {% endblock %}
      
  2. Event-Driven Logic:

    • Subscribe to ContactFormSubmittedEvent to extend behavior:
      // src/EventListener/CustomContactListener.php
      namespace App\EventListener;
      
      use FrequenceWeb\Bundle\ContactBundle\Event\ContactFormSubmittedEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class CustomContactListener implements EventSubscriberInterface
      {
          public static function getSubscribedEvents()
          {
              return [
                  ContactFormSubmittedEvent::class => 'onContactSubmitted',
              ];
          }
      
          public function onContactSubmitted(ContactFormSubmittedEvent $event)
          {
              $data = $event->getData();
              // Add custom logic (e.g., log to database, trigger Slack)
          }
      }
      
    • Register the listener in services.yaml:
      services:
          App\EventListener\CustomContactListener:
              tags:
                  - { name: kernel.event_subscriber }
      
  3. Validation:

    • Extend the default form type (FrequenceWeb\Bundle\ContactBundle\Form\ContactType) by creating a custom type:
      // src/Form/Type/CustomContactType.php
      namespace App\Form\Type;
      
      use FrequenceWeb\Bundle\ContactBundle\Form\ContactType as BaseContactType;
      use Symfony\Component\Form\AbstractType;
      use Symfony\Component\Form\FormBuilderInterface;
      
      class CustomContactType extends BaseContactType
      {
          public function buildForm(FormBuilderInterface $builder, array $options)
          {
              parent::buildForm($builder, $options);
              $builder->add('custom_field', TextType::class);
          }
      }
      
    • Override the service in services.yaml:
      services:
          frequence_web_contact.form.type.contact:
              class: App\Form\Type\CustomContactType
              tags: ['form.type']
      
  4. Translation:

    • Add translations for the subject and flash messages in config/packages/translation.yaml:
      translation:
          paths: ['%kernel.project_dir%/translations']
      
    • Create translations/messages.en.yaml:
      contact.message.new: "New Contact Form Submission"
      contact.flash.success: "Your message has been sent successfully!"
      

Gotchas and Tips

Pitfalls

  1. Event Dispatching:

    • The ContactFormSubmittedEvent is only dispatched if send_mails: true.
    • If you need the event to fire regardless, set send_mails: false and manually dispatch it in a custom listener for the form submission.
  2. Configuration Overrides:

    • The to and from emails must be set in config; null values will throw errors.
    • If using Symfony 4+, ensure the config file is named correctly (frequence_web_contact.yaml) and placed in config/packages/.
  3. Template Overrides:

    • The default template assumes fields like name, email, and message. If you rename these in your custom form type, update the Twig blocks accordingly:
      {% block contact_form_name_field %}
          {{ form_row(form.name) }}  {# Custom field name #}
      {% endblock %}
      
  4. CSRF Protection:

    • The form includes CSRF protection by default. If you encounter issues, ensure your Twig template includes:
      {{ form_start(form, {'attr': {'novalidate': 'novalidate'}}) }}
      

Debugging Tips

  1. Check Event Firing:

    • Add a dump() in your event subscriber to verify the event is triggered:
      public function onContactSubmitted(ContactFormSubmittedEvent $event)
      {
          dump($event->getData()); // Debug submitted data
      }
      
  2. Mail Configuration:

    • If emails aren’t sending, verify:
      • The to and from emails are valid.
      • Your mail transport (e.g., mailer_transport in .env) is configured.
      • No exceptions are caught by the EmailListener (check Symfony logs).
  3. Routing Conflicts:

    • If /contact conflicts with another route, use _frequence_web_contact with a custom prefix in routing.yaml:
      frequence_web_contact:
          resource: "@FrequenceWebContactBundle/Resources/config/routing.xml"
          prefix: "/support"
      

Extension Points

  1. Custom Storage:

    • To save submissions to a database, create a listener:
      public function onContactSubmitted(ContactFormSubmittedEvent $event)
      {
          $entityManager = $this->container->get('doctrine')->getManager();
          $contact = new Contact();
          $contact->setData($event->getData());
          $entityManager->persist($contact);
          $entityManager->flush();
      }
      
  2. Dynamic Recipients:

    • Override the EmailListener to set dynamic to addresses:
      # services.yaml
      services:
          frequence_web_contact.listener.email:
              class: App\EventListener\DynamicEmailListener
              arguments: ['@mailer']
              tags:
                  - { name: kernel.event_listener, event: ContactFormSubmittedEvent, method: onContactSubmitted }
      
  3. Async Processing:

    • Use Symfony Messenger to process submissions asynchronously:
      public function onContactSubmitted(ContactFormSubmittedEvent $event)
      {
          $this->messageBus->dispatch(new ProcessContactMessage($event->getData()));
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky