Kirk
Kirk

Reputation: 16245

Proper way to create a node alias that is the filename

I'm using a FileFeild Image field to get an image and then I'm using File (Field) Paths to rename the file to random characters.

What I'm trying to do

Problem

The image does get renamed with File (Field) Paths and that works perfectly. The trouble is that I can't get the node to rename to match the newly renamed filename.

What I've tried

I've tried to use Pathauto where I set a pattern for the Image content type of [node:field_image], Pathauto fails to add an alias on initial node creation. I suspect this has to do with the order of the hook calls.

I also tried this hook

function MYMODULE_node_insert($node) {
 if ($node->type == 'image') {
   $filename = $node->field_image['und'][0]['filename'];
   // do stuff
   $node->path['alias'] = $result;
 }
}

In this hook, $node->field_image doesn't seem to have all of the file data at this point and is not yet available.

Question

Does anyone know how to do this, even if I write a custom module? What hooks will allow me to do this?

Is there a way to get the file name with Custom Tokens instead?

Answer

I eventually tracked down in the File (Field) Paths code a hook to implement and using @Clive's code below, I was able to create an alias. I created a module to do this because File (Field) Paths doesn't appear to work directly with Pathauto.

hook_filefield_paths_process_file

Upvotes: 2

Views: 232

Answers (1)

Clive
Clive

Reputation: 36955

The node has already been saved in hook_node_insert()/hook_node_update() which is why your changes aren't being reflected.

Fortunately there's hook_node_presave(). If you put your code in that hook it should work.

The file field will only contain the ID of the file so you'll need to load that object to get the filename:

$items = field_get_items('node', $node, 'field_image');
if ($items) {
  $file = file_load($items[0]['fid']);
  $filename = $file->filename;
  // ...
}

If you install the Pathauto module, though, you'll be able to assign a pattern to the image node type which contains the image field's filename without any code at all.

Upvotes: 2

Related Questions