You are here

function farm_map_geofield_use_geocoder_submit in farmOS 7

Submit handler for the geocoder integration.

1 string reference to 'farm_map_geofield_use_geocoder_submit'
farm_map_geofield_field_widget_form in modules/farm/farm_map/farm_map_geofield/farm_map_geofield.module
Implements hook_field_widget_form().

File

modules/farm/farm_map/farm_map_geofield/farm_map_geofield.module, line 272
Farm Map Geofield integration.

Code

function farm_map_geofield_use_geocoder_submit($form, &$form_state) {
  $button = $form_state['triggering_element'];

  // Go one level up in the form, to the widgets container.
  $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  $field_name = $element['#field_name'];
  $langcode = $element['#language'];
  $delta = $element['#delta'];
  $parents = $element['#field_parents'];

  // Set the widget value based on geocoding results.
  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  $geocoder_field = $field_state['instance']['widget']['settings']['geocoder_field'];
  $geocoder_field_parents = array_merge(array_slice($button['#array_parents'], 0, -4), array(
    $geocoder_field,
    $langcode,
  ));

  // Since all validation errors are disabled we need to fetch the values for
  // the geocoding as only validate values are sent to the values array of the
  // form state.
  $values = drupal_array_get_nested_value($form_state['input'], $geocoder_field_parents);

  // Inject the values into the values array to ensure the geofield module is
  // able to handle the data.
  drupal_array_set_nested_value($form_state['values'], $geocoder_field_parents, $values);
  if ($field_value = geocoder_widget_get_field_value($element['#entity_type'], $field_state['instance'], NULL, $values)) {
    geophp_load();
    $geometry = geoPHP::load($field_value[$langcode][$delta]['geom']);

    // Openlayers can only use WKT, so translate.
    $field_value[$langcode][$delta]['geom'] = $geometry
      ->out('wkt');
    $field_value[$langcode][$delta]['input_format'] = 'wkt';

    // Override the field's value in the 'input' array to substitute the new
    // field value for the one that was submitted.
    drupal_array_set_nested_value($form_state, array_merge(array(
      'input',
    ), array_slice($button['#array_parents'], 0, -4), array(
      $field_name,
    )), $field_value);
  }

  // Rebuild the form to ensure that the map is recreated from scratch.
  // See field_add_more_submit() in core field.form.inc for similar usage.
  $form_state['rebuild'] = TRUE;
}