Drupal - How do i force a text format and hide the format selector in a formatted text field?
Adapted from the Allowed Formats code:
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_field_widget_form_alter().
*/
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
// Maps field names to an array containing a single format.
$map = [
'field_myfield' => ['myformat'],
];
$field_name = $context['items']->getFieldDefinition()->getName();
if (array_key_exists($field_name, $map)) {
$element['#allowed_formats'] = $map[$field_name];
$element['#after_build'][] = '_remove_text_format_box';
}
}
/**
* #after_build callback.
*/
function _remove_text_format_box($form_element, FormStateInterface $form_state) {
// Remove help, guidelines and wrapper.
unset($form_element['format']['help']);
unset($form_element['format']['guidelines']);
unset($form_element['format']['#type']);
unset($form_element['format']['#theme_wrappers']);
return $form_element;
}
Install the module Allowed Formats and configure the field to allow only one text format. Then the text format selector dropdown will no longer be displayed.