You are here

function leaflet_widget_field_widget_form in Leaflet Widget for Geofield 7

Same name and namespace in other branches
  1. 7.2 leaflet_widget.module \leaflet_widget_field_widget_form()

Implements hook_field_widget_form().

File

./leaflet_widget.module, line 89

Code

function leaflet_widget_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $settings = $instance['widget']['settings'];
  $widget = geofield_get_base_element($element, $items, $delta);
  $widget['#type'] = 'fieldset';
  switch ($instance['widget']['type']) {
    case 'leaflet_widget_widget':
      $id = 'leaflet-widget_' . str_replace('_', '-', $instance['field_name']);
      $class = 'leaflet-widget';
      $style = 'height: 300px;';
      $settings['map']['widget'] = array();
      $settings['map']['widget']['attach'] = "{$id}-input";
      $settings['map']['widget']['multiple'] = FALSE;
      $settings['map']['widget']['autoCenter'] = $settings['map']['auto_center'];
      if ($field['cardinality'] != 1) {
        $settings['map']['widget']['multiple'] = TRUE;

        // Leaflet.widget treats multiple == true && !cardinality as 'unlimited'.
        $settings['map']['widget']['cardinality'] = $field['cardinality'] > 0 ? $field['cardinality'] : 0;
      }

      // Provide container markup for map form element.
      $container = "<div id=\"{$id}\" class=\"{$class}\" style=\"{$style}\"></div>";
      $widget['leaflet_widget'] = array(
        '#markup' => $container,
      );

      // Overriding Geofield's validation handler.
      $widget['#element_validate'] = array(
        'leaflet_widget_widget_validate',
      );

      // Tell Geofield to expect GeoJSON instead of WKT.
      $widget['input_format']['#value'] = 'geojson';

      // Prepare existing field values to be rendered in widget.
      $collection = leaflet_widget_widget_prepare_items($items);

      // Set default value incase form is submitted without javascript enabled.
      $widget['wkt']['#default_value'] = drupal_json_encode($collection);
      $widget['wkt']['#attributes']['id'] = $settings['map']['widget']['attach'];

      // Include javascript.
      $widget['#attached']['library'][] = array(
        'leaflet_widget',
        'widget',
      );

      // Settings and geo-data are passed to the widget keyed by field id.
      $widget['#attached']['js'][] = array(
        'type' => 'setting',
        'data' => array(
          'leaflet_widget_widget' => array(
            $id => $settings,
          ),
        ),
      );
      break;
  }
  return $widget;
}