Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Embed Drupal 8 Contact Forms into a page

Parent Feed: 

Currently the core module Contact form only gives you an accessible URL that you can visit too see your form. There are plenty use cases where you instead would like to embed it into a page, a node, etc.

First we have the Contact Block module which allows you to use blocks to display contact forms.

The second option is to do it programmatically. So for example if we would like to add a form to all pages, we could preprocess the page hook_preprocess_page(&$variables) and then:

  // Get feedback form to be rendered on all pages.
  $message = \Drupal::entityTypeManager()
          ->getStorage('contact_message')
          ->create(array(
          'contact_form' => 'feedback', // The machine name of the form.
      ));
  $form = \Drupal::service('entity.form_builder')->getForm($message);
  $vars['feedback_form'] = $form;

Now we have a feedback_form variable we can simply output in our page.html.twig template.

If you want the form to be dynamic without a page reload, take a look at the Contact ajax module which works just fine even though it's in beta!

Author: 
RSS Tags: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web