1

I'm trying to save a file into my Profile2 entity, I've taken the user through a multi-step form, I've saved all the data and at the point I want to input my data into my profile object, I have a variable which 'holds' the file object which has already been uploaded before this point.

However, I can't find out what code I need to run to tell my profile2 entity (in pseudo terms)

field_cover_letter = $file

I've tried opening up a profile object of an existing account to see what it saves it as, which it seems to just be an array of the file object as well, but I tried typecasting my object to an array and using those values, but it throws a PDO. There must be a simple command to add a file to the profile2 object?

Cheers

1 Answer 1

0

If you are working with an unmanaged file, the following three-step process should do the trick:

  1. Move the file (if necessary) to its final home defined by the file field on the entity.
  2. Create a file object (see file_save_data() for some hints on how to do this) and then save it using file_save(). This will turn the file from unmanaged to managed.
  3. Add the file reference to the file field. You may also want to add an entry in the file usage table by calling file_usage_add(). Here is a code snippet for adding a file object to a file field on a node.

    $node->file_field_name[LANGUAGE_NONE][0] = array( 'fid' => $saved_file_object->fid, 'display' => 1, 'description' => '', );

This assumes the file field accepts only one entry (index 0).

3
  • I've tried doing something along that line, at the moment I've already typecast my file object (which contains fid, uid, display, description etc) to an array and saving it to my profile2 object, but that is what throws the PDO Commented Oct 23, 2013 at 8:24
  • Right, I'm not entirely sure why, but when I tried adding JUST those fields you recommended in the code above, it seems to work. Even though those fields were still being passed in the array before, it didn't like it... still a little confused, but it works Commented Oct 23, 2013 at 13:03
  • You don't need to pass all the file object's properties to the file field. The latter only requires the three properties in the code snippet above. You can see this by looking at the database schema for the {file_managed} table and file field instance schema.
    – mesch
    Commented Oct 23, 2013 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.