10

I have a custom date field in a node type 'day'. When the node is saved (or edited then saved), I would like to get the field_date value (not the published date) and save it into the title field.

I would like to know how, perhaps using a module to:

hook_presave

  • GET FIELD VALUE

  • SET TITLE AS FIELD VALUE

  • SAVE NODE

1

5 Answers 5

22

You need to implement the hook_entity_presave()

/**
 * Implements hook_entity_presave().
 */
function YOUR_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  switch ($entity->bundle()) {
    // Here you modify only your day content type
    case 'day':
      // Setting the title with the value of field_date.
      $entity->setTitle($entity->get('field_date')->value);
     break;
  }
}
3
  • 1
    Why would you load the node when it is being passed into the hook as the $entity object? Commented Nov 25, 2017 at 9:23
  • 3
    Also, calling $entity->save() in a presave hook causes infinite recursion. This isn't a correct answer. Commented Nov 25, 2017 at 9:56
  • 2
    @JamieHollern You're right, the code had problems, now I edit with the correct answer. Thanks for your comment. Commented Nov 26, 2017 at 20:34
6

For entity of type profile i have used below code

/**
 * Implements hook_entity_presave().
 */
function YOUR_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityType()->id() == 'profile') {
    $zipcode = $entity->field_zip_code->value;
    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$zipcode."&sensor=false";
    $details=file_get_contents($url);
    $result = json_decode($details,true);
    $lat=$result['results'][0]['geometry']['location']['lat'];
    $lng=$result['results'][0]['geometry']['location']['lng'];
    $entity->field_geolocation->lat = $lat;
    $entity->field_geolocation->lng = $lng;
 }
}
4

For entity of type user

/**
 * Implements hook_entity_presave().
 */
function YOUR_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity->field_uhid->value = 'testing';     //set value for field
}
1

This worked for me to get and set the date field value using presave hook based on content type

/**
 * Implements hook_entity_presave().
 */

function YOUR_MODULE_global_entity_presave(Drupal\Core\Entity\EntityInterface $entity) 
{
  if ($entity->bundle() == 'blog') {
    $published = $entity->get('created')->value;
    $entity->set('field_published_date', date('Y-m-d\TH:i:s', $published));
 }
}
0

You can alter and save the title to any available field using Automatic Entity Label https://www.drupal.org/project/auto_entitylabel

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.