2

I am trying to set the default input format for a node body field and avoid users can select a different input format by hiding the form element to change it.

I am using the following code, but it doesn't work.

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_article_form') {
    $form["body"]["widget"][0]['#allowed_formats'] = ['full_html'];
    $form["body"]["widget"][0]['#after_build'][] = 'mymodule_hide_format';
  }
}

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

  return $element;
}
1

1 Answer 1

5

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().

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

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_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';
  }
}

function mymodule_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 and acknowledge you have read our privacy policy.