Disabling/Eliminating form fields

23/02/2016

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(
   'field_stages',
   'field_project_visibility',
   'field_youth_partner_code',
   'field_about',
   'title',
   'field_region',
  );

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

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.