5

I want the title field of each new node of the Agenda content type to be constructed automatically from a date field in that same node.

I have variously tried setting the #default_value and #value on the $form array in hook_form_FORM_ID_alter() but without effect.

How can I achieve this?

5 Answers 5

10

Here's how to do it with an entity builder callback.

<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

//Implements hook_form_FORM_ID_alter()
function agenda_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    $form['title']['#access'] = FALSE;
    $form['#entity_builders'][] = 'agenda_node_builder';

}

function agenda_node_builder($entity_type, NodeInterface $node, $form, FormStateInterface $form_state)
{

    $date_of_meeting = $node->field_date_of_meeting->date->format('Y-m-d');
    $node->setTitle('Agenda for meeting on '.$date_of_meeting);

}    

Notes:

  1. I found that the callback had to be set up in hook_form_BASE_FORM_ID_alter() rather than hook_form_FORM_ID_alter in which case it didn't get called.
    Didn't get to the bottom of this but it's probably something to do with the fact that alter hooks are called in the following order: hook_form_alter(), hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter().

  2. Nodes #entity_builders offer a Node entity object for modification before being stored when the form is eventually submitted.

Thanks to @Berdir for the pointers.

5

Or possibly you could use hook_entity_presave() or hook_node_presave(), and change the value of the field there.

3

Another way to accomplish this is with this code:

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_node_CONTENT_TYPE_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  //Hide the title
  $form['title']['#access'] = FALSE;
}

/**
 * Implements hook_ENTITY_TYPE_create
 */
function MODULE_node_create(NodeInterface $node) {
  switch ($node->getType()) {
    case 'YOUR_CONTENT_TYPE':
      //Change the title
      $node->title = 'TEXT ' . $node->field_YOUR_FIELD->date->format('d-m-Y');
      break;
  }
}
3

You can use the Automatic Nodetitles and the Token modules to achieve this.

I know that the Automatic Nodetitles module doesn't have a Drupal 8 version yet, but if you read Port Automatic Nodetitles to Drupal 8, you can find a working solution.

1

The Automatic Entity Label module should be a good solution and has a D8 port (DEV version only for now).

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.