1

I need to modify the node title while saving the node ID. I implemented hook_form_FORM_ID_alter() as follows.

/**
 * Implements hook_form_FORM_ID_alter()
 */
function module_name_form_form_id_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['title']['#access'] = FALSE;
  $form['#entity_builders'][] = 'change_node_title';   
}

function change_node_title($entity_type, NodeInterface $node, $form, FormStateInterface $form_state) {
  $node_id = $node->nid->value; // Not getting the node details
  $node->setTitle('Custom Title -' . $node_id);
}

The node details aren't found from the #entity_builders callback.

How can modify the node title before saving it? I don't want to use any custom modules for this. I don't want to use hook_node_presave() either, as it would affect the cloned nodes.

1
  • 1
    Using same code which is working fine for me. Is there any changes in your code?
    – Ajay Reddy
    Mar 20 '18 at 11:23
4

Never tried entity_buildres but you could probably use the old and tried way of adding a submit handler

function MODULENAME_form_alter(&$form, &$form_state, $form_id) { 
  // this is the create form id, edit form would be node_article_edit_form
  if($form_id == 'node_article_form') {
    $form['actions']['submit']['#submit'][] = 'MODULENAME_change_title';
  }   
}

function MODULENAME_change_title($form, $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  $node->setTitle('Custom Title - ' . $node->id());
  $node->save();
}
5
  • Uncaught PHP Exception Drupal\\Core\\Entity\\EntityStorageException: "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null:
    – KTM
    Mar 20 '18 at 11:48
  • The code is working on my setup just did some word changes from my setup, can you try on a clean install ?
    – GiorgosK
    Mar 20 '18 at 11:52
  • 1
    Even it's working for me also with just small change as $node->id => $node->id(). @RubberDuckIsKing check with new Drupal installation or any other content type.
    – Ajay Reddy
    Mar 20 '18 at 11:55
  • Yes its working now ! seems buggy sometimes
    – KTM
    Mar 20 '18 at 11:59
  • @AAjayReddy corrected the typo
    – GiorgosK
    Mar 20 '18 at 12:01
0

I would advice to use hook_entity_presave() for this:

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function MYMODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  // save a different value as title
  if ($entity->bundle() == 'NODE_TYPE') {
    $entity->title = 'Custom Title - ' . $entity->id();
  }
}
1
  • We don't have node ID for the new nodes, it will work only for updated nodes May 28 at 11:52

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.