7

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.

3 Answers 3

11

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.

5
  • 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. Jun 22, 2017 at 10:11
  • There is no other solution.
    – user21641
    Jun 22, 2017 at 10:28
  • Well, that is unfortunate. i'll accept this one. Jun 22, 2017 at 10:32
  • I too prefer the D7 way but the D8 makes more sense from security POV.
    – user21641
    Jun 22, 2017 at 10:51
  • 1
    There is an issue in progress on D8 - drupal.org/project/drupal/issues/784672 Jan 18, 2019 at 8:15
11

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

If you use the #allowed_formats value and limit it to just 1 value; then the selector will disappear. This is code to add your own custom field; but I assume you can do a form alter to set these for an existing (UI placed) field.

$form['message_text'] = [
  '#type' => 'text_format',
  '#format' => 'simple',
  '#allowed_formats' => ['simple'],
  '#title' => $this->t('Message Text:'),
  '#description' => $this->t('Some help text here.'),
];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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