Drupal 8 - Pre-fill a form field

Use case

Suppose we have an song content type which contains a reference field for another content type called album. Now whenever an editor will add a new song, he will have to add reference album manually. We can improve authoring experience by pre-filling the album reference field whenever album id is available.

Solution

We can use hook_form_FORM_ID_alter, to alter node add form and set the default value for reference field.

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function music_form_node_song_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  // get album node id from request
  $nodeId = \Drupal::request()->attributes->get('node');
  // load node entity
  $node = is_numeric($nodeId) ? \Drupal\node\Entity\Node::load($nodeId) : null;

  if ($node && isset($form['field_album'])) {
    // set default value for reference field
    $form['field_album']['widget'][0]['target_id']['#default_value'] = $node;
  }
}

In above code, field_album is the machine name of the reference field. Also, we assume that album node id is available in the current request with the name of node.

If you need help regarding how to pass node id to add form, you can look at Action example.

In case the field that you want to pre-fill is not a reference field, then you can set the default value like following

// set default value
$form['field_album']['widget'][0]['value']['#default_value'] = $value;

  PHP, Drupal 8