4

I want prevent any user from being able to change the value of a field, yet I want to display its value.

How can I achieve this?

8

This can be done via hook_form_alter

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

   if($form_id == 'user_register_form') {
      $form['field_name']['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
   }

}

Add some css:

input:read-only {
  background-color: #ddd !important;
}

Result:

enter image description here

| improve this answer | |
1

And Just as a Reference, another solution is using the #disabled attribute:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['field_name']['#disabled'] = TRUE;
  }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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