Drupal 8 - Disable or hide a form field

Use case

Sometimes we might want to visually hide a field from a user but still render it in form. Or we might want to display the field to a user but want to disable it so that user is unable to edit it.

One reason for this could be that you have pre-filled a field like explained Here and now you don't want user to see this field or a user can see it but is unable to edit it.

Solution

If you are building your own form then you can apply following methods while building the form. Otherwise you can implement hook_form_FORM_ID_alter, to alter the form and apply these methods.

Disabling a drupal form field

Disabling the field is pretty simple. You just need to add disabled attribute to the field.

Add disabled attribute to a reference field

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function music_form_node_song_edit_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  $form['field_album']['widget'][0]['target_id']['#attributes']['disabled'] = 'disabled';
}

Add disabled attribute to normal input field

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function music_form_node_song_edit_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  $form['title']['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
}

Where field_album and title are machine names of fields respectively.

Visually hiding a drupal form field

The easiest way that I have found to visually hide a form field, is using CSS. First of all, you need to have a CSS class available which can hide an element. For example

.hide {
  display: none;
}

If you are not sure how to include CSS files in your custom module, you can look at drupal documentation for this, which explains this topic in detail.

Once CSS class is available, you can add it to field like following

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function music_form_node_song_edit_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  // attach css assets to form
  $form['#attached']['library'][] = 'music/music-assets';
  
  // add 'hide' css class to element
  $form['field_album']['#attributes']['class'][] = 'hide';
}

In the first line, we are attaching CSS asset file so that our custom CSS is available to use when the form is loaded.

Then we are adding CSS class to the field. This part is same, doesn't matter if its a reference field or normal field.


  PHP, Drupal 8