rdf_sync-1.x-dev/src/Form/Alter/FieldConfigFormAlter.php

src/Form/Alter/FieldConfigFormAlter.php
<?php

declare(strict_types=1);

namespace Drupal\rdf_sync\Form\Alter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\field\FieldConfigInterface;

/**
 * Field config form alter.
 */
class FieldConfigFormAlter extends AbstractFormAlter {

  /**
   * {@inheritdoc}
   */
  public function alter(array &$form, FormStateInterface $formState): void {
    /** @var \Drupal\field\FieldConfigInterface $fieldConfig */
    $fieldConfig = $formState->getFormObject()->getEntity();
    $fieldStorageConfig = $fieldConfig->getFieldStorageDefinition();

    $form['rdf_sync'] = [
      '#type' => 'details',
      '#title' => $this->t('RDF sync mapping'),
      '#open' => TRUE,
      '#weight' => 99,
      '#tree' => TRUE,
    ];

    foreach ($fieldStorageConfig->getSchema()['columns'] as $column => $columnDesc) {
      $description = isset($columnDesc['description']) ? $columnDesc['description'] . "<br>" : '';
      foreach (['type', 'length', 'size', 'serialize'] as $key) {
        if (!empty($columnDesc[$key])) {
          $description .= '<strong>' . $key . "</strong>: " . $columnDesc[$key] . ' ';
        }
      }

      $form['rdf_sync'][$column] = [
        '#type' => 'details',
        '#title' => $column,
        '#description' => $description,
      ];

      $settings = $fieldConfig->getThirdPartySettings('rdf_sync')[$column] ?? [];
      $form['rdf_sync'][$column]['predicate'] = $this->getPredicateElement($settings);
      $form['rdf_sync'][$column]['type'] = $this->getTypeElement($settings);
    }

    // The form must stay serializable, hence using a static method.
    $form['#entity_builders'][] = [static::class, 'entityFormEntityBuild'];
  }

  /**
   * Entity builder method.
   *
   * @param string $entityType
   *   The type of the entity.
   * @param \Drupal\field\FieldConfigInterface $fieldConfig
   *   The field config.
   * @param array $form
   *   A nested array form elements comprising the form.
   * @param \Drupal\Core\Form\FormStateInterface $formState
   *   The current state of the form.
   */
  public static function entityFormEntityBuild(string $entityType, FieldConfigInterface $fieldConfig, array $form, FormStateInterface $formState): void {
    $fieldStorageConfig = $fieldConfig->getFieldStorageDefinition();

    foreach (array_keys($fieldStorageConfig->getSchema()['columns']) as $column) {
      $fieldConfig->unsetThirdPartySetting('rdf_sync', $column);
      $data = $formState->getValue(['rdf_sync', $column]);
      $data['type'] = $data['type'] ?: NULL;

      if (!empty($data['predicate'])) {
        $fieldConfig->setThirdPartySetting('rdf_sync', $column, $data);
      }
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc