23 Apr.2017

Drupal 10: How to programmatically create a title for a new node

Programmatically create/update a title for a new node

Here's how to do it with an entity builder callback without any additional contrib module like "Automatic Entity Label" or "Automatic Nodetitles", using only Drupal core functionality.

In this example, we assume that we need to create titles in the format like the following: "'Lessons with Mark NY" and apply our rules to "lesson" content type only.

File
custom.module
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;
 
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function custom_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_lesson_form' || $form_id == 'node_lesson_edit_form') {
    $form['title']['#access'] = FALSE;
    $form['#entity_builders'][] = 'custom_lesson_node_title_builder';
  }
}
 
/**
 * Title builder for lessons content type.
 *
 * @param $entity_type
 * @param \Drupal\node\NodeInterface $node
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function custom_lesson_node_title_builder($entity_type, NodeInterface $node, $form, FormStateInterface $form_state) {
  $author = $node->getOwner()->getDisplayName();
  $venue = $node->get('field_venue')->entity->getTitle();
 
  $node->setTitle('Lessons with ' . $author . ' ' . $venue);
}

Ruslan Piskarov

Ukraine
PHP/WEB Developer / Drupal Expert. More than 11 years of experience delivering Drupal based General Purpose solutions for different sectors such as Job Boards, Product Portfolios, Geo Coding, Real Estate solutions, E-Commerce, Classifieds, Corporate and online Magazines/Newspapers.

Tags