sn-record-picker Helper, Part II

“If I had eight hours to chop down a tree, I’d spend six hours sharpening my ax.”
Abraham Lincoln

Now that we have all of the form fields and controls laid out on the page, the next order of business is to build the function that will use the form input to create the desired sn-record-picker. We have already specified an ng-submit function on the form, so all we have to do at this point is to actually create that function in the client-side script. This function is actually pretty vanilla stuff, and just takes the data entered on the screen and stitches it all together to form the resulting sn-record-picker tag.

$scope.createPicker = function() {
	var picker = '<sn-record-picker\n    table="' + "'";
	picker += c.data.table.value + "'";
	picker += '"\n    field="';
	picker += c.data.field;
	if (c.data.filter) {
		picker += '"\n    default-query="' + "'";
		picker += c.data.filter + "'";
	}
	picker += '"\n    display-field="' + "'";
	picker += c.data.displayField.value + "'";
	if (c.data.displayFields.value) {
		picker += '"\n    display-fields="' + "'";
		picker += c.data.displayFields.value + "'";
	}
	if (c.data.searchFields.value) {
		picker += '"\n    search-fields="' + "'";
		picker += c.data.searchFields.value + "'";
	}
	if (c.data.valueField.value) {
		picker += '"\n    value-field="' + "'";
		picker += c.data.valueField.value + "'";
	}
	if (c.data.multiple) {
		picker += '"\n    multiple="true"';
	}
	if (c.data.placeholder) {
		picker += '"\n    page-size="';
		picker += c.data.pageSize;
	}
	if (c.data.pageSize) {
		picker += '"\n    placeholder="';
		picker += c.data.placeholder;
	}
	c.data.generated = picker + '">\n</sn-record-picker>';
	c.data.ready = true;
	return false;
};

One of the last few things that happens in that script is to set c.data.ready to true. I set that variable up to control whether or not the rendered tag should appear on the screen. Altering any of the fields on the screen sets it to false, which hides the text box containing the generated code until you click on the button again. To make that work, I just added an ng-show to the enclosing DIV:

<div class="col-sm-12" ng-show="c.data.ready">
  <snh-form-field
    snh-model="c.data.generated"
    snh-name="generated"
    snh-label="Your sn-record-picker:"
    snh-type="textarea">
  </snh-form-field>
  <p><a href="javascript:void(0);" onclick="copyToClipboard();">Copy to clipboard</a></p>
</div>

The other thing that you will notice inside of that DIV is the Copy to clipboard link. That one uses a standard onclick rather than an ng-click, because that’s a DOM operation, which is outside the scope of the AngularJS controller. The referenced script, along with another DOM script that I use to set the height of that textarea, are placed in a script tag with the HTML.

<script>
function fixTextareaHeight() {
	var elem = document.getElementById('generated');
    elem.style.height = (elem.scrollHeight + 10)  + 'px';
}
function copyToClipboard() {
	var elem = document.getElementById('generated');
	elem.select();
	elem.setSelectionRange(0, 99999)
	document.execCommand('copy');
	alert("The following code was copied to the clipboard:\n\n" + elem.value);
}
</script>

Clicking on that Copy to clipboard link copies the code to the clipboard and also throws up an alert message to let you know what was copied.

Alert message after copying the code to the clipboard

The next thing on my list was to actually place the code on the page so that you could see it working. I tried a number of things to get that to work, including ng-bind, ng-bind-html, ng-bind-html-compile, and sc-bind-html-compile, but I could never get any of that to work, so I ultimately gave up on trying to use the actual generated code, and did the next best thing, which was to just set up a picker of my own using the selected options.

        <div class="col-sm-12" ng-show="c.data.ready">
          <snh-form-field
            snh-model="c.data.liveExample"
            snh-name="liveExample"
            snh-label="Live Example"
            snh-type="reference"
            snh-change="optionSelected()"
            placeholder="{{c.data.placeholder}}"
            table="c.data.table.value"
            display-field="c.data.displayField.value"
            display-fields="c.data.displayFields.value"
            value-field="c.data.valueField.value"
            search-fields="c.data.searchFields.value"
            default-query="c.data.filter">
          </snh-form-field>
        </div>

This approach allowed me to add a modal pop-up that showed the value of the item selected.

Modal pop-up indicating option selected

The code to make that happen is in the client-side controller:

$scope.optionSelected = function() {
	spModal.open({
		title: 'Selected Option',
		message: '<p>You selected  "<b>' + c.data.liveExample.value + '</b>"</p>',
		buttons: [
			{label: 'Close', primary: true}
		],
		size: 'sm'
	});
};

