You are here

function allowed_formats_field_widget_form_alter in Allowed Formats 8

Implements hook_field_widget_form_alter().

File

./allowed_formats.module, line 63
This is the allowed_formats module.

Code

function allowed_formats_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
  $field_definition = $context['items']
    ->getFieldDefinition();

  // We can't use the protected isDefaultValueWidget() method.
  $is_default_value_widget = (bool) $form_state
    ->get('default_value_widget');
  if (in_array($field_definition
    ->getType(), _allowed_formats_field_types()) && !$is_default_value_widget) {
    if ($field_definition instanceof FieldConfigBase) {

      // Read configuration if available.  This is possible for bundle fields or
      // base fields overridden using a BaseFieldOverride.
      $field_configuration = $field_definition
        ->getConfig($field_definition
        ->getTargetBundle());
      $allowed_formats_setting = $field_configuration
        ->getThirdPartySettings('allowed_formats');
    }
    else {

      // Base fields don't support third party settings so use an ordinary
      // setting.  That's the way it would work anyway if allowed formats gets
      // into core.
      $allowed_formats_setting = $field_definition
        ->getSetting('allowed_formats');
    }
    if (isset($allowed_formats_setting) && is_array($allowed_formats_setting)) {
      $allowed_formats = array_filter($allowed_formats_setting);
      if (!empty($allowed_formats)) {
        $element['#allowed_formats'] = $allowed_formats;
      }
    }

    /** @var \Drupal\Core\Field\WidgetInterface $widget */
    $widget = $context['widget'];
    $element['#allowed_format_hide_settings'] = $widget
      ->getThirdPartySettings('allowed_formats');
    if (count(array_filter($element['#allowed_format_hide_settings']))) {
      $element['#after_build'][] = '_allowed_formats_remove_textarea_help';
    }
  }
}