如何使用presave挂钩将字段值保存为节点标题?


8

我在节点类型“天”中有一个自定义日期字段。保存(或编辑然后保存)节点后,我想获取field_date值(而不是发布日期)并将其保存到title字段中。

我想知道如何使用一个模块来:

hook_presave

  • 获取字段值

  • 将标题设置为字段值

  • 保存节点


Answers:


16

您需要实现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
当节点作为$entity对象传递到挂钩中时,为什么还要加载该节点?
Jamie Hollern

2
另外,在预保存钩子中调用$ entity-> save()会导致无限递归。这不是正确的答案。
Jamie Hollern

1
@JamieHollern是的,代码有问题,现在我用正确的答案进行编辑。谢谢你的评论。
Adrian Cid Almaguer

3

对于类型为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

对于类型配置文件的实体,我使用了以下代码

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

0

这对我有用,它根据内容类型使用预保存钩子来获取和设置日期字段值

/**
 * 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));
 }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.