One other thing that I should mention is that the snh-form-field directive that I used in this example is not same as the last version that I had published. To support the multiple=true/false option, I needed a checkbox, and for some reason, I never included that in the list of many, many field types that included in that directive. I also had to tweak a few other things here and there, so it’s no longer the same. I should really release that separately in a future installment, but for now, I will just bundle it with everything else so that this will all work as intended.

I wrapped the whole thing in an snh-panel, just to provide the means to add some documentation on the sn-record-picker tag. I had visions of gathering up all of the documentation that I could find and assembling it all into a comprehensive help screen document, but that never happened. Still, the possibility is there with the integrated help infrastructure.

Pop-up widget help screen

I also added a sidebar menu item so that I could easily get to it within the main UI. It may be a Service Portal Widget under the hood, but it doesn’t really belong on the Service Portal. It’s a development tool, so I added the menu item so that it could live with all of the other development tools in the primary UI. If you want to take it for a spin yourself, here is an Update Set.

Update: There is a better (corrected) version here.

sn-record-picker Helper

“You are never too old to set another goal or to dream a new dream.”
Les Brown

One of the cool little doodads packaged with ServiceNow is the sn-record-picker. On the Service Portal side of the house, the sn-record-picker gives you a type-ahead search of any ServiceNow table with a considerable number of flexible features. I use it quite a lot, but not often enough to intuitively recall every configuration option available. Although this is a widely used facet of the Service Portal platform, the documentation for this component is relatively sparse, which is uncharacteristic for ServiceNow. A number of individuals have attempted to provide their own version of the needed documentation, and I have even considered doing that myself, but that only solves half of my problem. The other thing that I can never remember is the names of tables and fields, which you need to know whenever you set up an sn-record-picker. What I would really like is some kind of on-line wizard that stepped me through all of the necessary parts and pieces needed to build the sn-record-picker that I need at the time, and it would be even better if had the ability to go ahead and build it so that I could see it live once I completed all of the steps needed to construct it. I looked around for such a tool and couldn’t find one, so I decided to build it myself.

Here’s the idea: create a Service Portal widget that has input fields for all of the configuration options along with some kind of Build It button that would both create the sn-record-picker code based on the user input, and put the code live on the page so that you could see it in action. It seemed like it would be quite useful when it was finished, and fairly simple to put together. After all, how hard could it be?

The first thing that you need for an sn-record-picker is a Table. Since we are building a widget, the easiest way to select a Table from a list would be to use an sn-record-picker. So, it would seem appropriate that the first field on our new sn-record-picker tool would, in fact, be an sn-record-picker. Technically, I will be using an snh-form-field in practice, but under the hood, there is still an sn-record-picker doing all of the heavy lifting.

<snh-panel title="'${sn-record-picker Tool}'" class="panel-primary">
  <form id="form1" name="form1" ng-submit="createPicker();" novalidate>
    <div class="row">
       <div class="col-sm-12">
        <snh-form-field
          snh-model="c.data.table"
          snh-name="table"
          snh-type="reference"
          snh-help="Select the ServiceNow database table that will contain the options from which the user will select their choice or choices."
          snh-change="buildFieldFilter();"
          snh-required="true"
          placeholder="Choose a Table"
          table="'sys_db_object'"
          display-field="'label'"
          display-fields="'name'"
          value-field="'name'"
          search-fields="'name,label'">
        </snh-form-field>
      </div>
    </div>
  </form>
</snh-panel>

I had to look up the name of the ServiceNow table of tables, because I couldn’t remember what it was (sys_db_object), but that may just be because I never knew what it was in the first place. I also had to look up the column names for all of the fields that I needed. I should be able to avoid all of that effort once all of this comes together and I can use my new tool, which of course, is whole point of this exercise. Configuring the table selector is enough to get things started, though, and I don’t like to do too much without giving things a whirl, so let’s throw this widget onto a portal page and hit the Try It! button.

sn-record-picker tool with table selector

Once you have the table selected, you can start selecting from the fields defined for that table. Once again, this is an excellent use for an sn-record-picker, but for the table fields we will need to filter the choices based on the table selected. To do that, we need to build an encoded query for a filter. On the client-side script, we can create a function to do just that:

$scope.buildFieldFilter = function() {
	c.data.fieldFilter = 'elementISNOTEMPTY^name=' + c.data.table.value;
};

