8

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

13

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;
  }
}
  • 1
    Why would you load the node when it is being passed into the hook as the $entity object? – Jamie Hollern Nov 25 '17 at 9:23
  • 2
    Also, calling $entity->save() in a presave hook causes infinite recursion. This isn't a correct answer. – Jamie Hollern Nov 25 '17 at 9:56
  • 1
    @JamieHollern You're right, the code had problems, now I edit with the correct answer. Thanks for your comment. – Adrian Cid Almaguer Nov 26 '17 at 20:34
3

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
}
3

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;
 }
}

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.