Disabling/Eliminating form fields


Here is a code fragment in Drupal 7 that implements a callback with the aim of facilitating two actions according to the action that you want to carry out (tell the following line the action to carry out).

·         Disabling the field: disables the field in the form, leaving it visible

·         Eliminating the field: eliminates the field of the formula (even if it is required)

In Drupal 8, these types of functions are not necessary anymore; we can already edit the presentation of forms in the interface.

* Implements hook_form_FORM_ID_alter().
function MODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {

  // Hide none editable fields.
  $hide_fields = array(

  callback_hide_fields($hide_fields, $form);

* Hide fields.
* @param $fields
*  An array with field names to hide.
* @param $form
* @ingroup callbacks
function callback_hide_fields($fields, &$form) {
 foreach ($fields as $field) {
   $form[$field]['#access'] = FALSE; // Elimina el campo del formulario.
   $form[$field]['#disabled'] = TRUE; // Deshabilita el campo del formulario.