Now that we have our filter defined, we can reference it in the next picker that we will need, the Primary Display field:

<snh-form-field
  snh-model="c.data.displayField"
  snh-name="displayField"
  snh-label="Primary Display Field"
  snh-type="reference"
  snh-help="Select the primary display field."
  snh-required="true"
  snh-change="c.data.ready=false"
  placeholder="Choose a Field"
  table="'sys_dictionary'"
  display-field="'column_label'"
  display-fields="'element'"
  value-field="'element'"
  search-fields="'column_label,element'"
  default-query="c.data.fieldFilter">
</snh-form-field>

The default-query attribute of the Display Field sn-record-picker is set to c.data.fieldFilter, which is the variable that contains the value that is recalculated every time a new selection is made on the Table sn-record-picker. Whenever you select a different table, the filter is updated and then the list of available options for the Display Field selector changes to just those fields found on the selected table. This technique will be utilized for the Primary Display Field, the Additional Display Fields, the Search Field, and the Value Field.

In addition to the basic table and field attributes, there are also a number of other attributes that need to be included in the tool as well. I’m not even sure that I know all of the possible attributes that might be available, but my thought is that I will add all of the ones that I know about and then toss the others in when I learn about them. It turns out that there a quite a few, though, and after putting them all in with their associated help information, it made my page long and narrow, and put the button and results way, way down at the bottom of the page. I didn’t really like that, so I decided to split the page into two columns, and to hide any optional parameters unless needed. That format turned out to be much better that what I had originally; I like it much better.

Picker tool split into two columns

To temporarily hide the optional fields, I added an anchor tag with an ng-click above the form field, and gave both the anchor tag and the form field ng-show attributes based on the same boolean variable so that either one or the other would appear on the page.

<div class="col-sm-12" ng-show="c.data.table.value > ''">
  <p><a href="javascript:void(0)" ng-click="c.data.showFilter = true;" ng-show="!c.data.showFilter">Add an optional query filter</a></p>
  <snh-form-field
    ng-show="c.data.showFilter"
    snh-model="c.data.filter"
    snh-name="filter"
    snh-help="To limit the records retrieved from the table, enter an optional Encoded Query"
    placeholder="Enter a valid Encoded Query"
    snh-change="c.data.ready=false">
  </snh-form-field>
</div>

Now that I have configured all of the form fields for all of the attributes, the next thing to do will be to build the code that turns the user’s input into an actual sn-record-picker, and then makes it available for copy/paste operations, and hopefully, to try out right there on the wizard form. That’s actually quite a bit, so I think I will save all of that for a future installment.

More Service Portal Form Fields

“Code reuse is the Holy Grail of Software Engineering.”
Douglas Crockford

One of the thing that I like about making parts is that, even after you’ve “completed” your work and put a part on the shelf, you can always go back at some point later on and make it even better. When I first set out to create my form field tag, my primary goal was to save myself some work and to set things up so that things would always come out consistently. Consistency is a nice by-product of reusing the same component over and over again. People like it when things are consistent. So when I came across a need for a field type that I had not built into the current version of my form field tag, my first impulse was to pull it off the shelf, dust it off, and give it a bit of an upgrade.

What I needed was a feedback field, which is really a combination to two separate fields, a rating widget and a comments box. There are all kinds of rating widgets out there where you can configure stars or happy faces or some other graphic to indicate some level of satisfaction, but none of the existing field types in my current form field implementation supported that feature, and none of them included a single label for two input elements. What I wanted to do was to support something like this:

Example feedback entry

For the rating, I peeked under the hood of the Knowledge Article widget, and found the uib-rating tag, which looks like it comes from here. That looked like just the thing that I needed, so I all that was left for me to do was to wrap my labels and decorations around that widget in the same manner as I had for the sn-record-picker and sn-choice-list tags. The code for the stand-alone rating was pretty much just a copy, paste, and slightly modify:

if (type == 'radio' || type == 'inlineradio') {
	htmlText += buildRadioTypes(attrs, name, model, required, type);
} else if (type == 'select') {
	htmlText += buildSelect(attrs, name, model, required);
} else if (SPECIAL_TYPE[type]) {
	htmlText += buildSpecialTypes(attrs, name, model, required, type, fullName, label);
} else if (type == 'reference') {
	htmlText += "      <sn-record-picker field=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\"" + passThroughAttributes(attrs) + (required?' required':'') + "></sn-record-picker>\n";
} else if (type == 'choicelist') {
	htmlText += "      <sn-choice-list sn-model=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\"" + passThroughAttributes(attrs) + (required?' required':'') + "></sn-choice-list>\n";
} else if (type == 'rating') {
	htmlText += "      <uib-rating ng-model=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\"" + passThroughAttributes(attrs) + (required?' required':'') + "></uib-rating>\n";
} else ...

