5

I Want to force a certain text format in a user profile text format field and hide the text format selector dropdown. How do i do it? This is for Drupal 8.

8

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.

  • 1
    I was hoping to be able to do this without having to install a third-party module, but i'll try it, unless someone comes up with a different solution. – José Trindade Jun 22 '17 at 10:11
  • There is no other solution. – user21641 Jun 22 '17 at 10:28
  • Well, that is unfortunate. i'll accept this one. – José Trindade Jun 22 '17 at 10:32
  • I too prefer the D7 way but the D8 makes more sense from security POV. – user21641 Jun 22 '17 at 10:51
  • There is an issue in progress on D8 - drupal.org/project/drupal/issues/784672 – Anish Sheela Jan 18 at 8:15
7

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;
}

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.