Programatically Creating Comment Entities in Drupal 7

Creating and manipulating content (entities) has become much less complex with EntityAPI in Drupal 7.

There are lots of examples out there for manipulating nodes, creating custom entity types, etc. Here's a quick one for programatically creating a comment entity and attaching it to a node.

For demonstration's sake, suppose we want to attach a comment whenever a node of a certain type is created, and assign it to a given user.


/** * Implements hook_node_insert(). */ function qm_register_node_insert($node) { // If it's not a user profile comments node. if (empty($node->type) || $node->type != 'user_profile_comment') { // Bail out. return NULL; } // Create a comment entity attached to the user's profile comment node and // authored by the Event Administrator so they get comment updates. $comment = entity_create('comment', array( 'nid' => $node->nid, 'uid' => QM_REGISTER_EVENT_ADMIN_UID, 'node_type' => 'comment_node_user_profile_comment', )); // Entity API. $comment_wrapper = entity_metadata_wrapper('comment', $comment); // Set the comment body. $comment_wrapper->comment_body = array( 'value' => t('Your exhibitor / sponsor request was received and will be reviewed.'), 'format' => 'plain_text', ); // Save the comment. $comment_wrapper->save(); }

Notes

  • The only real trip-up was the node_type key in the comment entity. Drupal was throwing errors about a missing bundle property, but this is really what it was looking for.
  • You may be able to just use some combination of entity_save, and/or comment_submit, comment_save, etc. This would prevent the entity_metadata_wrapper and EntityAPI requirement. However, I find it much easier and always end up using it many times per project anyway.

Error Messages

Including these to help on search results for people with similar issues

  1. Missing bundle property on entity of type X (node, comment, etc)
    • See the first note above
  2. Invalid data value given. Be sure it matches the required data type and format
    • This can occur when setting the value of a filtered text field without specifying the format. See // Set the comment body above.

Context

To put this in context, this sample usage was our actual use case on a project. We were using User Profile Comments as a simple way for 1-1 communication between administrators and users who were going through the signup process for an event registration system. Somewhat along the lines of a ticketing system like Support module, or a messaging system like Privatemsg, but much (much) more simple & lightweight.

The ideas was to have the event administrator programatically attach a comment (to the user profile comment node type) each time a user signed up. Then, in turn, subscribe them via Comment Notify.

Remember, just because there's a module for that, there's a good chance you don't actually need (most) of it!