You are here

public function GeofieldWidget::formElement in farmOS 2.x

File

modules/core/map/src/Plugin/Field/FieldWidget/GeofieldWidget.php, line 134

Class

GeofieldWidget
Plugin implementation of the map 'geofield' widget.

Namespace

Drupal\farm_map\Plugin\Field\FieldWidget

Code

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

  // Wrap the map in a collapsible details element.
  $field_name = $this->fieldDefinition
    ->getName();
  $field_wrapper_id = Html::getUniqueId($field_name . '_wrapper');
  $element['#type'] = 'details';
  $element['#title'] = $this
    ->t('Geometry');
  $element['#open'] = TRUE;
  $element['#prefix'] = '<div id="' . $field_wrapper_id . '">';
  $element['#suffix'] = '</div>';

  // Get the current form state value. Prioritize form state over field value.
  $form_value = $form_state
    ->getValue([
    $field_name,
    $delta,
    'value',
  ]);
  $field_value = $items[$delta]->value;
  $current_value = $form_value ?? $field_value;

  // Define the map render array.
  $element['map'] = [
    '#type' => 'farm_map',
    '#map_type' => 'geofield_widget',
    '#map_settings' => [
      'wkt' => $current_value,
      'behaviors' => [
        'wkt' => [
          'edit' => TRUE,
          'zoom' => TRUE,
        ],
      ],
    ],
  ];

  // Add a textarea for the WKT value.
  $display_raw_geometry = $this
    ->getSetting('display_raw_geometry');
  $element['value'] = [
    '#type' => $display_raw_geometry ? 'textarea' : 'hidden',
    '#title' => $this
      ->t('Geometry'),
    '#default_value' => $current_value,
    '#attributes' => [
      'data-map-geometry-field' => TRUE,
    ],
  ];

  // Add an option to populate geometry using files field.
  // The "populate_file_field" field setting must be configured and the
  // field must be included in the current form.
  $populate_file_field = $this
    ->getSetting('populate_file_field');
  if (!empty($populate_file_field) && !empty($form[$populate_file_field])) {
    $element['trigger'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Import geometry from uploaded files'),
      '#submit' => [
        [
          $this,
          'fileParse',
        ],
      ],
      '#ajax' => [
        'wrapper' => $field_wrapper_id,
        'callback' => [
          $this,
          'fileCallback',
        ],
        'message' => $this
          ->t('Working...'),
      ],
      '#states' => [
        'disabled' => [
          ':input[name="' . $populate_file_field . '[0][fids]"]' => [
            'empty' => TRUE,
          ],
        ],
      ],
    ];
  }
  return $element;
}