Use custom initialization scripts

Warning
Legacy feature

This article pertains to the Coveo Hive framework which is now in maintenance mode.

Choose one of Coveo’s more modern, lightweight, and responsive libraries for any future search interface development. See the search interface Implementation guide for more details.

Coveo Hive components are initialized, based on the related data source options you specify, once the search page has been completely loaded. The Coveo Search Interface component launches the initialization of the interface and its embedded components.

Search interface initialization script

In the past, the search interface initialization script was hard-coded in the Coveo Search Interface.cshtml view file. So, to alter the initialization of a particular search page or to leverage Coveo JavaScript Search Framework options not fronted in the Coveo Search Interface data source, while not impacting other search pages, you had to duplicate the Coveo Search Interface rendering item and view file, and make the new rendering available in the Coveo UI placeholder.

The February 2019 version of Coveo for Sitecore 5 greatly simplifies the customization of the Coveo Search Interface initialization script and, consequently, the use of additional Coveo JavaScript Search Framework options and methods (see Coveo JavaScript Search Framework - Reference Documentation).

Coveo for Sitecore packages contain the following changes:

  • A new Initialization File Name field, whose default value is init, has been added in the Coveo Search Interface data source template item.

  • The initialization script has been removed from the Coveo Search Interface.cshtml view file and replaced with a @Html.Partial line which references the InitializationFileName model property.

  • A new init.cshtml file, which contains the default search interface initialization script, has been added in the <SITECORE_INSTANCE_ROOT>\Website\Coveo\Hive\init folder.

Hence, to customize your search interface initialization, you now only need to create an initialization .cshtml view file and reference it in the Coveo Search Interface rendering data source.

Example 1: Collapse a facet on page load

You have a search page which contains a few facets. You would like to have the first facet collapsed at page load using the facet collapse method (see Coveo Facet Component - Collapse).

