Làm cách nào để sử dụng hook presave để lưu giá trị trường làm tiêu đề nút?


8

Tôi có trường ngày tùy chỉnh trong loại nút 'ngày'. Khi nút được lưu (hoặc chỉnh sửa rồi lưu), tôi muốn lấy giá trị field_date (không phải ngày xuất bản) và lưu nó vào trường tiêu đề.

Tôi muốn biết làm thế nào, có lẽ sử dụng một mô-đun để:

hook_presave

  • NHẬN GIÁ TRỊ L FINH VỰC

  • THIẾT LẬP TITLE NHƯ GIÁ TRỊ L FINH VỰC

  • TIẾT KIỆM NODE


Câu trả lời:


16

Bạn cần triển khai 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
Tại sao bạn tải nút khi nó được truyền vào hook làm $entityđối tượng?
— Jamie Hollern

2
Ngoài ra, việc gọi $ entity-> save () trong hook có sẵn sẽ gây ra đệ quy vô hạn. Đây không phải là một câu trả lời đúng.
— Jamie Hollern

1
@JamieHollern Bạn nói đúng, mã có vấn đề, bây giờ tôi chỉnh sửa với câu trả lời đúng. Cám ơn bạn đã góp ý.
— Adrian Cid Almaguer

3

Đối với thực thể của loại người dùng

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

3

Đối với thực thể của hồ sơ loại tôi đã sử dụng mã dưới đây

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

Điều này giúp tôi có được và thiết lập giá trị trường ngày bằng cách sử dụng hook presave dựa trên loại nội dung / ** * Thực hiện hook_entity_presave (). * /

chức năng YOU_MODULE_global_entity_presave (Drupal \ Core \ Entity \ EntityInterface $ entity) {if ($ entity-> bundle () == 'blog') {$ đã xuất bản = $ entity-> get ('created') -> value; $ entity-> set ('field_published_date', ngày ('Ymd \ TH: i: s', $ đã xuất bản)); }}

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookie và Chính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.