Drupal 7: Openlayers map disappears after form submit

Published by Lennart Van Vaerenbergh on August 23, 2017

This post is about loading an Openlayers map into a custom Drupal form and make sure it stays loaded after the form submit generates common form errors.

When an Openlayers map is loaded into a form array using the function openlayers_geofield_form_latlon_map(), it gets nicely loaded right where you want it. Except for one nasty side effect: the form disappears after the form gets submitted and reloads showing common form errors.

This is because the Openlayers function is using the drupal_add_js() function to load javascript. These scripts don't get cached while the form does and of course the form gets loaded from cache after the submit for several reasons.
 

So either we make sure the script get into the cache OR we make sure the drupal_add_js() functions get triggered again after submit. Because the Openlayers function openlayers_geofield_form_latlon_map() is a nested pile of drupal_add_js functions, the first option seems hard to do. We go for option 2. We can obtain this by using the #after_build property. This way we can register a function that gets executed after the form is built, even after a submit.
 

/**
 * Form callback.
 */
function MY_MODULE_form($form, &$form_state) {
  $form['map'] = array(
    '#markup' => openlayers_geofield_form_latlon_map(array(), 'my_map'),
  );

  $form['#after_build'][] = 'MY_MODULE_form_after_build';

  return $form;
}

/**
 * After build callback.
 */
function MY_MODULE_form_after_build($form, &$form_state) {
  // Execute when not loaded during ajax call and not during initial
  // form load.
  if (arg(1) !== 'ajax' && !empty($form_state['input'])) {
    // This is a fix for the map not being rendered after a form error.
    // When a form error occurs, the form is loaded from cache, hence the
    // drupal_add_js functions of openlayers aren't executed anymore.
    $form['map']['#markup'] = openlayers_geofield_form_latlon_map(array(), 'my_map');
  }

  return $form;
}

 

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.
CAPTCHA
This challenge is for testing whether or not you are a human visitor and to prevent automated spam submissions.