2
/**
 * Implements hook_form_alter().
 */
function MODULE_NAME_form_alter(
  &$form,
  \Drupal\Core\Form\FormStateInterface $form_state,
  $form_id
) {

  if ($form_id == 'node_article_form') {
    $form["body"]["widget"][0]['#allowed_formats'] = ['full_html']; // Your default format
    $form["body"]["widget"][0]['#after_build'][] = 'MODULE_NAME_hide_format';
  }
}

function MODULE_NAME_hide_format(
  &$element,
  FormStateInterface $form_state
) {
  if (isset($element["format"]["format"])) {
    $element["format"]["format"]["#access"] = FALSE;
  }

  return $element;
}
2

The module suggested (in comments above) seems interesting, but if you want to do it with code only for body field and you don't want to use the module,
you can use hook_field_widget_form_alter instead of hook_form_alter.

Try this:

use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldConfig;

/**
 * Implements hook_field_widget_form_alter().
 */
function MODULE_NAME_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
  $field_definition = $context['items']->getFieldDefinition();

  // Base fields are not configurable.
  if (!$field_definition instanceof FieldConfig) {
    return;
  }

  if ($field_definition->getName() === 'body'){
    // Set only full_html as allowed format.
    $element['#allowed_formats'] = ['full_html'];
    // Add after build to remove the help wrapper and text.
    $element['#after_build'][] = 'MODULE_NAME_after_build';
  }
}



/**
 * @param array $element
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *
 * @return array
 */
function MODULE_NAME_after_build(array $element, FormStateInterface $form_state) {
  // Remove Guidelines and Help text.
  unset($element['format']['help']);
  unset($element['format']['guidelines']);
  unset($element['format']['#type']);
  unset($element['format']['#theme_wrappers']);
  return $element;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.