Skip to content

Instantly share code, notes, and snippets.

@vladdancer
Created November 25, 2013 15:14
Show Gist options
  • Save vladdancer/7642763 to your computer and use it in GitHub Desktop.
Save vladdancer/7642763 to your computer and use it in GitHub Desktop.
function entity_property_values_create_entity($entity_type, $values = array()) {
if (entity_type_supports($entity_type, 'create')) {
$info = entity_get_info($entity_type);
// Create the initial entity by passing the values for all 'entity keys'
// to entity_create().
$entity_keys = array_filter($info['entity keys']);
$creation_values = array_intersect_key($values, array_flip($entity_keys));
// In case the bundle key does not match the property that sets it, ensure
// the bundle key is initialized somehow, so entity_extract_ids()
// does not bail out during wrapper creation.
if (!empty($info['entity keys']['bundle'])) {
$creation_values += array($info['entity keys']['bundle'] => FALSE);
}
$entity = entity_create($entity_type, $creation_values);
// Now set the remaining values using the wrapper.
$wrapper = entity_metadata_wrapper($entity_type, $entity);
foreach ($values as $key => $value) {
if (!in_array($key, $info['entity keys'])) {
if (isset($wrapper->$key)) {
$wrapper->$key->set($value);
}
else {
$entity->$key = $value;
}
}
}
// @todo: Once we require Drupal 7.7 or later, verify the entity has
// now a valid bundle and throw the EntityMalformedException if not.
return $wrapper;
}
return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment