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
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.
- 1I 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– José Trindade2017-06-22 10:11:14 +00:00Commented Jun 22, 2017 at 10:11
- There is no other solution.user21641– user216412017-06-22 10:28:35 +00:00Commented Jun 22, 2017 at 10:28
- Well, that is unfortunate. i'll accept this one.José Trindade– José Trindade2017-06-22 10:32:01 +00:00Commented Jun 22, 2017 at 10:32
- I too prefer the D7 way but the D8 makes more sense from security POV.user21641– user216412017-06-22 10:51:05 +00:00Commented Jun 22, 2017 at 10:51
- 1There is an issue in progress on D8 - drupal.org/project/drupal/issues/784672Anish Sheela– Anish Sheela2019-01-18 08:15:35 +00:00Commented Jan 18, 2019 at 8:15
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; } 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.'), ];