You are here

public function KmlImporter::submitForm in farmOS 2.x

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormInterface::submitForm

File

modules/core/import/modules/kml/src/Form/KmlImporter.php, line 295

Class

KmlImporter
Provides a form for importing KML placemarks as land assets.

Namespace

Drupal\farm_import_kml\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {

  // Bail if no file was uploaded.
  $file_ids = $form_state
    ->getValue('file', []);
  if (empty($file_ids)) {
    $this
      ->messenger()
      ->addError($this
      ->t('File upload failed.'));
    return;
  }

  // Load the assets to create.
  $assets = $form_state
    ->getValue('assets', []);
  $confirmed_assets = array_filter($assets, function ($asset) {
    return !empty($asset['confirm']);
  });

  // Create a parent asset if specified.
  $parent = $form_state
    ->getValue('parent');
  $parent_asset = NULL;
  if (!empty($parent['create'])) {
    $parent_asset = Asset::create([
      'type' => 'land',
      'land_type' => $parent['land_type'],
      'is_location' => TRUE,
      'is_fixed' => TRUE,
      'name' => $parent['name'],
    ]);
    $parent_asset
      ->save();
    $asset_url = $parent_asset
      ->toUrl()
      ->setAbsolute()
      ->toString();
    $this
      ->messenger()
      ->addMEssage($this
      ->t('Created land asset: <a href=":url">%asset_label</a>', [
      ':url' => $asset_url,
      '%asset_label' => $parent_asset
        ->label(),
    ]));
  }

  // Create new assets.
  foreach ($confirmed_assets as $asset) {
    $new_asset = Asset::create([
      'type' => 'land',
      'land_type' => $asset['land_type'],
      'intrinsic_geometry' => $asset['geometry'],
      'is_location' => TRUE,
      'is_fixed' => TRUE,
    ]);

    // Set the name.
    if (!empty($asset['name'])) {
      $new_asset
        ->set('name', $asset['name']);
    }

    // Set the notes.
    if (!empty($asset['notes'])) {
      $new_asset
        ->set('notes', $asset['notes']);
    }

    // Set the parent.
    if (!empty($parent_asset)) {
      $new_asset
        ->set('parent', $parent_asset);
    }
    $new_asset
      ->save();
    $asset_url = $new_asset
      ->toUrl()
      ->setAbsolute()
      ->toString();
    $this
      ->messenger()
      ->addMEssage($this
      ->t('Created land asset: <a href=":url">%asset_label</a>', [
      ':url' => $asset_url,
      '%asset_label' => $new_asset
        ->label(),
    ]));
  }
}