1

I have a content type (Structure) to which I added a text computed field.

In a module I added the following code.

function computed_field_field_reference_compute($entity_type_manager, $node, $fields, $delta) {
  return GedProjectUtils::computeReference($node);
}

It works: In view mode, the field is well calculated.

Now I would like to show this field on edit mode. I added this code to the module.

function gedproject_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_structure_edit_form') {
    $form['field_reference']['widget'][0]['value']['#type']='textfield';
    $form['field_reference']['widget'][0]['value']['#title']='Référence';
    $form['field_reference']['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
  }
}

The field is shown empty.

screenshot

What do I need to change in the code I added?

2
  • $form['field_reference']['widget'][0]['value']['#value'] = $value;
    – leymannx
    Apr 11 '21 at 13:25
  • Thanks, but how to init $value. I found the solution
    – Benoit
    Apr 11 '21 at 13:53
2

So the solution found is : I catched the node id from $form_state and then catched the field value from the node like this :

 /**
 * Implements hook_form_alter
 *
 */
function gedproject_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_structure_edit_form') {
    $form_object = $form_state->getFormObject();
    if ($form_object instanceof EntityForm) {
      $entity = $form_object->getEntity();
      $value = $entity->get('field_reference')->value;
      $form['field_reference']['widget'][0]['value']['#value'] = $value;
      $form['field_reference']['widget'][0]['value']['#type']='textfield';
      $form['field_reference']['widget'][0]['value']['#title']='Référence';
      $form['field_reference']['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
    }
  }
}
1

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.