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?
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;
}
}
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;
}
'#disabled' => TRUE
as suggested in the other answer!
Commented
Feb 9, 2022 at 10:38