Drupal - How to use presave hook to save a field value as node title?
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;
}
}
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
}
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;
}
}