Answers:
/**
* 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;
}
}
$entity
对象传递到挂钩中时,为什么还要加载该节点?
对于类型为user的实体
/**
* Implements hook_entity_presave().
*/
function YOUR_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
$entity->field_uhid->value = 'testing'; //set value for field
}
对于类型配置文件的实体,我使用了以下代码
/**
* 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;
}
}
这对我有用,它根据内容类型使用预保存钩子来获取和设置日期字段值
/**
* 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));
}
}