SharePoint 2013: Show and set Rating with JavaScript
Preconditions:
- Enable Rating with Stars in a List.
- Prepare some sort of HTML to show list item Information. Add a div which will act as the Container for the Rating Control.
Script:
In your script preload the needed dependencies:
SP.SOD.executeOrDelayUntilScriptLoaded(function() {
SP.SOD.executeOrDelayUntilScriptLoaded(function() {
SP.SOD.registerSod("sp.ui.reputation.js", SP.Utilities.Utility.getLayoutsPageUrl("sp.ui.reputation.js"));
SP.SOD.executeOrDelayUntilScriptLoaded(function() {
SP.SOD.executeFunc("sp.ui.reputation.js", "SP.UI.Reputation.AverageRatingFieldTemplate", contoso.collaboration.start);
},
"clienttemplates.js");
SP.SOD.executeFunc("clienttemplates.js", false, function() {});
},
"sp.js");
SP.SOD.executeFunc("sp.js", false, function() {});
},
"strings.js");
In your start function get a List-Item and call the function renderAverageControl.
contoso.collaboration.start = function()
{
var clientContext = SP.ClientContext.get_current();
if (clientContext) {
var oList = clientContext.get_web().get_lists().getByTitle('<a list title>');
var item = oList.getItemById(<a listem item id>);
clientContext.load(item);
clientContext.executeQueryAsync(
function () {
if (item) {
var id = item.get_id();
var averageRating = item.get_item('AverageRating');
var ratingCount = item.get_item('RatingCount');
var _RatedBy = item.get_item("RatedBy");
contoso.collaboration.renderAverageControl(_RatedBy, "averageRatingDiv", averageRating, ratingCount, id);
}
},
function (sender, args) {
if(args)
{
console.log("Request to get ... failed. " + '\n' + args.get_message() + '\n' + args.get_stackTrace());
}
alert("Sorry something went wrong!");
});
}
}
The function renderAverageControl:
contoso.collaboration.renderAverageControl = function(_RatedBy, containerId, averageRating, ratingCount, itemId)
{
var average = { container: undefined};
average.container = document.getElementById(containerId);
var ratedByLookupItems = _RatedBy;
var ratedBy = [];
if (ratedByLookupItems != null) {
for (var i = 0; i < ratedByLookupItems.length; i++) {
var ratedByItem = ratedByLookupItems[i];
ratedBy[ratedBy.length] = {
id: String(ratedByItem.get_lookupId())
, value: ratedByItem.get_lookupValue()
, title: ratedByItem.get_lookupValue()
};
}
}
var displayContext = new Context();
displayContext.CurrentItem = [];
displayContext.CurrentItem.ID = itemId;
displayContext.CurrentItem.AverageRating = averageRating === null?"0":averageRating.toString();
displayContext.CurrentItem.Ratings = ratingCount === null?"0":ratingCount.toString().replace(".",",");
displayContext.CurrentItem.RatedBy = ratedBy;
displayContext.listName = "{EE87F0D6-832A-4E45-9A80-A3EA3990A3D3}";
displayContext.listTemplate = g_wsaListTemplateId;
displayContext.CurrentItem.ContentTypeId = "0x0100CBDF088C26134A2D9AB8508476DB1B12";
displayContext.CurrentItem.FSObjType = "0";
displayContext.HttpRoot = _spPageContextInfo.siteAbsoluteUrl;
displayContext.ListSchema = {
Userid: _spPageContextInfo.userId,
Direction: "LTR"
};
displayContext.CurrentFieldSchema = {
AllowGridEditing: "FALSE",
GridActiveAndReadOnly: "TRUE",
fieldRenderer: SP.UI.Reputation.AverageRatingFieldTemplate.renderAverageRatingField
};
average.container.innerHTML = SP.UI.Reputation.AverageRatingFieldTemplate.renderAverageRatingField(displayContext);
SP.UI.Reputation.AverageRatingFieldTemplate.onPostRender();
}
Important note
- displayContext.listName must be the GUID of the list. If you use the list Name you will get an error when you rate an item.
- displayContext.CurrentItem.ContentTypeId should be the ContentTypeId of the list. It does not matter if you use list Content type or its parent.
- displayContext.CurrentItem.AverageRating: You have to avoid null. Value has to be a string otherwise, you will get an error because a trim() of the value will fail in a SharePoint JavaScript file.
- displayContext.CurrentItem.Ratings: same as to AverageRating.
- onPostRender will add the Event handler so that a user can rate by click from the start.
This snippet has been used based on a custom list and custom Content type.