Monday, February 15, 2016

Using SPServices to help populate fields in a SharePoint form

image

I know SPServices is old skool and so am I. We both go very well in hand with web services indeed, but we do enjoy the occasional re-write to new world of REST. Honestly!

I have a form where based on a lookup to another list I should populate, or copy values, over to some fields. Pretty simple task, which is not out of the box.

As I hate writing plumbing code I pinged Marc Anderson and found out that his SPServices library has a method named SPDisplayRelatedInfo. This method is meant to be attached to the drop-down tied to the look-up list, and will pull in related data and render it as an inline table.

(Image borrowed from https://spservices.codeplex.com)

In my case I wanted to populate the Site name, Department and Responsible person based on the item selected in the below drop-down.

image

The configuration for this can look like below, and pay attention to line 5.

$().SPServices.SPDisplayRelatedInfo({
  columnName: "Applicable finding",
  relatedList: "Findings",
  relatedColumns: ["PzlInspector", "PzlSiteName", "PzlDepartment"],
  displayFormat: "none",
  matchOnId: true,
  completefunc: function(data) {
      if( $('select[id^="PzlFindingLookup"]').val() != 0) {
        setFormValues(data);
      }
  }
});

displayformat = none is an extension I added myself, as I don’t want to render out related information, I only want the data so that I can populate forms (it’s added as an issue at https://github.com/sympmarc/SPServices/issues/28) .

In the completefunc callback I pick up the returned data and fill out the form fields. The start of my setFormValues function looks like this:

function setFormValues(data) {
    var siteName = data.attr("ows_WoWSiteName");
    var inspector = data.attr("ows_WoWInspector");    
    var departmentItemId = data.attr("ows_WoWDepartment").split(";")[0];

The real magic is of course the code which populates the people picker as well as the taxonomy field in the form. Ping me if you are interested and I’ll clue you in.

Time saved is time I can spend on blogging

All in all, I saved myself from writing the jQuery needed to attach to the drop-down, as well as the API call to pull in the related item. When saving time, I don’t care how old skool it as long as it works :-)