1

Is there a way to automatically fill in fields in Drupal 8 Contact forms, for example by passing the value in the URL? E.g.

/contact/myform?subject=Subject%20line

If Drupal doesn't have this built-in, does anyone know of a javascript plugin that will do this?

1 Answer 1

2

There isn't a built-in way to do this with the contact entity form. The prepopulate module looks like it would be covered under this scenario, but it doesn't work on contact forms.

As an alternative, a simple form alter with a custom module could do this on the back end, or front end, with a hook_form_alter() invocation.

The backend solution could alter the default form value:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  // Set the default subject based off the subject query param.
  $default_subject = \Drupal::request()->query->get('subject');
  $form['subject']['widget'][0]['value']['#default_value'] = $default_subject;
}

Or the frontend solution can attach a custom JS file:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  // Assuming mymodule has defined a drupal.mymodule library 
  // within mymodule.libraries.yml
  $form['#attached']['library'][] = 'mymodule/drupal.mymodule';
}

Then have the attached JS attach to a Drupal behavior:

(function ($, Drupal, drupalSettings) {

  // Attach a drupal behavior that uses jQuery to alter the form value.
  Drupal.behaviors.mymodule = {
    attach: function () {
      var subject = '';
      // @TODO: parse location.search for the subject query param.
      $('#edit-subject-0-value').val(subject);
    }
  };

})(jQuery, Drupal, drupalSettings);
1
  • Hi, on my side, the prepropulate module worked with the Contact form.
    – user334
    Commented Mar 21, 2017 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.