I'm currently facing a situation where I need to create a new instance of a certain entity and attach a file to it.
Since the main entity should 'reference' the file (the same way a node references a user, by an entity property) there are several things I can do.
- Save the main entity
- Save the file
- Update the main entity with the file id.
- Save the file with temporary status
- Save the main entity with the file id.
- Update the file to a permanent status.
Since both methods would require me to perform 3 operations in a row I thought it might be simpler to do this with an entity metadata wrapper like this:
// Create the file entity. $f = entity_create('file', array( 'uid' => $data->uid, 'filename' => $data->filename, 'url' => $data->uri, 'filemime' => $data->filemime, 'filesize' => $data->filesize, 'status' => 1, )); // Create the main entity. $e = entity_create('main_entity', array()); $entity= entity_metadata_wrapper('main_entity', $e); $entity->title = $data->title; $entity->... = $data->... $entity->file = $f; $entity->save();
This however saves the main entity with
$entity->file = 0, and the file does not show up in
file_managed. Which conflicts with the answer to "How to set value of file field with entity_metadata_wrapper" that implies I can use a new stdClass().
Is there some other error in my entity metadata implementation, or is it not possible to save (create) two entities at once like this?
Apparently my understanding on entity metadata wrappers was completely wrong; While reading the comments on the Entity metadata wrappers documentation page I assumed I could do things like this:
// Changing the author's email. $wrapped_node->author->mail->set('firstname.lastname@example.org'); // Adding to the answer of @Zakaria Elhariri. $wrapped_node->field_page->status->set(0); // Save the changes. $wrapped_node->save();
I thought saving the main entity would update the nested entities, so I'd expect the email of my account to be changed and the linked node of Zakaria Elhariri's answer to be unpublished. But none of this is true. Why is this is the examples?
To update the user's mail address one could use
<?php $wrapper->author->mail->set('email@example.com'); ?>
Or is entity metadata wrapper broken somehow?