For the combination of a rating and a comment block, things got a little more complicated. In all of my other field types, I passed through to the input element all of the original attributes that did not have some other purpose in rendering out the entire block of code. For the first time, I had more than one input element, as I was combining the rating doodad with the textarea for the comments all under one label. After experimenting with different ways to distinguish attributes for one of the elements from attributes for the other, I decided against making things more complicated than they needed to be, and just assume that all non-standard attributes would be attributed to the textarea. Once that was settled, the resulting code turned to be the following:

...
} else if (type == 'rating') {
	htmlText += "      <uib-rating ng-model=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\"" + passThroughAttributes(attrs) + (required?' required':'') + "></uib-rating>\n";
} else if (type == 'textarea' || type == 'feedback') {
	if (type == 'feedback' && attrs.snhRatingModel) {
		var max = 5;
		if (attrs.snhRatingMax && parseInt(attrs.snhRatingMax) > 0) {
			max = parseInt(attrs.snhRatingMax);
		}
		htmlText += "      <uib-rating ng-model=\"" + attrs.snhRatingModel + "\" max=\"" + max + "\"/>\n";
	}
	htmlText += "      <textarea class=\"snh-form-control\" ng-model=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\"" + passThroughAttributes(attrs) + (required?' required':'') + "></textarea>\n";
} else {
	htmlText += "      <input class=\"snh-form-control\" ng-model=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\" type=\"" + type + "\"" + passThroughAttributes(attrs) + (required?' required':'') + "/>\n";
}

As you can see, I did break down and allow for the max attribute by creating an snh-rating-max attribute that would not be passed in to the textarea, but other than that, the rating paired with the comments ends up basically unconfigurable. I may change that one day, but for now, this was all I needed to get me what I was after.

Anyway, I have done a little testing, and it all seems to work so far. If you would like to play around with it on your own, here is an Update Set with all of the relevant parts and pieces.

Fun with Highcharts, Part III

“It’s the little details that are vital. Little things make big things happen.”
John Wooden

So far, we have built a generic chart widget and a generic chart utility that produces chart objects from templates and dynamic data. Now it’s time to build the widget that will allow the user to pick and choose what they want to see, and then present the appropriate chart based on the user’s selections. Let’s start with a little HTML for the various pick lists that we will present to the user:

<link rel="stylesheet" type="text/css" href="/747e2219db213300f9699006db9619b9.cssdbx"/>
<link rel="stylesheet" type="text/css" href="/styles/retina_icons/retina_icons.css"/>
<div class="panel panel-default">
  <div class="panel-body form-horizontal">
    <div class="col-sm-12">
      <form id="form1" name="form1" novalidate>
        <div class="col-sm-3">
          <snh-form-field
            snh-model="c.data.group"
            snh-name="group"
            snh-label="Group"
            snh-type="choicelist"
            sn-value-field="value"
            sn-text-field="label"
            sn-items="c.data.config.groupOptions"
            ng-click="updateChart();"/>
        </div>
        <div class="col-sm-3">
          <snh-form-field
            snh-model="c.data.type"
            snh-name="type"
            snh-label="Task Type"
            snh-type="choicelist"
            sn-value-field="value"
            sn-text-field="label"
            sn-items="c.data.config.typeOptions"
            ng-click="updateChart();"/>
        </div>
        <div class="col-sm-3">
          <snh-form-field
            snh-model="c.data.frequency"
            snh-name="frequency"
            snh-label="Frequency"
            snh-type="choicelist"
            sn-value-field="value"
            sn-text-field="label"
            sn-items="c.data.config.freqOptions"
            ng-click="updateChart();"/>
        </div>
        <div class="col-sm-3">
          <snh-form-field
            snh-model="c.data.ending"
            snh-name="ending"
            snh-label="Period Ending"
            snh-type="choicelist"
            sn-value-field="value"
            sn-text-field="label"
            sn-items="c.data.config.endingOptions[c.data.frequency]"
            ng-click="updateChart();"/>
        </div>
      </form>
    </div>
    <div class="col-sm-12">
      <sp-widget widget="data.workloadWidget"></sp-widget>
    </div>
  </div>
</div>