To collapse the first facet in your search interface

  1. In your file explorer, open the <SITECORE_INSTANCE_ROOT>\Coveo\Hive\init folder.

  2. Create a copy of the init.cshtml file in the same folder. Name the new file collapseFirstFacet.cshtml.

  3. Open collapseFirstFacet.cshtml in a text editor.

  4. Add the following code inside the setTimeout (function() curly braces:

    searchInterface.addEventListener(Coveo.InitializationEvents.afterComponentsInitialization, function() {
       var myFacetElement = Coveo.get(document.getElementsByClassName("CoveoFacet")[0]);
       myFacetElement.collapse();
    });

    Your collapseFirstFacet.cshtml code should now read as follows:

    @using Sitecore.Mvc
    @using Coveo.UI.Components
    @using Coveo.UI.Components.Extensions
    @using Coveo.UI.Core.ErrorReports
    @model Coveo.UI.Components.Models.SearchInterfaces.ISearchInterfaceModel
    <script type="text/javascript">
       /*The event below was originally "DOMContentLoaded". It was replaced with the
       "CoveoSearchEndpointInitialized" event in the October 30, 2020 release of Coveo for Sitecore.*/
       document.addEventListener("CoveoSearchEndpointInitialized", function() {
          @*
             setTimeout(function() { }, 0) defers the initialization just enough to execute other CoveoSearchEndpointInitialized events in the page.
             This is required by some components to allow them to register before initialization.
          *@
          setTimeout(function() {
             var searchInterface = document.getElementById("@Model.Id");
             @if (Html.Coveo().IsEditingInPageEditor()) {
                @: if (typeof(CoveoForSitecore) !== "undefined" && typeof(Sitecore) !== "undefined") {
                   @: CoveoForSitecore.initializeSearchInterfaceForExperienceEditor(searchInterface);
                @: }
             } else {
                @: if (typeof(CoveoForSitecore) !== "undefined") {
                   @: CoveoForSitecore.initSearchInterface(searchInterface);
                @: }
             }
             searchInterface.addEventListener(Coveo.InitializationEvents.afterComponentsInitialization, function() {
                var myFacetElement = Coveo.get(document.getElementsByClassName("CoveoFacet")[0]);
                myFacetElement.collapse();
             });
          }, 0);
        });
    </script>
  5. Save your changes.

  6. In the Sitecore Experience Editor, select the Coveo Search Interface component.

  7. In the floating toolbar, select Edit the rendering’s data source. It should be the leftmost option in the toolbar.

  8. In the Initialization section, set the Initialization File Name value to the base name part of your .cshtml filename.

    CoveoSearchInterfaceInitialization
  9. Click OK.

Example 2: Display a facet only when a specific value is selected in its parent

You have multiple templates which contain a style field. However, in your search interface, you only want to show the Style dynamic facet when the user selects the House value in the Template dynamic facet. To do this, you need to:

  1. Specify that the Style facet depends on the Template facet.

  2. Create a custom initialization script to define the dependsOnCondition of the Style facet.

To specify that the Style facet depends on the Template facet

Configure your Style facet as follows:

First part of data source configuration | Coveo for Sitecore 5 Second part of data source configuration | Coveo for Sitecore 5

Where the Depends On value must match the value you entered as the Facet ID in the Template facet data source.

The DOM Unique Id is automatically generated. You use this DOM Unique Id in the custom initialization script to select your Style facet.

To display the Style facet only when the user selects House in the Template facet

  1. In your file explorer, open the <SITECORE_INSTANCE_ROOT>\Coveo\Hive\init folder.

  2. Create a copy of the init.cshtml file in the same folder. Name the new file dependsOnHouse.cshtml.

  3. Open dependsOnHouse.cshtml in a text editor.

  4. Add the following code inside the setTimeout (function() curly braces:

    Coveo.options(searchInterface, {
       coveodb691f100: {
         dependsOnCondition: (parentFacet) => {
           const id = parentFacet.options.id;
           const value = "House";
           const selected = parentFacet.queryStateModel.get(`f:${id}`)
           return selected.includes(value);
         }
       }
    });

    Your dependsOnHouse.cshtml code should now read as follows:

    @using Sitecore.Mvc
    @using Coveo.UI.Components
    @using Coveo.UI.Components.Extensions
    @using Coveo.UI.Core.ErrorReports
    @model Coveo.UI.Components.Models.SearchInterfaces.ISearchInterfaceModel
    <script type="text/javascript">
       document.addEventListener("CoveoSearchEndpointInitialized", function() {
          @*
             setTimeout(function() { }, 0) defers the initialization just enough to execute other DOMContentLoaded or CoveoSearchEndpointInitialized events in the page.
             This is required by some components to allow them to register before initialization.
          *@
          setTimeout(function() {
             var searchInterface = document.getElementById("@Model.Id");
             Coveo.options(searchInterface, {
                coveodb691f100: {
                   dependsOnCondition: (parentFacet) => {
                      const id = parentFacet.options.id;
                      const value = "House";
                      const selected = parentFacet.queryStateModel.get(`f:${id}`)
                      return selected.includes(value);
                   }
                }
             });
             @if (Html.Coveo().IsEditingInPageEditor()) {
                @: if (typeof(CoveoForSitecore) !== "undefined" && typeof(Sitecore) !== "undefined") {
                   @: CoveoForSitecore.initializeSearchInterfaceForExperienceEditor(searchInterface);
                @: }
             } else {
                @: if (typeof(CoveoForSitecore) !== "undefined") {
                   @: CoveoForSitecore.initSearchInterface(searchInterface);
                @: }
             }
          }, 0);
       });
    </script>
  5. Save your changes.

  6. In the Sitecore Experience Editor, select the Coveo Search Interface component.

  7. In the floating toolbar, select Edit the rendering’s data source. It should be the leftmost option in the toolbar.

  8. In the Initialization section, set the Initialization File Name value to the base name part of your .cshtml filename.

    Setting Initialization File Name in Search Interface Data Source | Coveo for Sitecore 5
  9. Click OK.

See the Coveo JavaScript Search Framework Define dependent facets article and Passing component options before the init call example for more details.

Example 3: Change the Coveo Did You Mean query correction message

You’re using the Coveo Did You Mean rendering in a search interface and would like to change the default English query correction message (below left) to the one you see below right.

Coveo Did You Mean query correction message| Coveo for Sitecore
  1. In your file explorer, open the <SITECORE_INSTANCE_ROOT>\Coveo\Hive\init folder.

  2. Create a copy of the init.cshtml file in the same folder. Name the new file queryCorrectionMessage.cshtml.

  3. Open queryCorrectionMessage.cshtml in a text editor.

  4. Replace the code of the file with the following:

    @using Sitecore.Mvc
    @using Coveo.UI.Components
    @using Coveo.UI.Components.Extensions
    @using Coveo.UI.Core.ErrorReports
    @model Coveo.UI.Components.Models.SearchInterfaces.ISearchInterfaceModel
    <script type="text/javascript">
        document.addEventListener("CoveoSearchEndpointInitialized", function() {
            @*
                setTimeout(function() { }, 0) defers the initialization just enough to execute other DOMContentLoaded or CoveoSearchEndpointInitialized events in the page.
                This is required by some components to allow them to register before initialization.
            *@
            setTimeout(function() {
    		    var searchInterface = document.getElementById("@Model.Id");
    			String.toLocaleString({
    				"en": {
    				"autoCorrectedQueryTo": "Searching for {0} instead.", // Overrides the default message.
                                                                      // You could also override the noResultFor param
                                                                      // to change the first sentence.
    				}
    			});
    
                @if (Html.Coveo().IsEditingInPageEditor()) {
                    @: if (typeof(CoveoForSitecore) !== "undefined" && typeof(Sitecore) !== "undefined") {
                        @: CoveoForSitecore.initializeSearchInterfaceForExperienceEditor(searchInterface);
                    @: }
                } else {
                    @: if (typeof(CoveoForSitecore) !== "undefined") {
                        @: CoveoForSitecore.initSearchInterface(searchInterface);
                    @: }
                }
            }, 0);
        });
    </script>
  5. Save your changes.

  6. In the Sitecore Experience Editor, select the Coveo Search Interface component.

  7. In the floating toolbar, select Edit the rendering’s data source. It should be the leftmost option in the toolbar.

  8. In the Initialization section, set the Initialization File Name value to the base name part of your .cshtml file name (that is, queryCorrectionMessage).

    Setting Initialization File Name in Search Interface Data Source | Coveo for Sitecore 5
  9. Click OK.

Searchbox initialization script

In the March 2019 release of Coveo for Sitecore 5, an Initialization File Name field was added to the Coveo Searchbox and Coveo Global Searchbox components data sources. Hence, you can now create a custom searchbox initialization .cshtml view file and reference that file in a searchbox component data source, very much the same way you can reference an initialization script file in a Coveo Search Interface component data source (see Search interface initialization script).

Using a custom searchbox initialization script is ideal if, for example, you need to link a Coveo Global Searchbox to a given search interface programmatically at runtime.

To associate a custom initialization script to a searchbox component

  1. In your file explorer, open the <SITECORE_INSTANCE_ROOT>\Coveo\Hive\search box init folder.

  2. Create a copy of the init.cshtml file in the same folder. Name the new file customInit.cshtml.

  3. Open customInit.cshtml in a text editor.

  4. Edit the code.

  5. Save your changes.

  6. In the Sitecore Experience Editor, select your searchbox component.

  7. In the floating toolbar, select the Edit the rendering’s data source option. It should be the leftmost option in the toolbar.

  8. In the Initialization section, set the Initialization File Name value to customInit.

  9. Click OK.

Note

The searchbox initialization Initialize Searchbox.cshtml file has been renamed init.cshtml and moved to the new \Coveo\Hive\search box init folder.