12

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?

2 Answers 2

13

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;
  }
}
2
  • 3
    That's not exact. When a field is disabled and you programmatically set its value in the form, the value will be ignored, from the form validation handler and the form submission handler. When the field is readonly, the value will be handled. Commented Jul 2, 2021 at 13:21
  • 2
    This is exactly the answer to the question!
    – Elin Y.
    Commented Mar 2, 2022 at 15:34
9

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

1
  • 2
    This solution can be easily circumvented on client side. Use '#disabled' => TRUE as suggested in the other answer!
    – donquixote
    Commented Feb 9, 2022 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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