This particular layout leverages our snh-form-field tag, but you could do basically the same thing with a simple sn-choice-list. There is nothing too exotic here, except maybe the lists of choices for the last element (Period Ending), which are contained in an object keyed by the value of the previous selection (Frequency). When you change the Frequency, the list of period ending dates changes to a list that is appropriate for the selected Frequency. Other than that one little oddity, it’s pretty vanilla stuff.

There are several reasons that I chose choicelist, which implements the sn-choice-list tag, for the snh-type of each pick list rather than reference, which implements the sn-record-picker tag. It would have been relatively easy to set up a filter on the sys_user_group table to create a record picker of active user groups, but I wanted to limit the choices to just those groups who had tasks assigned in the task table. That requires a GlideAggregate rather than a GlideRecord query, and I’m not sure how you would set that up in an sn-record-picker. For a choice list, you run the query yourself and then just set the value of the specified variable to an array created from your query results. For this widget, I created a config object to hold all of the choice list arrays, and used the following code to populate the array of choices for the group pick list:

cfg.max = 0;
cfg.maxGroup = '';
cfg.groupOptions = [];
var group = new GlideAggregate('task');
group.addAggregate('COUNT');
group.groupBy('assignment_group');
group.ordderBy('assignment_group');
group.query();
while (group.next()) {
	if (group.getDisplayValue('assignment_group')) {
		cfg.groupOptions.push({label: group.getDisplayValue('assignment_group'), value: group.getValue('assignment_group'), size: group.getAggregate('COUNT')});
		if (group.getAggregate('COUNT') > cfg.max) {
			cfg.max = group.getAggregate('COUNT');
			cfg.maxGroup = group.getValue('assignment_group');
		}
	}
}

For the choice list of task types, I wanted to wait until a group was selected, and then limit the choices to only those types that had been assigned to the selected group. This was another GlideAggregate, and that turned out to be very similar code:

var max = 0;
var defaultType = '';
data.config.typeOptions = [];
var type = new GlideAggregate('task');
type.addQuery('assignment_group', data.group);
type.addAggregate('COUNT');
type.groupBy('sys_class_name');
type.ordderBy('sys_class_name');
type.query();
while (type.next()) {
	if (type.getDisplayValue('sys_class_name')) {
		data.config.typeOptions.push({label: type.getDisplayValue('sys_class_name'), value: type.getValue('sys_class_name'), size: type.getAggregate('COUNT')});
		if (type.getAggregate('COUNT') > max) {
			max = type.getAggregate('COUNT') * 1;
			defaultType = type.getValue('sys_class_name');
		}
	}
}

The frequency choices, on the other hand, were just a hard-coded list that I came up with on my own. I wanted to be able to display the chart on a daily, weekly, monthly, quarterly, or yearly basis, so that’s the list of choices that I put together:

cfg.freqOptions = [
	{value: 'd', label: 'Daily', size: 7},
	{value: 'w', label: 'Weekly', size: 12},
	{value: 'm', label: 'Monthly', size: 12},
	{value: 'q', label: 'Quarterly', size: 8},
	{value: 'y', label: 'Yearly', size: 5}
];

The choices for period ending dates took a bit more code. For one thing, I needed a different list of choices for each frequency. For another, the methodology for determining the next date in the series was slightly different for each frequency. That meant that much of the code was not reusable, as it was unique to each use case. There is probably a way to clean this up a bit, but this is what I have working for now:

cfg.endingOptions = {d: [], w: [], m: [], q: [], y: []};
var todaysDateInfo = getDateValues(new Date());
var today = new Date(todaysDateInfo.label);
var nextSaturday = new Date(today.getTime());
nextSaturday.setDate(nextSaturday.getDate() + (6 - nextSaturday.getDay()));
dt = new Date(nextSaturday.getTime());
for (var i=0; i<52; i++) {
	cfg.endingOptions['d'].push(getDateValues(dt));
	cfg.endingOptions['w'].push(getDateValues(dt));
	dt.setDate(dt.getDate() - 7);
}
dt = new Date(today.getTime());
dt.setMonth(11);
dt = getLastDayOfMonth(dt);
cfg.endingOptions['y'].push(getDateValues(dt));
dt = new Date(today.getTime());
dt.setDate(1);
dt.setMonth([2,2,2,5,5,5,8,8,8,11,11,11][dt.getMonth()]);
dt = getLastDayOfMonth(dt);
cfg.endingOptions['q'].push(getDateValues(dt));
dt = new Date(today.getTime());
for (var i=0; i<36; i++) {
	dt = getLastDayOfMonth(dt);
	var mm = dt.getMonth();
	cfg.endingOptions['m'].push(getDateValues(dt));
	if (mm == 2 || mm == 5 || mm == 8 || mm == 11) {
		cfg.endingOptions['q'].push(getDateValues(dt));
	}
	if (mm == 11 && i != 0) {
		cfg.endingOptions['y'].push(getDateValues(dt));
	}
	dt.setDate(1);
	dt.setMonth(dt.getMonth() - 1);
}

