I'm trying to auto-fill the title a content creation form in Drupal 8 with the user ID of the person creating the node, but I can't seem to get past step 1, which is having the title default to anything. I've made a module and added this code to it:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "new_content_type_node_form") {
    $form['title']['#default_value'] = 'Test12';

On the creation screen I'm using dpm to look at the $form var, and it's showing that the title does have a value in #default_value, and it is Test12, but when the form renders the title field is blank.

It seems like the way to do this in Drupal 7 and earlier was drupal_set_title(), but I can't find the equivalent for Drupal 8. Any ideas?

3 Answers 3


The preferred way to do this is to use the create hook.

use Drupal\node\NodeInterface;

function mymodule_node_create(NodeInterface $node) {
  if ($node->getType() == 'node_type') {
    $node->title = 'Test12';

Your code, at least without also additionally checking whether the node is new, will replace the title when editing nodes as well.

  • This was not working for me because the client side validation was preventing the form form submitting with no value. The idea behind what I was doing was to assign a title programmatically then hide the field so the user never had to do anything.
    – Samsquanch
    Commented Apr 2, 2014 at 21:47
  • This is set before the form is displayed, which will then pick up the value and display it pre-filled in the form.
    – Berdir
    Commented Apr 2, 2014 at 22:05
  • Oh, I must have been thinking of another function then. I'll accept your answer as the preferred method of accomplishing this.
    – Samsquanch
    Commented Apr 2, 2014 at 22:26

Solved by digging a little deeper into the form array:

$form['title']['widget'][0]['value']['#default_value'] = 'Test12';

You can check also Automatic Entity Label module. (Maybe look through the code)

With this module, you have access to the tokens. https://www.drupal.org/files/images/auto-entity-labels.png

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.