You are here

public function ManagerForm::addField in Hashtags 8

File

src/Form/ManagerForm.php, line 91

Class

ManagerForm

Namespace

Drupal\hashtags\Form

Code

public function addField(array &$form, FormStateInterface $form_state) {
  $hashtags_vid = \Drupal::config('hashtags.settings')
    ->get('hashtags_vid');
  $clicked_button = $form_state
    ->getTriggeringElement();
  $entity_type = $clicked_button['#entity_type'];
  $bundle = $clicked_button['#bundle'];
  $field_name = $clicked_button['#field_name'];

  // create field storage or take existing one
  $field_storage = $this
    ->isFieldStorageExists($entity_type, $field_name);
  if (!$field_storage) {
    $field_storage = $this
      ->createFieldStorage($entity_type, $field_name);
  }
  $field = _hashtags_is_field_exists($entity_type, $bundle, $field_name);
  if (!$field) {
    $this
      ->createField($field_storage, $bundle, 'Hashtags', [
      $hashtags_vid => $hashtags_vid,
    ]);
    $this
      ->updateFieldFormDisplay($entity_type, $bundle, $field_name);
    $body_field = \Drupal::entityTypeManager()
      ->getStorage('field_config')
      ->load("{$entity_type}.{$bundle}.body");
    $entity_type_label = _hashtags_get_entity_type_label($entity_type);
    $bundle_label = _hashtags_get_bundle_label($entity_type, $bundle);
    $source = $entity_type !== $bundle ? $entity_type_label . ' > ' . $bundle_label : $entity_type_label;
    if (!empty($body_field)) {
      $body_field
        ->setThirdPartySetting('hashtags', 'hashtags_activate', TRUE);
      $body_field
        ->save();
      \Drupal::messenger()
        ->addMessage("Hashtags have been activated for Body field. Also you can activate Hashtags for another Text fields of {$source}.");
    }
    else {
      \Drupal::messenger()
        ->addMessage("Body field is not found for {$source}. Create some Text field and activate Hashtags manually for it.");
    }
  }
}