That takes care of the four choice lists and the code to come up with the values for the four choice lists. We’ll want something selected when the page first loads, though, so we’ll need some additional code to come up with the initial values for each of the four selections. For the group, my thought was to start out with the group that had the most tasks, and if the user was a member of any groups, group of which the user was a member with the most tasks would be event better. Here’s what I came up with the handle that:

function getDefaultGroup() {
	var defaultGroup = '';

	var max = 0;
	var group = new GlideAggregate('task');
	if (data.usersGroups.size() > 0) {
		var usersGroups = '';
		var separator = '';
		for (var i=0; i<data.usersGroups.size(); i++) {
			usersGroups = separator + "'" + data.usersGroups.get(i) + "'";
			separator = ',';
		}
		group.addQuery('assignment_group', 'IN', usersGroups);
	}
	group.addAggregate('COUNT');
	group.groupBy('assignment_group');
	group.ordderBy('assignment_group');
	group.query();
	while (group.next()) {
		if (group.getDisplayValue('assignment_group')) {
			if (group.getAggregate('COUNT') > max) {
				max = group.getAggregate('COUNT') * 1;
				defaultGroup = group.getValue('sys_class_name');
			}
		}
	}
	if (!defaultGroup) {
		defaultGroup = data.config.maxGroup;
	}

	return defaultGroup;
}

Since the type choices are dependent on the group selected, that code is already built into the type selection list creation process (above). For the initial frequency, I just arbitrarily decided to start out with daily, and for the initial period ending date, I decided that the current period would be the best place to start as well. That code turned out to be pretty basic.

data.frequency = 'd';
data.ending = data.config.endingOptions[data.frequency][0].value;

With the initial choices made, we now need to work out the process of gathering up the data for the chart based on the choice list selections. That’s a bit of a task as well, so let’s make that our focus the next time out.

My Delegates Widget

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
Martin Fowler

A while back I was tinkering with creating a universal Help infrastructure for my Service Portal widgets, and one of my example images used my My Delegates widget for the demonstration.

Widget Help example using the My Delegates widget

While the concept of delegation is an out-of-the-box feature, the widget is a custom component that I built to allow Service Portal users to manage their delegates. It’s really just a portalized version of the same functionality available inside the UI, but there was no way to do that within the Service Portal itself, so I threw together a simple widget to do so. Here is the HTML:

<snh-panel rect="rect" title="'${My Delegates}'">
  <div style="width: 100%; padding: 5px 50px;">
    <table class="table table-hover table-condensed">
      <thead>
        <tr>
          <th style="text-align: center;">Delegate</th>
          <th style="text-align: center;">Approvals</th>
          <th style="text-align: center;">Assignments</th>
          <th style="text-align: center;">CC notifications</th>
          <th style="text-align: center;">Meeting invitations</th>
          <th style="text-align: center;">Remove</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="item in c.data.listItems track by item.id | orderBy: 'delegate'" ng-hide="item.removed">
          <td data-th="Delegate">
            <sn-avatar class="avatar-small-medium" primary="item.id" show-presence="true"/>
             
            {{item.delegate}}
          </td>
          <td data-th="Approvals" style="text-align: center;"><input type="checkbox" ng-model="item.approvals"/></td>
          <td data-th="Assignments" style="text-align: center;"><input type="checkbox" ng-model="item.assignments"/></td>
          <td data-th="CC notifications" style="text-align: center;"><input type="checkbox" ng-model="item.notifications"/></td>
          <td data-th="Meeting invitations" style="text-align: center;"><input type="checkbox" ng-model="item.invitations"/></td>
          <td data-th="Remove" style="text-align: center;"><img src="/images/delete_row.gif" ng-click="removePerson($index)" alt="Click here to remove this person as a delegate" title="Click here to remove this person from the list" style="cursor: pointer;"/></td>
        </tr>
      </tbody>
    </table>
    <p>To add a delegate to the list, select a person from below:</p>
    <sn-record-picker id="snrp" field="data.personToAdd" ng-change="addSelected()" table="'sys_user'" display-field="'name'" display-fields="'title,department,location,email'" value-field="'sys_id'" search-fields="'name'" page-size="20"></sn-record-picker>
    <br/>
    <p>To remove a delegate from the list, click on the Remove icon.</p>
  </div>

  <div style="width: 100%; padding: 5px 50px; text-align: center;">
    <button ng-click="saveDelegates()" class="btn btn-primary ng-binding ng-scope" role="button" title="Click here to save your changes">Save</button>
     
    <button ng-click="returnToProfile()" class="btn ng-binding ng-scope" role="button" title="Click here to cancel your changes">Cancel</button>
  </div>
