From da89e2eb0c0af61c6bfa955888336b177e3825bd Mon Sep 17 00:00:00 2001
From: Colan Schwartz <colan@58704.no-reply.drupal.org>
Date: Fri, 6 May 2016 19:09:42 -0400
Subject: [PATCH] Issue #2720439 by colan: Added site autocompletion & name to
 nid conversion.

---
 site/hosting_site.module | 66 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 66 insertions(+)

diff --git a/site/hosting_site.module b/site/hosting_site.module
index 3e137fe..b7cd061 100644
--- a/site/hosting_site.module
+++ b/site/hosting_site.module
@@ -69,6 +69,13 @@ function hosting_site_menu() {
     'access arguments' => array('access content'),
   );
 
+  // Provide autocomplete functionality.
+  $items['hosting/sites/autocomplete'] = array(
+    'title' => 'Autocomplete for sites',
+    'page callback' => 'hosting_site_autocomplete_sites',
+    'access arguments' => array('access content'),
+    'type' => MENU_CALLBACK,
+  );
 
   $items['node/%node/goto_site'] = array(
     'page callback' => 'hosting_site_goto',
@@ -115,6 +122,65 @@ function _hosting_site_form_check() {
 }
 
 /**
+ * Retrieve autocomplete suggestions for site names.
+ *
+ * @param $string
+ *   The typed string so far, as typed in by the user.
+ *
+ * @return
+ *   A list of matching sites in JSON format.
+ */
+function hosting_site_autocomplete_sites($string) {
+
+  // Fetch the list of matching sites from the node table.
+  $results = db_select('node', 'n')
+    ->fields('n', array('nid', 'title'))
+    ->condition('n.status', 1)
+    ->condition('n.type', 'site')
+    ->condition('title', '%' . db_like($string) . '%', 'LIKE')
+    ->execute();
+
+  // Save each result to the list.
+  $matches = array();
+  foreach ($results as $row) {
+    $matches[$row->title] = check_plain($row->title);
+  }
+
+  // Return the results as a JSON list.
+  drupal_json_output($matches);
+}
+
+/**
+ * Gets the node ID of a site from its name.
+ *
+ * @param $name
+ *   The title of the node named for the site.
+ * @return
+ *   The node ID of the site with the name, or FALSE if no matching site could
+ *   be found.
+ */
+function hosting_site_get_nid_from_name($name) {
+
+  // Get the list of node IDs whose title matches the name.
+  $query = new EntityFieldQuery();
+  $entities = $query->entityCondition('entity_type', 'node')
+    ->propertyCondition('type', 'site')
+    ->propertyCondition('title', $name)
+    ->range(0,1)
+    ->execute();
+
+  if (!empty($entities['node'])) {
+    // Fetch the node ID from the list and return it.
+    $nids = array_keys($entities['node']);
+    return array_shift($nids);
+  }
+  else {
+    // The list is empty so there's no such site.
+    return FALSE;
+  }
+}
+
+/**
  * Menu wildcard loader callback.
  *
  * Loads a hosting_site node.
-- 
2.5.0

