You are here

class FieldMappings in Schema.org configuration tool (RDF UI) 8

RDF UI Field Mapping form.

Hierarchy

Expanded class hierarchy of FieldMappings

File

src/Form/FieldMappings.php, line 18

Namespace

Drupal\rdfui\Form
View source
class FieldMappings extends FormBase {

  /**
   * The EasyRdfConverter.
   *
   * @var \Drupal\rdfui\EasyRdfConverter
   */
  protected $rdfConverter;
  protected $displayContext = 'form';
  protected $entityTypeId;
  protected $bundle;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.field.field_type'), $container
      ->get('plugin.manager.field.widget'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $entity_type_id = NULL, $bundle = NULL) {
    $this->entityTypeId = $entity_type_id;
    $this->bundle = $bundle;
    $this->rdfConverter = new SchemaOrgConverter();

    // Gather bundle information.
    $instances = array_filter(\Drupal::service('entity_field.manager')
      ->getFieldDefinitions($entity_type_id, $bundle), function ($field_definition) {
      return $field_definition instanceof FieldConfigInterface;
    });
    $mappings = rdf_get_mapping($this->entityTypeId, $this->bundle);
    $options = NULL;
    $bundle_mapping = $mappings
      ->getBundleMapping();
    if (!empty($bundle_mapping) && !empty($bundle_mapping['types']['0'])) {
      $type = $bundle_mapping['types']['0'];
      $options = $this->rdfConverter
        ->getTypeProperties($type);
    }
    else {
      $options = $this->rdfConverter
        ->getListProperties();
    }
    $form += array(
      '#entity_type' => $this->entityTypeId,
      '#bundle' => $this->bundle,
      '#fields' => array_keys($instances),
    );
    $table = array(
      '#type' => 'table',
      '#tree' => TRUE,
      '#header' => array(
        $this
          ->t('Label'),
        $this
          ->t('RDF Property'),
        $this
          ->t('Data Type'),
        $this
          ->t('Status'),
      ),
      '#regions' => $this
        ->getRegions(),
      '#attributes' => array(
        'class' => array(
          'rdfui-field-mappings',
        ),
        'id' => Html::getUniqueId('rdf-mapping'),
      ),
    );

    // Fields.
    foreach ($instances as $name => $instance) {
      $property = $mappings
        ->getFieldMapping($name);
      $table[$name] = array(
        '#attributes' => array(
          'id' => Html::getUniqueId($name),
        ),
        'label' => array(
          '#markup' => $this
            ->t($instance
            ->getLabel()),
        ),
        'rdf-predicate' => array(
          '#id' => 'rdf-predicate',
          '#type' => 'select',
          '#title' => $this
            ->t('RDF Property'),
          '#title_display' => 'invisible',
          '#options' => $options,
          '#empty_option' => '',
          '#attached' => array(
            'library' => array(
              'rdfui/drupal.rdfui.autocomplete',
            ),
          ),
          '#default_value' => !empty($property) ? $property['properties'][0] : '',
        ),
        'type' => array(
          '#title' => $this
            ->t('Data Type'),
          '#title_display' => 'invisible',
          '#markup' => $this
            ->t('Text'),
        ),
        'status' => array(
          '#title' => $this
            ->t('Status'),
          '#title_display' => 'invisible',
          '#markup' => !empty($property['properties'][0]) ? 'Mapped' : 'Unmapped',
        ),
      );
    }
    $table['#regions']['content']['rows_order'] = array();
    foreach (Element::children($table) as $name) {
      $table['#regions']['content']['rows_order'][] = $name;
    }
    $form['fields'] = $table;
    $form['actions'] = array(
      '#type' => 'actions',
    );
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => $this
        ->t('Save'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getRegions() {
    return array(
      'content' => array(
        'title' => $this
          ->t('Content'),
        'invisible' => TRUE,
      ),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // @TODO implement method if validation is required.
  }

  /**
   * Overrides \Drupal\field_ui\FormDisplayOverview::submitForm().
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state
      ->getValue('fields');
    $mapping = rdf_get_mapping($this->entityTypeId, $this->bundle);

    // Add mapping for title field.
    if ($this->entityTypeId === 'node') {
      $type = $mapping
        ->getFieldMapping('title');
      if (empty($type)) {
        $mapping
          ->setFieldMapping('title', array(
          'properties' => array(
            'schema:name',
          ),
        ));
      }
    }
    foreach ($form_values as $key => $value) {
      $mapping
        ->setFieldMapping($key, array(
        'properties' => array(
          $value['rdf-predicate'],
        ),
      ));
    }
    $mapping
      ->save();
    $this
      ->messenger()
      ->addStatus($this
      ->t('Your settings have been saved.'));
  }

  /**
   * Returns a unique string identifying the form.
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return "rdfui_field_mapping_form";
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FieldMappings::$bundle protected property
FieldMappings::$displayContext protected property
FieldMappings::$entityTypeId protected property
FieldMappings::$rdfConverter protected property The EasyRdfConverter.
FieldMappings::buildForm public function Form constructor. Overrides FormInterface::buildForm
FieldMappings::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FieldMappings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FieldMappings::getRegions public function
FieldMappings::submitForm public function Overrides \Drupal\field_ui\FormDisplayOverview::submitForm(). Overrides FormInterface::submitForm
FieldMappings::validateForm public function Form validation handler. Overrides FormBase::validateForm
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.