You are here

public function YoastSeoFieldManager::attachField in Real-time SEO for Drupal 8

Attach a field to a target content type.

Parameters

string $entity_type: Entity type. Example 'node'.

string $bundle: Bundle type.

mixed $field: Field.

File

src/YoastSeoFieldManager.php, line 117

Class

YoastSeoFieldManager
Class YoastSeoFieldManager.

Namespace

Drupal\yoast_seo

Code

public function attachField($entity_type, $bundle, $field) {

  // Retrieve the yoast seo field attached to the target entity.
  $field_storage_config = $this->entity_manager
    ->getStorage('field_storage_config')
    ->load($entity_type . '.' . $field['field_name']);

  // If the field hasn't been attached yet to the target entity, attach it.
  if (is_null($field_storage_config)) {
    $this->entity_manager
      ->getStorage('field_storage_config')
      ->create([
      'field_name' => $field['field_name'],
      'entity_type' => $entity_type,
      'type' => $field['storage_type'],
      'translatable' => $field['translatable'],
    ])
      ->save();
  }

  // Retrieve the yoast seo field attached to the target content type.
  $fields_config = \Drupal::service('entity_field.manager')
    ->getFieldDefinitions($entity_type, $bundle);

  // If the field hasn't been attached yet to the content type, attach it.
  if (!isset($fields_config[$field['field_name']])) {
    $field_values = [
      'field_name' => $field['field_name'],
      'entity_type' => $entity_type,
      'bundle' => $bundle,
      'label' => $field['field_label'],
      'translatable' => $field['translatable'],
    ];
    $this->entity_manager
      ->getStorage('field_config')
      ->create($field_values)
      ->save();
    $this->entity_manager
      ->getStorage('entity_form_display')
      ->load($entity_type . '.' . $bundle . '.default')
      ->setComponent($field['field_name'], [])
      ->save();
    $this->entity_manager
      ->getStorage('entity_view_display')
      ->load($entity_type . '.' . $bundle . '.default')
      ->setComponent($field['field_name'], [])
      ->save();
  }
}