0

I am developing a Drupal 8 website and I added a new field to a custom content type called Download. This field is updated each time a file is downloaded from this content type. I use hook_file_access to find a node from which a file was downloaded. I then get current download count value by getting a field from a node. The value is incremented by 1 and the new value is stored in the field. I then save the node to store the value. Below is the code used for node (field change) saving:

$field_download_count = $entity->get('field_download_count')->get(0);
if ($field_download_count == null) {
    $download_count = 1;
} else {
    $download_count = $field_download_count->getValue()['value'];
    $download_count += 1;
}
$entity->set('field_download_count', $download_count);
$entity->setNewRevision(false);
$entity->save();

The problem is that with this code, updated date of the content changes and this is a problem for me as I use updated date in many view and data is not valid as per this code, updated date is changed with each file download from the node.

Is there a way to store the field value only on Drupal 8?

In Drupal 7, one could use field_attach_update but this function was removed in Drupal 8.

I tried to update the field value using Drupal update SQL function, but this is not a proper way and also didn't play well with a cache system.

  • Are you sure this hook works? It's for access checks and they are usually cached for roles or hashed permissions. And statistic data doesn't belong in the entity, you should store it in an extra table. – 4k4 Oct 30 '17 at 19:41
  • The hook is tested and works. It is also used in download_count module for Drupal 8. I store this data as a field because I later use it in views to sort data. With custom table, there would be too much work with implementation in view or any other third party module that only works with field data. – Klemen Oct 30 '17 at 20:50
  • OK, if there is a module why not use it? BTW this module stores the data also in an extra table and provides the Views integration in hook_views_data(): cgit.drupalcode.org/download_count/tree/… – 4k4 Oct 30 '17 at 21:11
1

You could directly update the field table in the database ?

$database = \Drupal::database(); $result = $database->query("UPDATE node__field_download_count SET field_download_count = field_download_count + 1 WHERE entity_id = " . $entity_id);

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.