In Drupal 7, I have a field on both nodes and users that I'd like to update from a single function. What's the most efficient and what is best practice for updating by entity id?

I want the client to hit my Services REST API endpoint with an entity id and value. So far I've got:

function json_field_resource_update($entity_id = NULL, $data = array()) {
  global $user;

  $entity_type = 'user';
  $entity = entity_load_single($entity_type, $entity_id);
  if (!$entity) {
    $entity_type = 'node';
    $entity = entity_load_single($entity_type, $entity_id);
  if (!$entity) {
    return services_error(t('No user or node entity found by entity_id !entity_id', array('!entity_id' => $entity_id)), 406);
  if (!entity_access('update', $entity_type, $entity)) {
    return services_error(t('Permission denied for !user to update entity !entity_id', array('!user' => $user->name, '!entity_id' => $entity_id)), 403);

The purpose of the above is to first check whether this entity Id refers to a user or a node then perform the appropriate access check. This works ok, but am I missing some magical all-in-one Entity API function or something?

2 Answers 2


I think the entity metadata wrapper is semi indiscriminate aslong as the field is the exactly the same on both entities. So you can just wrap it and then use the default set/get methods

// All your code (it looks fine) 
$wrapper = entity_metadata_wrapper($entity_type, $entity);

More info on the metadata wrapper


am I missing some magical all-in-one Entity API function or something?

You're not. Think of an entity as a database table, and imagine trying to query it. This is what you'd have with your current workflow:


Notice the table name is missing, because no one has provided it.

Same thing for entities; you need to provide the type of entity you're trying to load, otherwise Drupal can't know which type to look for.

You need to get that entity type into the request. Best practice would be to properly separate your concerns, e.g. have a separate resource for updating nodes and users respectively. Remember, conceptually speaking, you're updating an entity here, not a field, so the layout of your resource should really reflect that.

The services modules actually has node and user update resources included by default, so you don't even need to do any extra work.

If you're hell-bent on having a separate resource just for updating this field, then you need to pass the entity type along when you consume the resource, or provide a different parameter that you can use to distinguish the type of entity you're trying to update. Drupal can't help you to make the decision, it simply doesn't know what you mean when you give it nothing but a number to work with.

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.