</snh-panel>

Basically, it is just a table of delegates followed by an sn-record-picker from which you can choose additional people to add to the list. The source of the data is the same as that used by the internal delegate maintenance form, which you can see gathered up in server-side script here:

(function() {
	data.userID = gs.getUser().getID();
	if (input) {
		data.listItems = input.listItems || fetchList();
		if (input.personToAdd && input.personToAdd.value > '') {
			addPersonToList(input.personToAdd.value);
		}
		if (input.button == 'save') {
			saveList();
		}
	} else {
		if (!data.listItems) {
			data.listItems = fetchList();
		}
	}

    function fetchList() {
		var list = [];
		var gr = new GlideRecord('sys_user_delegate');
		gr.addQuery('user', data.userID);
		gr.orderBy('delegate.name');
		gr.query();
		while (gr.next()) {
			var thisDelegate = {};
			thisDelegate.sys_id = gr.getValue('sys_id');
			thisDelegate.id = gr.getValue('delegate');
			thisDelegate.delegate = gr.getDisplayValue('delegate');
			thisDelegate.approvals = (gr.getValue('approvals') == 1);
			thisDelegate.assignments = (gr.getValue('assignments') == 1);
			thisDelegate.notifications = (gr.getValue('notifications') == 1);
			thisDelegate.invitations = (gr.getValue('invitations') == 1);
			list.push(thisDelegate);
		}
		return list;
	}

    function saveList() {
		for (var i=0; i<data.listItems.length; i++) {
			var thisDelegate = data.listItems[i];
			if (thisDelegate.removed) {
				if (thisDelegate.sys_id != 'new') {
					var gr = new GlideRecord('sys_user_delegate');
					gr.get(thisDelegate.sys_id);
					gr.deleteRecord();
				}
			} else {
				var gr = new GlideRecord('sys_user_delegate');
				if (thisDelegate.sys_id != 'new') {
					gr.get(thisDelegate.sys_id);
				} else {
					gr.initialize();
					gr.user = data.userID;
					gr.delegate = thisDelegate.id;
					gr.starts = new Date();
				}
				gr.approvals = thisDelegate.approvals;
				gr.assignments = thisDelegate.assignments;
				gr.notifications = thisDelegate.notifications;
				gr.invitations = thisDelegate.invitations;
				gr.update();
			}
		}
		gs.addInfoMessage('Your Delegate information has been updated.');
	}

    function addPersonToList(selected) {
		var existing = -1;
		for (var i=0; i<data.listItems.length && existing == -1; i++) {
			if (data.listItems[i].id == selected) {
				existing = i;
			}
		}
		if (existing == -1) {
			var thisDelegate = {};
			thisDelegate.sys_id = 'new';
			thisDelegate.id = selected;
			var gr = new GlideRecord('sys_user');
			gr.get(selected);
			thisDelegate.delegate = gr.getDisplayValue('name');
			thisDelegate.approvals = true;
			thisDelegate.assignments = true;
			thisDelegate.notifications = true;
			thisDelegate.invitations = true;
			data.listItems.push(thisDelegate);
		} else {
			data.listItems[existing].removed = false;
		}
		input.personToAdd = {};
	}
})();

All of the changes are held in the session until you decide to Save or Cancel, and if you elect to save, then things are updated on the database at that time. On the client side of things, we just have functions to add and remove people from the list, and to handle the two buttons:

function($scope, $window) {
	var c = this;

	$scope.addSelected = function() {
		$scope.server.update().then(function(response) {
			$('#snrp').select2("val","");
		});
	};

	$scope.removePerson = function(i) {
		c.data.listItems[i].removed = true;
	};

	$scope.saveDelegates = function() {
		c.data.button = 'save';
		$scope.server.update().then(function(response) {
			reloadPage();
		});
	};

	$scope.returnToProfile = function() {
		reloadPage();
	};

	function reloadPage() {
		$window.location.reload();
	}
}

