I added an additional field with a type "File" to an "article" content type. Now I need to get a fid
of the uploaded file in hook_node_view()
. I use for this the next code:
$my_form['fid']['#value'] = $node->field_image_svg[$node->language][0]['fid'];
The problem is that when I check "Include file in display" before saving a node, I get a fid
correctly. But when I do not check, I get a warning:
Notice: Undefined offset: 0 in testmodule_node_view()
What's the problem? Is there way to get a fid
of an uploaded file not depending on whether the file is displayed or not?
You are using the Enable Display field setting for the file field:
When the "Include file in display" checkbox is checked, you allow it to be rendered in the view mode of the node and so your field gets added into the language array of the field_image_svg
field:
$node->field_image_svg[$node->language][0]['fid']
If unchecked it will not be allowed to and the language array will not keep the file information:
$node->field_image_svg[$node->language]
So if you want to get the fid not depending on that checkbox and still use it as a setting, you are forced to make a check on wether it exists or not to get rid of the notice and instead get the fid with:
$fid = db_query('SELECT fid FROM {file_usage} WHERE id = :id',array(':id' => $node->nid))->fetchField();
Another solution would be to remove the checbox (in field settings) and manage it to be hidden or shown through Manage display. This will keep the file's information in hook_node_view
.
Hope this helps.