You are here

function geofield_field_presave in Geofield 7.2

Same name and namespace in other branches
  1. 7 geofield.module \geofield_field_presave()

Implements hook_field_presave().

File

./geofield.module, line 267

Code

function geofield_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if ($field['type'] === 'geofield') {

    /**
     * Edge case. Currently, Drupal will set a field value to the default value if the current value
     * is empty, even if it's set by the user. This bypasses our validation, and currently non-valid WKB
     * data in geom causes catastrophic failures in entity_load. To compensate, we add the default value
     * in early. When the core issue is fixed, we should drop this code.
     *
     * Geofield Issue: http://drupal.org/node/1886852
     * Core Issue: http://drupal.org/node/1253820
     */
    if ($instance['required'] == 0 && empty($items)) {
      $entity_ids = entity_extract_ids($entity_type, $entity);
      if (empty($entity_ids[0])) {
        $items = isset($instance['default_value']) ? array(
          $instance['default_value'],
        ) : array();
      }
    }
    ctools_include('plugins');
    $backend = ctools_get_plugins('geofield', 'geofield_backend', $field['settings']['backend']);
    $save_callback = $backend['save'];

    // For each delta, we compute all the auxiliary columns and transform the geom column into a geometry object
    // We then pass the geometry object (now stored in the geom column) to the backend to prepare it for insertion into the database
    foreach ($items as $delta => $item) {
      $items[$delta] = geofield_compute_values($item);
      if (isset($items[$delta]['geom']) && $items[$delta]['geom']) {
        $items[$delta]['geom'] = $save_callback($items[$delta]['geom']);
      }
    }
  }
}