Currently working with the Commerce module in Drupal 7.

I've hooked the product creation form (using hook_form_alter()) to include a custom validation function. I have an image for each product that is generated on the fly and needs to be associated with the relevant product. The name of the image field is 'field_pchem_structure_image.'

I'm able to create and save the image, but I need to make sure it is added to the product when the product is saved. I've tried setting:

$form_state['values']['field_pchem_structure_image'] = $file;

However, this does not seem to work. Could someone please explain how to do this?

2 Answers 2


I installed Commerce Customizable Products and created a new line item type. This enabled me to create another product type with an upload field in the add to cart form users can use to upload file to the site. Also use rules obviously to do some more backend stuff, like change file location (that's set with a token uid) to be updated on username change and lots more. Can do lots of fun stuff with media/file entity, but your fix also works, just adding this for the search bot arena ;)


I ended up solving this by using hook_field_attach_submit().

The basic process was this:

  • Save the file using $file = file_save_data()
  • Set a hidden field in $form_state to store $file
  • Ex: $form_state['hidden_fid_val'] = array( '#type' => 'hidden', '#value' => $file );

  • In hook_field_attach_submit() do some basic entity type checking (e.g. if ($entity_type == '<your_entity_type_here>') { ... }

  • Typecast the file object as an array

  • Set the correct entity field to the file array ( $entity-><entity_field_name>['und'][0] = $file;)

The file should then populate the correct field after save.

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.