Skip to main content
Jan 21, 2017

We had a request from a client to integrate Google Custom Search with SilverStripe CMS. The idea was interesting and we decided to write tutorial about it.

There are three main steps to be done:

  • Create Google Custom Search Engine, if you haven't yet
  • Create new page type and template
  • Add search form to template

Custom Google search engine

1) Create custom search engine on Google site http://www.google.com/cse

(Creating custom search engine is out of the scope of this tutorial (I'm going to write it in a couple of days, don't worry), so we'll provide only steps related to the SilverStripe CMS itself.)

New page type

2) Create new page type for custom search in folder /mysite/code

<?php
class CustomSearchPage extends Page {
 
  public static $db = array(
  );
 
  public static $has_one = array(
  );
 
}
class CustomSearchPage_Controller extends Page_Controller {
   
}

New template file

3) Create new template file CustomSearchPage.ss in /themes/%your-theme%/templates

4) Insert code from custom search engine; it looks like this one:

<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript"> 
  google.load('search', '1', {language : 'en', style : google.loader.themes.V2_DEFAULT});
  google.setOnLoadCallback(function() {
    var customSearchOptions = {};  var customSearchControl = new google.search.CustomSearchControl(
      '%some-code%', customSearchOptions
    );
    customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
    var options = new google.search.DrawOptions();
    options.enableSearchResultsOnly(); 
    customSearchControl.draw('cse', options);
    function parseParamsFromUrl() {
      var params = {};
      var parts = window.location.search.substr(1).split('\x26');
      for (var i = 0; i < parts.length; i++) {
        var keyValuePair = parts[i].split('=');
        var key = decodeURIComponent(keyValuePair[0]);
        params[key] = keyValuePair[1] ? decodeURIComponent(keyValuePair[1].replace(/\+/g, ' ')) : keyValuePair[1];
      }
      return params;
    }
 
    var urlParams = parseParamsFromUrl();
    var queryParamName = "q";
    if (urlParams[queryParamName]) {
      customSearchControl.execute(urlParams[queryParamName]);
    }
  }, true);
</script>

Create new page

5) Go to the admin section and create new page with page type Custom Search

6) Give it a name, e.g. Search Results and save ti.

Note: Remember it's URL because you need to add it later to a search form (in our case the URL is "search-results")

Search form

7) Add code for new search form that will redirect search query to the new search page, e.g.:

<form action="search-results">
  <input name="q" type="text">
  <input type="submit" name="submit" value="Search">
</form>

Build and flush

8) You need to rebuild tables and flush template cache with the following URL in a browser's address bar:

%your-site%/dev/build?flush=all