That’s the whole thing in all of its glory. If you want a copy of your own, here’s a little Update Set.

Update: There is an even better version here.

Service Portal Form Fields, Part X

“No matter how far you have traveled down the wrong road, turn back.”
— Turkish Proverb

Recently, it was brought to my attention that my little form field tag experiment did not provide the same functionality for a “choice list” that you get with the out-of-the-box sn-choice-list tag that is shipped with ServiceNow. I went ahead and dug into the source code behind the sn-choice-list, and it definitely does a lot more and provides quite a bit more flexibility. It was definitely far superior to my own feeble offering. I wanted mine to be able to do all of that.

My first thought was to just grab all of the code and stuff it into my own directive, tweaking the attribute names to conform to the snh- prefix that I had been using with all of the others. Unfortunately, that turned out to be quite a bit more of an adventure than I had originally anticipated. After further review, I made the cowardly decision to revert my code back to it’s pre-adventure state, and determined that it was time for a different approach.

My second thought was that my first thought was rather ill considered, particularly since it suddenly occurred to me that I could just wrap the existing sn-choice-list tag just exactly the way that was already wrapping the existing sn-record-picker tag. Why copy the code when you can just reference it in place and leave the future maintenance to someone else? If I were a smarter guy, that would have been my first thought and I would have saved myself a lot of pointless work that I just ended up throwing out the window. Oh, well.

I still wanted to keep my own simple choicelist option, though, so I ended up renaming that one to select, and then creating a new version of choicelist. As you can see, the new choicelist is pretty much a letter for letter copy of reference, which is my implementation of the sn-record-picker tag.

if (type == 'radio' || type == 'inlineradio') {
	htmlText += buildRadioTypes(attrs, name, model, required, type);
} else if (type == 'select') {
	htmlText += buildSelect(attrs, name, model, required);
} else if (SPECIAL_TYPE[type]) {
	htmlText += buildSpecialTypes(attrs, name, model, required, type, fullName, label);
} else if (type == 'reference') {
	htmlText += "      <sn-record-picker field=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\"" + passThroughAttributes(attrs) + (required?' required':'') + "></sn-record-picker>\n";
} else if (type == 'choicelist') {
	htmlText += "      <sn-choice-list sn-model=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\"" + passThroughAttributes(attrs) + (required?' required':'') + "></sn-choice-list>\n";
} else if (type == 'textarea') {
	htmlText += "      <textarea class=\"snh-form-control\" ng-model=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\"" + passThroughAttributes(attrs) + (required?' required':'') + "></textarea>\n";
} else {
	htmlText += "      <input class=\"snh-form-control\" ng-model=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\" type=\"" + type + "\"" + passThroughAttributes(attrs) + (required?' required':'') + "/>\n";
}

I basically copied two lines of code and then made a few edits on the copied lines. That’s it! That was definitely easier than the path that I had started on when I first set out to solve this problem. Now, I just needed to test it. I kept my original choicelist option under its new name (select), so I wanted to be able to test both. I pulled up my little test widget and copied the line that I used to test the original choicelist and made a copy. Then I tweaked one to test the select option and the other to test out the new choicelist option.

<snh-form-field
  snh-model="c.data.select"
  snh-name="select"
  snh-label="Select"
  snh-type="select"
  snh-required="true"
  snh-choices='[{"value":"1", "label":"Choice #1"},{"value":"2", "label":"Choice #2"},{"value":"3", "label":"Choice #3"},{"value":"4", "label":"Choice #4"}]'/>
<snh-form-field
  snh-model="c.data.choicelist"
  snh-name="choicelist"
  snh-label="Choice List"
  snh-type="choicelist"
  snh-required="true"
  sn-value-field="value"
  sn-text-field="label"
  sn-items="c.data.choicelistchoices"/>

Since the whole purpose of bringing in the stock sn-choice-list in the first place was to allow for the use of a variable for the choices, I went ahead and defined a variable for that purpose and populated it in the server-side code:

data.choicelistchoices = [{"value":"1", "label":"Choice #1"},{"value":"2", "label":"Choice #2"},{"value":"3", "label":"Choice #3"},{"value":"4", "label":"Choice #4"}];

All that was left now was to bring up the test page and see how things turned out.

Select option and Choice List option rendered on the page

Well, it all seems to work. I guess it’s time to post yet another Update Set.