0

I have created a custom compound field which contains a managed_file element in the field widget form.

The issue I am having is not with saving the file, but with adding the file usage information.

I picked hook_field_presave based on some research, but this is not working for new content or translating the node.

function MODULE_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      foreach ($items as $delta => &$item) {

        // save file permenantly
        if ($item['IMAGE']) {
          $file = file_load($item['IMAGE']);
          $file->status = 1;
          file_save($file);
          file_usage_add($file, 'MODULE', 'FIELD_TYPE', $entity->nid);
        }
      }
      break;
  }
}

The issue here is that when I save a newly created node, at this point, $entity->nid has not been defined. This number is required by file_usage_add.

Is there another hook that I can use to do what I'm trying to do?

1

You could add the file usage by implementing hook_node_insert which gives you all node fields besides what you are looking for nid and the fid using file_load in that case you could add file usage

0

Since I'm dealing with fields, hook_node_insert was overkill, but it got me on the right track.

The answer is to remove the file_usage_add logic from hook_field_presave and put it in hook_field_insert and hook_field_update.

Remove from hook_field_presave:

function MODULE_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      // no file logic here
      break;
  }
}

Add to hook_field_insert:

function MODULE_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      foreach ($items as $delta => &$item) {

        // save file permenantly
        if ($item['IMAGE']) {
          $file = file_load($item['IMAGE']);
          $file->status = 1;
          file_save($file);
          file_usage_add($file, 'MODULE', 'FIELD_TYPE', $entity->nid);
        }
      }
      break;
  }
}

Duplicate for hook_field_update:

function MODULE_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      foreach ($items as $delta => &$item) {

        // save file permenantly
        if ($item['IMAGE']) {
          $file = file_load($item['IMAGE']);
          $file->status = 1;
          file_save($file);
          file_usage_add($file, 'MODULE', 'FIELD_TYPE', $entity->nid);
        }
      }
      break;
  }
}

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.