Programmatically saving and updating entities

Automating the creation of users, nodes, and other Drupal entities is a common task. Third-party software is often used to do this and other tasks. It's important to know how the underlying data works so that you can find and change the correct code.

There is a good tutorial for entity creation on Drupal 7 at: How to programmatically create nodes, comments and taxonomies in Drupal 7.

One important thing to know is that Drupal 7 is built on the entity system. The entity system is a data model system that provides a generic storage interface (CRUD) that is now at the very heart of users, nodes, and taxonomy terms and will take an even more prominent role in the future. In versions prior to 7, Drupal provided helper functions for its major data structures like node_save(), node_delete(), user_save(); these are still available today, but now they use the entity system underneath.

If you want to learn more about the entity system, you can read some more useful information at Drupal Entities - Part 1 - Moving beyond nodes.

The second major system to grasp is the field API, which allows you to define a field of any data type that isn't attached to any data structure yet, and then bundle the field to a specific node type, user object, or other entity. This is already implemented, and because of this existing "save" hooks for nodes, users, and terms will save the field data you had on a node or user object.

The field API allows you to easily create new entities (for example, a term) like this:

$term = new stdClass();$term->name = ‘Term Name’;$term->vid = 1;$term->field_custom_field_name[LANGUAGE_NONE][0]['value'] = ‘Some value’;taxonomy_term_save($term);

You can also use it to update existing data:

$node = node_load(10);$node->field_screenshot[LANGUAGE_NONE]['0']['fid'] = $file->fid;node_save($node);

You can achieve other types of functionality by applying these ideas on user objects by using user_load() and user_save() on your entities. You can also use this to temporarily create a field on users from the user interface and store images on example user objects, so that you can manually load your user and look at exactly how the data structure looks with the var_dump() function. By replicating how the objects and arrays look, you can automate everything you want to do. Functions like file_load(), file_copy(), and file_save() also help you to deal with uploaded files or files that you manually copied from your location on the server.

Contact supportStill need assistance? Contact Acquia Support