Drupal, Programmatically create registration entity

Submitted by swim on Wed, 09/04/2013 - 04:05

Recently we required a simple method for allowing users to register to the site and an event through a single form. We are using the Entity Registration (1.x) module in conjunction with Commerce Entity Registration. The form was available for each event on the corresponding node pages. Essentially the user required an account to attend an event as follow up & post event information was needed.

 * Helper function, register user for event.
 * @param
 *  User object or user id of account to register.
 * @param
 *  Node id of target event.
function _MYMODULE_events_register_user($user, $nid) {
  // Attempt to load the user object if not passed directly.
  if (is_numeric($user) && !is_object($user)) {
    $user = user_load($user);
  // Load our event node.
  $node = node_load($nid);
  if (!$node) {
  // Is the user already registered?
  $is_user_registered = _MYMODULE_events_return_registered_users($uid, $nid);
  if (!$is_user_registered) {
    // Create the associated registration entity.
    $registration = entity_create('registration', array(
      'user_uid' => $user->uid,
      'author_uid' => $user->uid,
      'type' => 'event',
      'entity_type' => 'node',
      'entity_id' => $nid,
      'count' => 1,

 * Helper function
 * @return (boolean)
 *  Return false if user is not registered.
function _MYMODULE_events_return_registered_users($uid, $entity_id) {
  $result = FALSE;

  $query = db_select('registration', 'r')
    ->fields('r', array('registration_id'))
    ->condition('entity_id', $entity_id)
    ->condition('user_uid', $uid)
  if ($query) {
    $result = TRUE;

  return $result;

Simply passing the account object or the user id with the associated event node id will be enough to register the user & or check if they are already registered.

  _MYMODULE_events_register_user($account, $form_state['values']['event_nid']);