I need to modify the node title while saving the node id am using 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);

But the node details is not getting in the #entity_builders function callback. Any idea on how to modify the node title with the node it before saving it? I don't want to use any custom modules for this. I don't want to use in hook_node_presave either (as it would affect the cloned nodes)

  • 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

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());
|improve this answer|||||
  • Uncaught PHP Exception Drupal\\Core\\Entity\\EntityStorageException: "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null: – Crazyrubixfan 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 – Crazyrubixfan Mar 20 '18 at 11:59
  • @AAjayReddy corrected the typo – GiorgosK Mar 20 '18 at 12:01

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.