Classic SharePoint Add-ins with Office UI Fabric

Office UI Fabric is the new dress for Office add-ins, that perfectly marries with modern SharePoint pages using the SharePoint Framework. Besides providing a set of UI guidelines, font styles, grid layouts and icons, Office UI Fabric adds a rich collection of HTML components ready to use in your Office add-ins & SharePoint pages.

Office UI Fabric for Modern SharePoint

In Modern SharePoint, Office UI Fabric site is your definitive framework for styles and components, with components available for both React and Angular. When creating a web part with SharePoint Framework (SPFx), all you have to do is choose, say, React as a JavaScript framework, and let Yeoman do all the necessary scaffolding for preparing your SPFx web part project. The article “Use Office UI Fabric React components in your SharePoint client-side web part” describes how to build a simple web part that uses a React component of Office UI Fabric.

Office UI Fabric for Classic SharePoint

Completely different is the story if you were to develop a SharePoint add-in for a Classic site. In that case, React or Angular wouldn’t be your preferred choice, which would bar you from using the Office UI Fabric components. Good news is, though, that a lean JavaScript collection of components, aptly named Office UI Fabric JS, exists and it’s ready to use in your classic SharePoint add-in solution.

The Office UI Fabric JS component collection includes many components, such as breadcrumb, button, contextual menu, date picker, panel, people picker, progress indicators and many more. Adding a component to a page is a matter of adding the necessary HTML code, which references CSS classes for the Office UI Fabric style, and JavaScript code that enables behaviors.

To use these components in a SharePoint add-in page, all you have to do is add the following references to the relevant CSS stylesheet and JavaScript files:

For Office UI Fabric (theme colors, fonts, icons):

HTML

<link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-core/9.6.0/css/fabric.min.css" />

For Office UI Fabric JS (components):

HTML

<link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.2.0/css/fabric.min.css" /> 
 
<link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.2.0/css/fabric.components.min.css" /> 
 
<script type="text/javascript" src="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.2.0/js/fabric.min.js"></script>

Then, for each component, the component reference guide on the Office UI Fabric JS web site indicates the HTML and JavaScript code to use. For example, for a button component, the HTML code looks like this one:

HTML

<button class="ms-Button"   <span class="ms-Button-label">Button Text</span> 
</button>

And the JavaScript code would be:

JavaScript

var buttonElements = document.querySelectorAll(".ms-Button"); 
for (var i = 0; i < buttonElements.length; i++) { 
    new fabric['Button'](buttonElements[i], function () { 
        // Insert event here 
    }); 
}

Weather Add-In

Let’s build a web part that displays the current weather conditions for a selected city. Weather data is provided by OpenWeatherMap, an online service that exposes an API for retrieving weather conditions and forecast around the world.

The SharePoint add-in looks like this:

  • Shows a list of cities from a SharePoint list; each city is identified by a name and an internal ID used by the OpenWeatherMap API.
  • On select of a city, it shows the current weather condition returned by the API.

 

Weather Add-in

Weather Add-in

 

There are a few elements decorated with Office UI Fabric in this page:

  1. The dropdown list with the city names.
  2. The “Weather today in” label.
  3. The icons next to the weather elements.

Adding a dropdown component consists in an HTML code snippet that defines the component’s label and options. We keep the option list empty as we want to populate it dynamically from a SharePoint list. Note the CSS class “ms-Dropdown” assigned to the external <div> element; this class will be used in JavaScript to select the dropdown component and “dress it” with the Office UI fabric style.

HTML

<div class="ms-Dropdown"    <label class="ms-Label">Select a city:</label> 
    <i class="ms-Dropdown-caretDown ms-Icon ms-Icon--ChevronDown"></i> 
    <select class="ms-Dropdown-select" id="selectCity"        <option></option> 
    </select> 
</div>

Labels and icons benefits of a set of predefined CSS classes for font styles and icons, which help give consistency of design to the different elements of a SharePoint add-in.

HTML

<div class="ms-font-su ms-fontColor-themePrimary">Weather today in <span id="cityName"></span></div> 
<i class="ms-Icon ms-Icon--CloudWeather ms-font-xl" aria-hidden="true"></i> 
<span class="ms-font-l ms-fontWeight-semibold">Conditions:</span>

Data Loading

Let’s have a look at the JavaScript code that defines a few important aspects of this add-in:

  1. Load the cities to displayed in the dropdown from a SharePoint list.
  2. Initialize the Office UI Fabric JS components.
  3. Setup the event handler for the dropdown list that invokes the weather API on selection of a city.

 

The add-in relies on JSOM – the JavaScript client-side Object Model – for communication to the SharePoint backend. Communication is obtained via a client context and an app context where the add-in runs. This code runs when the page’s DOM is ready and creates a context object which is needed to use the SharePoint object model.

