You are here

protected function ContentBuilderForm::createField in Schema.org configuration tool (RDF UI) 8

Create fields for the selected properties.

1 call to ContentBuilderForm::createField()
ContentBuilderForm::submitForm in rdf_builder/src/Form/ContentBuilderForm.php
@inheritdoc

File

rdf_builder/src/Form/ContentBuilderForm.php, line 368

Class

ContentBuilderForm

Namespace

Drupal\rdf_builder\Form

Code

protected function createField() {
  $entity_type = 'node';
  $bundle = $this->entity
    ->id();
  foreach ($this->properties as $key => $value) {
    $label = $this->converter
      ->label($key);

    // Add the field prefix and truncate if longer than 32 char.
    $field_name = $this->prefix . strtolower($label);
    if (strlen($field_name) > 32) {
      $field_name = substr($field_name, 0, 32);
    }
    $field_storage = array(
      'field_name' => $field_name,
      'entity_type' => $entity_type,
      'type' => $value['type'],
      'translatable' => TRUE,
    );
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
      'label' => $label,
      // Field translatability should be explicitly enabled by the users.
      'translatable' => FALSE,
    );

    // Create the field and instance.
    try {
      \Drupal::entityTypeManager()
        ->getStorage('field_storage_config')
        ->create($field_storage)
        ->save();
      \Drupal::entityTypeManager()
        ->getStorage('field_config')
        ->create($instance)
        ->save();

      // Make sure the field is displayed in the 'default' form mode (using
      // default widget and settings). It stays hidden for other form modes
      // until it is explicitly configured.
      \Drupal::service('entity_display.repository')
        ->getFormDisplay($entity_type, $bundle, 'default')
        ->setComponent($field_name)
        ->save();

      // Make sure the field is displayed in the 'default' view mode (using
      // default formatter and settings). It stays hidden for other view
      // modes until it is explicitly configured.
      \Drupal::service('entity_display.repository')
        ->getFormDisplay($entity_type, $bundle, 'default')
        ->setComponent($field_name)
        ->save();

      // RDF Mapping.
      $this->rdfMapping
        ->setFieldMapping($field_name, array(
        'properties' => array(
          $key,
        ),
      ));
    } catch (\Exception $e) {
      $this
        ->messenger()
        ->addError($this
        ->t('There was a problem creating field %label: !message', array(
        '%label' => $instance['label'],
        '!message' => $e
          ->getMessage(),
      )));
    }
  }
}