Some fields of my nodes get regularly updated by an external datasource and therefore should not be edited by editors in Drupal. But for UX reasons I still need those fields visible on the edit form.

For input fields I've added the HTML readonly attribute, which works quite well:

function MYMODULE_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $node = $form_state->getFormObject()->getEntity();

  if ($form_id == 'node_MYBUNDLE_form' || $form_id == 'node_MYBUNDLE_edit_form') {
    if ($node->hasField('remote_id') && $node->hasField('remote_datasource')) {
      if ($node->get('remote_id')->value && $node->hasField('remote_datasource') == 'SET_BY_MY_IMPORTER') {
        $readonlyFields = ['title', 'body', 'field_image', 'remote_id', 'field_minprice', 'field_roomsize', 'field_minoccupancy', 'field_stdoccupancy', 'field_maxoccupancy', 'field_roomamenity'];
        foreach ($readonlyFields as $rof) {
          $form[$rof]['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
          $form[$rof]['widget'][0]['value']['#description'] = t('This is a readonly import field');

But I've got problems with those fields with the "advanced" (non HTML <input type="text|number|...">) widgets:

  • body is a text field with CKeditor
  • field_image is an ER field with Entity browser widget for media entities
  • field_roomamenity is an ER field with autocomplete widget for taxonomy terms

Can anybody give me a hint how to set those widgets programmatically to readonly?

I know there is a Read-only Field Widget module. But I don't want to change the widget type, because editors can create their own items, which are not served by an external datasource (hence fields remote_XXX). In those cases the editors need those widgets in "write mode".

  • I think you need to replace those widgets by item elements rather than try to tweak their attributes. But you'll have to work out how to get the default value for the item depending on the field type. – Alfred Armstrong Dec 7 '18 at 10:46
  • @AlfredArmstrong Is it possible to dynamically change the field widget? I've found this D7 post using hook_field_widget_properties_alter, but this hook does not exist in D8's field.api.php – Hudri Dec 7 '18 at 12:17
  • Unless I am mistaken you can simply replace the whole array for the field for one with #type of 'item'. You don't need to get clever with the widget as you are making the field read-only. I am sure there will be complications but I don't think this aspect is one of them. – Alfred Armstrong Dec 7 '18 at 12:26

Your Answer

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

Browse other questions tagged or ask your own question.