JavaScript

var context = SP.ClientContext.get_current(); 
 
var appContext = new SP.AppContextSite(context, hostUrl);
 The add-in benefits also of jQuery, which can provide an easy access to the DOM and its element and events. On document ready, we can run the three actions necessary for:
  1. Loading data.
  2. Initializing Office UI Fabric JS.
  3. Initializing the event handlers.

 

Please note that it is important to execute these three actions in sequence. As the data load is asynchronous, as we’ll see in a moment, we have to wait for all the cities to be loaded and the dropdown list populated before initializing the Office UI Fabric JS component.

JavaScript

$(document).ready(function () { 
    $.when(loadData()) 
        .then(initFabricUI()) 
        .then(initEventHandlers()); 
});
 City names and IDs are retrieved from a SharePoint list called “Cities”
Cities

Cities

 

As mentioned, the JSOM SharePoint client object model is used to retrieve a list of cities from a SharePoint list. A complete description of the available operations using JavaScript library code in SharePoint is available here:

https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-javascript-library-code-in-sharepoint

 

The city list is retrieved by looking for the “Cities” SharePoint list in the add-in context, and then querying for its list items using a CAML query. We are after the Title and CityID fields only, which are specified in the Include condition when loading data.

JavaScript

function loadData() { 
    var cityList = appContext.get_web().get_lists().getByTitle("Cities"); 
 
    var camlQuery = new SP.CamlQuery(); 
    camlQuery.set_viewXml("<View><RowLimit>100</RowLimit></View>"); 
 
    cityListItems = cityList.getItems(camlQuery); 
    context.load(cityListItems, "Include(Title, CityID)"); 
 
    context.executeQueryAsync(onQuerySucceeded, onQueryFailed); 
}

The query executes asynchronously. On successful execution, the onQuerySucceeded function is called, which iterates through the list items and generates an <option> HTML tag that is added to the city dropdown list.

JavaScript

function onQuerySucceeded(sender, args) { 
    var listItemEnumerator = cityListItems.getEnumerator(); 
 
    while (listItemEnumerator.moveNext()) { 
        var listItem = listItemEnumerator.get_current(); 
        $("#selectCity").append($("<option>"{ 
            value: listItem.get_item("CityID"), 
            text: listItem.get_item("Title") 
        })); 
    } 
}

For this code to execute successfully, it is important not to forget to set the necessary permissions in the app manifest, specifically the Read permission on the List scope.

App Manifest

App Manifest

 

Initialize Office Fabric UI

Once data is loaded and the dropdown component is populated with the necessary options, we can initialize it with the Office Fabric UI JS styles and behaviors. This is done by selecting the HTML tag with the “ms-Dropdown” CSS class and instantiating a new fabric object of type “Dropdown”.

JavaScript

function initFabricUI() { 
    var dropdownHTMLElements = document.querySelectorAll('.ms-Dropdown'); 
    for (var i = 0; i < dropdownHTMLElements.length; ++i) { 
        new fabric['Dropdown'](dropdownHTMLElements[i]); 
    } 
}

For registering an event handler on change of the selection, I’ll stick to the usual jQuery “on” method. When a city is selected in the list, we want to read its current weather conditions and display on screen.

 

JavaScript

function initEventHandlers() { 
    $("#selectCity").on("change"function () { 
        getWeather(this.value); 
    }); 
}

The getWeather function constructs the URI of the API endpoint, which includes the city ID, the API key (you have to register your own account to obtain an API key), and the type of units to use for the temperature. I choose to go for metric type, which returns temperature in Celsius degrees.

Then, invoke the API at the defined endpoint and obtain a JSON object that contains the information that we are looking for. The returned weather object contains many more fields, as documented on the Open Weather Map web site.

JavaScript

function getWeather(cityId) { 
    var apiUri = weatherApiUri(cityId); 
 
    $.getJSON(apiUri, function (data) { 
        $("#cityName").text(data.name); 
        $("#weatherConditions").text(data.weather[0].main); 
        $("#weatherTemperature").text(Math.round(data.main.temp)); 
        $("#weatherHumidity").text(data.main.humidity); 
    }); 
} 
 
function weatherApiUri(cityId) { 
    return "https://api.openweathermap.org/data/2.5/weather?id=" + cityId + "&appid=" + weatherApiAppId + "&units=metric"}
 The entire source code of this solution is available on my GitHub repository:

https://github.com/stefanotempesta/SharePoint/tree/master/SharePointAddins 

 

Reference: Tempesta, S. (2018). Classic SharePoint Add-ins with Office UI Fabric. Available at: https://code.msdn.microsoft.com/Classic-SharePoint-Add-ins-8b34e2f5 [Accessed 19 April 2018].

Share this on...

Rate this Post:

Share: