Sitecore API and JavaScript
Sitecore API and JavaScript
One thing that I like to do with forms is make them interactive. Making use of AJAX calls to call API endpoints that interact with Sitecore. One of the more common asks I get is to use a list of children items as a source for a dropdown. So let's take an example of a form that has a State dropdown. We want this dropdown to be editable in Sitecore as a list of children items.
First we will set up a View Rendering to give us a model based dropdown.
@Html.DropDownListFor(x => x.FormModel.States, Model.States, new {id = "state-select" })
Next, we will call an API endpoint to give us a JSON object of states.
{"states":[{"id":"stateguid","displayName":"state"},{"id":"stateguid","displayName":"state"}]}
To help translate this JSON, we will use json2csharp.com to auto create a model class.
public class State
{
public string id { get; set; }
public string displayName { get; set; }
}
public class RootObject
{
public List<State> states { get; set; }
}
We will then write a controller with a method that will get all states and serialize the return.
public class StateController : SitecoreController
{
public ActionResult GetAllStates()
{
// get states from Sitecore
// ...
return Content(JsonConvert.SerializeObject(rootObject));
}
}
Finally we will write some JavaScript using jQuery to populate the dropdown on page load.
$(document).ready(function () {
$.getJSON("/api/Sitecore/State/GetAllStates", function (data) {
appendInputs(data, $('#state-select'));
});
});
function appendInputs(data, element) {
var items = data.states;
for (var i = 0; i < items.length; i++) {
element.append($('<option>', {
value: items[i].id,
text: items[i].displayName
}));
}
}
This is a simple example but it should give you a good starting point for integrating Sitecore data with your JavaScript forms.