“No matter how far down the wrong road you have gone, turn back.” — Turkish Proverb
I love making parts. That’s pretty much what I do. But even more than that, I love finding parts. If I can locate the part that I need, then I don’t have to build it, and even more important, I don’t have to maintain it. Nothing lasts forever, and all parts require periodic maintenance at one point or another, if for no other reason that to keep pace with an ever changing world. Even if I have already created a part for a particular purpose, if I can find a viable replacement, then I will gladly discard my own creation in favor of an acceptable newly released component or third-party alternative.
In fact, it doesn’t even have to be new — ServiceNow is so chock full of valuable gems that it would be impossible for any single individual to know and understand what’s under every rock in every corner of every room. I find stuff all of the time that I had no idea had been in there all along. And when I find an out-of-the-box doodad that can replace some custom-crafted gizmo that I built because I didn’t know any better, I will gladly toss aside my own creation to embrace what the product has to offer.
Not too long ago, I was pretty proud of myself for coming up with a way to display Portal Pages in a modal pop-up on a UI Page. That was pretty cool at the time, but what is even better is to find out that I never had to go to all of the trouble. My way of doing it looked like this:
var dialog = new GlideDialogWindow("portal_page_container");
dialog.setPreference('url', '/path/to/my/widget');
dialog.render();
… and it required a component that I had built for just that purpose, the portal_page_container. That worked, which is always import. However, there is a better way: using a built-in component that will essentially accomplish the same thing without the need for the extra home-made parts. Instead of a GlideDialogWindow, the trick is to use a GlideOverlay:
var go = new GlideOverlay({
title: 'Title of My Widget',
iframe : '/path/to/my/widget',
closeOnEscape : true,
showClose : true,
height : "90%",
width : "90%"
});
go.center();
go.render();
Now I can pitch that portal_page_container into the trash. It served its purpose honorably, but when things are no longer needed, it’s time to let go and move on!
“It has long been an axiom of mine that the little things are infinitely the most important.” — Sir Arthur Conan Doyle
When we last left this particular widget, I was experiencing problems with the companion button-handling widget executing more than one time per click. While my little conditional work-arounds seem to have hidden the unwanted results of that unfortunate behavior, I am still no closer to understanding how or why that is happening. In my simple mind, one click on the button should result in one execution of the activated code. Given that I don’t really know what I am doing, I may never understand why that isn’t the case, but it annoys my sense of The Way Things Ought To Be. Still, it’s probably long past time to simply move on.
Before I do, though, there is one more little enhancement that I wanted to squeeze in. Whenever I lay out a page where the content selector is on the top, instead of on the left- or right-hand side of the actual Data Table, it takes up too much vertical space and leaves a lot of unused screen real estate on either side. To change that, I added a new option to the widget called display_inline that changes the way the elements of the widget are laid out. Below is a sample use case where display_inline has been set to true.
The magic to pull that off was just the addition of conditional class attributes on each of the three primary DIV elements. There was already a class attribute on each, so I could have just thrown some logic in there, but in the end I decided to leverage the AngularJSng-class attribute instead. By adding the Bootstrap class col-sm-4 to the DIV whenever data.inline is true, the DIVs end up side by side instead of their normal stacked configuration.
Of course, I had to define the Display Inline option as well, but that was just a matter of updating the widget’s Option schema will a little JSON object:
[{"hint":"If selected, will display the widget content in a single row rather than a stacked block",
"name":"display_inline",
"default_value":"false",
"section":"Behavior",
"label":"Display Inline",
"type":"boolean"}]
That’s about it for allowing this to stretch out across the page rather than be stacked up in the corner. Hopefully, this will be the last you see of this unless I happen to figure out my other issue. For those of you who are interested in seeing all of the parts and pieces in detail, I have assembled everything into yet another Update Set, which you can grab from here.
“Everyone thinks of changing the world, but no one thinks of changing himself.” — Leo Tolstoy
After all of that work on customizing the Data Table widget(s), I realized that my Data Table Content Selector widget didn’t support all of the new features. If I wanted to have buttons or icons or customized reference links, I needed to tweak the code a little bit to provide that capability. Primarily, I needed to expand the schema for my configuration object to include options for buttons and reference pages for every table configuration. That would make the typical state value for a given table look something like this:
To maintain backwards compatibility, both of the new options, btnarray and refmap, would need to be optional. Since the content selector widget relies on the URL-based version of the Data Table widget, implementing the new features was simply a matter of including them, if present, in the new URL at every page refresh:
function refreshPage(table, perspective, state) {
var tableInfo = getTableInfo(table, perspective);
var s = {};
s.id = $location.search().id;
s.table = tableInfo.name;
s.filter = tableInfo[state].filter;
s.fields = tableInfo[state].fields;
s.buttons = '';
if (tableInfo[state].btnarray && Array.isArray(tableInfo[state].btnarray) && tableInfo[state].btnarray.length > 0) {
s.buttons = JSON.stringify(tableInfo[state].btnarray);
}
s.refpage = '';
if (tableInfo[state].refmap) {
s.refpage = JSON.stringify(tableInfo[state].refmap);
}
s.px = perspective;
s.sx = state;
var newURL = $location.search(s);
spAriaFocusManager.navigateToLink(newURL.url());
}
That was basically all there was to it. Now I just need to create a new configuration object that takes advantage of these new features. My original example configuration contained two perspectives, Requester and Fulfiller. To show off the new buttons feature, I decided to add a third perspective, Approver, and then include three separate icons, one to Approve, one to Approve with comments, and another to Reject. The button configuration that I created to support this turned out like this:
btnarray: [
{
name: 'approve',
label: 'Approve',
heading: '-',
icon: 'workflow-approved',
color: 'success',
hint: 'Click here to approve'
},{
name: 'approvecmt',
label: 'Approve w/Comments',
heading: '-',
icon: 'comment-hollow',
color: 'success',
hint: 'Click here to approve with comments'
},{
name: 'reject',
label: 'Reject',
heading: '-',
icon: 'workflow-rejected',
color: 'danger',
hint: 'Click here to reject'
}
]
After entering some additional modifications to the configuration to add the new perspective, the resulting page ended up looking like this:
That took care of the look and feel, but to make the buttons actually work, I needed to create another button handling widget to process the button clicks on the three icons that I had configured. For that, I just grabbed the example that I had created earlier and cloned it to create a new Approval Click Handler widget. Here is the client script:
function(spModal, $rootScope) {
var c = this;
$rootScope.$on('button.click', function(e, parms) {
if (!c.data.inProgress) {
c.data.inProgress = true;
c.data.sys_id = parms.record.sys_id;
c.data.action = parms.button.name;
c.data.comments = '';
if (c.data.action == 'reject' || c.data.action == 'approvecmt') {
getComments(c.data.action);
} else if (c.data.action == 'approve') {
processDecision();
}
c.data.inProgress = false;
}
});
function getComments(state) {
var msg = 'Approval comments:';
if (state == 'reject') {
msg = 'Please enter the reason for rejection:';
}
spModal.prompt(msg, '').then(function(comments) {
c.data.comments = comments;
processDecision();
});
}
function processDecision() {
c.server.update().then(function(response) {
window.location.reload(true);
});
}
}
… and here is the server side script:
(function() {
if (input) {
var current = new GlideRecord('sysapproval_approver');
current.get(input.sys_id);
if (current.state == 'requested') {
current.state = 'approved';
if (input.action == 'reject') {
current.state = 'rejected';
}
var comments = 'Approval response from ' + gs.getUserDisplayName() + ':';
comments += '\n\nDecision: ' + current.getDisplayValue('state');
if (input.comments) {
comments += '\nReason: ' + input.comments;
}
current.comments = comments;
current.update();
}
}
})();
When I first pulled this up and tested the various buttons, a single click appeared to launch multiple iterations of the code. After entering comments in the modal pup-up box, another comment entry box would pop-up as if I had clicked on the icon a second time. Looking at the resulting records, the entered comments would often appear multiple times. On one example, it was entered 10 times! I never did figure out why that was happening, but I added conditionals to both the client side and server side scripts in an effort to put a stop to that behavior. That seems to have stopped it, but that still doesn’t explain to me why that is happening.
Looks like I have a little more testing to do before I put together a final Update Set …
“Never give up on something that you can’t go a day without thinking about.” — Winston Churchill
Those of us who develop software for a living always like to blame the customer for the inevitable scope creep that works its way into an assignment or project. The real truth of the matter, though, is that a lot of that comes right from the developers themselves. Often, just when you think you are about to wrap something up and call it complete, you get that nagging you-know-it-would-be-even-better-if-we-added-this feeling that just won’t go away.
It was my intention to make my previous installment on the Custom Data Table widget my last and final offering on the subject. I had this idea to create a custom Service Portal breadcrumbs widget that didn’t require you to specify the entire page hierarchy on every page where it was included, and I was ready to dive into that little adventure. But there were still a couple of things pulling at me on the Data Table widget(s), and I just felt compelled to wrap those up before I moved on. For one, I never really implemented the buttons and icons as URL parameters in the version of the wrapper widget that was based on the URL. On top of that, I never really liked reusing the same page for all reference links; I wanted to create the capability to have different pages for different references. None of that was really super critical, but I couldn’t really call it complete until I took care of that, so here we are.
For the reference links, I decided to create a simple JSON object that mapped reference tables to portal pages. Primarily, I wanted to send all user references to the user_profile page, but I also wanted to create possibility of sending any reference to any page. So I added yet another configuration option, much like the other two that are already there:
[
{
"hint":"If enabled, show the list filter in the breadcrumbs of the data table",
"name":"enable_filter",
"default_value":"false",
"section":"Behavior",
"label":"Enable Filter",
"type":"boolean"
},{
"hint":"A JSON object containing the specification for row-level buttons and action icons",
"name":"buttons",
"default_value":"",
"section":"Behavior",
"label":"Buttons",
"type":"String"
},{
"hint":"A JSON object containing the page id for any reference column links",
"name":"refpage",
"default_value":"",
"section":"Behavior",
"label":"Reference Pages",
"type":"String"
}
]
This creates yet another text input on the widget configuration page just under the one that we created for the button specifications:
The JSON object itself is just a simple mapping of table name to portal page name (id). To support my intent to bring up all users via the User Profile page, I used the following JSON object:
{
"sys_user": "user_profile"
}
To add more options, you just add more properties to the object using the table name as the property name and the associated page name/id as the property value. To make all of that work, I had to pull in the JSON string and then parse it out to create the actual object to be used.
if (data.refpage) {
try {
var refinfo = JSON.parse(data.refpage);
if (typeof refinfo == 'object') {
data.refmap = refinfo;
} else {
gs.error('Invalid reference page option in SNH Data Table widget: ' + data.refpage);
data.refmap = {};
}
} catch (e) {
gs.error('Unparsable reference page option in SNH Data Table widget: ' + data.refpage);
data.refmap = {};
}
} else {
data.refmap = {};
}
Once you have all of that tucked away for future reference, whenever a reference link is clicked, we simply refer to the map to see if there is a specific page associated to the table specified in the reference link. If there is, we simply pass that along with the rest of the parameters when we broadcast the reference click.
if (c.data.refmap[table]) {
parms.page_id = c.data.refmap[table];
}
For those listening for the reference click, all we needed to do was to check for the presence of a page_id in the parms before we check for a page_id in the options, which we were already doing before we settled on the default page of ‘form’.
var p = parms.page_id || $scope.data.page_id || 'form';
That’s about it for supporting table-specific reference link pages. The other thing that I wanted to do was to make sure that my Data Table from URL Definition widget also supported buttons and icons as well as the new reference link page specifications. That turned out to be a simple matter of just adding those two extra options to the existing copyParameters function call to have those values pulled in from the URL and added to the data passed to the core Data Table widget.
With that in place, you can add something like &refpage={“sys_user”:”user_profile”} to the URL for the page and have that picked up by the Data Table from URL Definition widget and processed just as if it were specified in the widget options. I’ve wrapped all of that up into yet another Update Set for those of you who are into that sort of thing. Hopefully, this will bring this little adventure to a close now, and I can move on to other things.
“Quality is not an act; it is a habit.” — Aristotle
In order to test my Data Table buttons and icons, I’m going to need a way to trigger both options, navigating to a new page and processing the global broadcast. Since my initial test page was configured to use the sys_user table, bouncing over to the User Profile page seems like easiest thing to do to demonstrate the first. But, to demonstrate the second, I’m going to have to create another widget, one that I will build just to prove that the other option works as well. Before we do that, though, let’s set up the button configuration JSON object to create one button and one icon, and have one implement the first option and the other implement the second. That will set things up for our testing.
[
{
"name":"button",
"label":"Button",
"heading":"Button",
"color":"primary",
"page_id":"user_profile",
"hint":"Clicking this button should take you to the User Profile page"
},{
"name":"icon",
"label":"Icon",
"heading":"Icon",
"icon":"user",
"hint":"Clicking this icon should open a modal pop-up"
}
]
We can enter that configuration using the Page Designer and clicking on the Edit icon (pencil) to bring up the options screen:
With that configured, we can actually test the button right away, as that one is configured to branch to another page (user_profile). We can’t test the icon, though, until we build a widget to listen for the broadcast.
So, I went over to the Service Portal Widgets list and clicked on the New button to create a net new widget to listen for the broadcast message. The only things this widget will do is listen and take action, so I didn’t need a Body HTML template and I didn’t need a Server script, so I just left those blank. For the Client controller, I just entered this:
This was about a simple as I could think of and still test out the process. Unfortunately, when I tested it, it didn’t work. It turns out that the stock user-profile widget cannot accept a sys_id from input. Well, that’s easily enough fixed, but I had to clone the user-profile widget to add in the code, and then I had to have my new listener widget launch the cloned snh-user-profile widget instead of the original. Now, that worked.
The listener widget has no HTML body, so you can pretty much drag it anywhere on the page. Once it shares the page with the customized Data Table widget, it will be able to pick up the broadcast and do whatever it is that you want to do. My example just checks for a ‘button-click’ event, but if you have more than one button on your page, you may also what to check to see which button was clicked before you take any action. I’ll leave that to those of you who want to try all this out on your own.
One unfortunate bit of bad news, though: in the process of testing all of this out, I clicked on one of the column headings to sort the list and my buttons disappeared. That was deflating! That’s why we pull on all of the levers and twist all of the dials, though. It’s important to check everything out thoroughly. Still, I hate to be reminded that I don’t really know what I am doing. It will probably take me a while to dig around, find the source of the problem, and come up with a viable solution. Still, I did promise to publish an Update Set soon, so I think I am going to go ahead and do that, even though this version violates Rule #1. If you don’t mind playing around with something that is obviously broken, you can get the version 1.0 Update Sethere. Just be aware that there is a flaw that has yet to be corrected. Speaking of which, I better get busy diagnosing and correcting that problem.
“All life is an experiment. The more experiments you make, the better.” — Ralph Waldo Emerson
Now that we’ve tweaked the Data Table widget to support reference links and action buttons and icons, it’s time to add the code that will process the clicks on the buttons and icons. There are a number of things that we could do here, but since I like to start out small and build things up over time, today I think I will just handle a couple of the options: 1) navigating to another page, and 2) broadcasting the click and letting some other widget or function take it from there. The first is basically just a copy of what is already being done for the primary row link and the reference links and the second is just the weasel way out of building other options into the Data Table widget itself. By broadcasting the details of the click, users can pretty much do whatever it is that they would like to do by setting up listeners for the broadcast, and then I won’t have to add any additional logic or options on my end.
But before we get into all of that, I do have to admit that I got a little sidetracked the other day and started to tinker. Since I had already opened up the code and was messing with it anyway, I decided to go ahead and see if I could add a user avatar to any reference to the sys_user table. I had to dig around a little bit to see how that was done, but it is actually pretty simple with the sn-avatar tag.
I had to play around with the classes for various things to get everything to come out visually the way that I wanted, but the end result turned out to be a relatively simple addition to the HTML:
Now, back to our regularly scheduled programming …
In the main Data Table widget’s Client Controller, I virtually copied the existing go function and then just added in a quick loop to hunt through the configured buttons to find the one that was clicked so that we could pass it on. Other than that, it’s virtually the same as the original:
$scope.buttonclick = function(button, item) {
spNavStateManager.onRecordChange(c.data.table).then(function() {
var parms = {};
parms.table = c.data.table;
parms.sys_id = item.sys_id;
parms.record = item;
for (var b in c.data.buttons) {
if (c.data.buttons[b].name == button) {
parms.button = c.data.buttons[b];
}
}
$scope.ignoreLocationChange = true;
for (var x in c.data.list) {
c.data.list[x].selected = false;
}
item.selected = true;
$scope.$emit(eventNames.buttonClick, parms);
}, function() {
// do nothing in case of closing the modal by clicking on x
});
};
Then, on the wrapper widgets, I copied the original listener and hacked it up to look into the button spec to see if there was a page configured. If so, then I navigate to the page; otherwise, I simply broadcast the click on the root scope so that another, independent widget can pick things up from there:
$scope.$on('data_table.buttonClick', callButtonClick);
function callButtonClick(e, parms) {
if (parms.button.page_id) {
var oid = $location.search().id;
var p = parms.button.page_id;
var s = {id: p, table: parms.table, sys_id: parms.sys_id, view: $scope.data.view};
var newURL = $location.search(s);
spAriaFocusManager.navigateToLink(newURL.url());
} else {
$rootScope.$broadcast('button.click', parms);
}
}
That was all there was to it. Now all that’s left is to write a sample independent widget to listen for the broadcast and test all of this out to make sure that it all works. That should wrap all of this up quite nicely and should turn out to be the final installment in this particular series.
“It always seems impossible until it’s done.” — Nelson Mandela
Today I am going continue on with my little Data Table widget customization by tackling the HTML portion of project, and then set things up so that we can do a little testing. Currently, the HTML that displays a single row in the data table does so in a way that the entire row is the clickable link to the details for that row. My intent is to change that so that the first column is the link to the details for that row, and then any other column that contains a reference field can be a link to the details of that specific reference. So, let’s take a look at the HTML structure that is there now:
I’m not quite sure what purpose is served by that first <TD> that doesn’t repeat, but there is a column heading to match, although neither appear to have any value or content. Maybe it’s a spot for a row-level checkbox or a glyph or something, but I’m not really smart enough to figure it out. The first thing that I did on my version was to delete it, along with the associated column heading — if I don’t understand why it needs to be there, then it just needs to go. Of course, that has nothing to do with what I am trying to accomplish, but if you happen to notice it gone in my version, that’s because I made it gone. I may end up having to go out and look for it one day when I finally figure out its value, but for now at least, it sleeps with the fishes.
With that out of the way, we can focus on the actual table columns, which are all treated the same in this version. The entire cell, not just the content, is the link to further information on the row, and with every column the same, no matter where you click on the row, the result is the same. We don’t want to do that in our version, though, so we can keep the ng-repeat on the <TD>, but the rest will be dependent on the column. Since we want the links to be on the content and not on the entire cell, we don’t really need anything else at the <TD> level anyway.
The first column will always be a link, and it will perform the same function as clicking anywhere on the row in the original version. For all other columns, they will also be links if the data type is reference, and there is a value. We can use the $first property to detect the first column, so the code for that link can basically be lifted from the original, with the addition of an ng-if to target the first column.
<a ng-if="$first" href="javascript:void(0)" ng-click="go(item.targetTable, item)" title="${Click for more on }{{::item[field].display_value}}">{{::item[field].display_value}}</a>
The remaining columns will require a few more lines. Not only do we need to determine that this not the first column, we also need to check to see of the type is reference, and if there is a value (if there is no value, then there is no need to code the link). Wrapping the whole thing in a <SPAN> will allow us to separate all of this from the first column, and then we can use an anchor tag for the links and a simple <SPAN> for the rest.
<span ng-if="!$first">
<a ng-if="item[field].value && item[field].type == 'reference'" href="javascript:void(0)" ng-click="go(item[field].table, item[field].record)" title="${Click for more on }{{::item[field].display_value}}">{{::item[field].display_value}}</a>
<span ng-if="!item[field].value || item[field].type != 'reference'">{{::item[field].display_value}}</span>
</span>
At this point, I am leveraging the existing go function to handle the clicks. That function takes a table and a record as an argument, so I figure that I can just pass in the name of the referenced table and a mocked-up record (more on that later) and simply reuse the existing function. I may want to rethink that later and create a function specifically for reference field clicks, but for now this works, so it’s good enough. My earlier server-side additions did not originally create mocked-up record for each reference field, so I had to go back and that in to bring all of this together. I added that to the same block of code where I was adding the name of related table.
Well, that should do it — at least, for this initial version. Now we just need to take it out for a spin and make sure that everything works. For that, we’ll need to create a test page and then put the widget on the page and configure it. Then we can hit the Try It! button.
Well, that wasn’t too bad. Everything seems to work as I had intended. Nothing happens right now when you click on anything, but that’s because the go function simply broadcasts the click events, and I don’t have anything listening for that in this version. This was a clone of the core Data Table widget, and the listeners are in the wrapper widgets that implement the various ways to configure the display and contents. I’ll have to clone those wrapper widgets as well, or maybe modify them to choose between the stock Data Table widget and my customized version. Either one seems like a lot more work than I want to dive into right now, so I’m going to leave that for a later installment.
“The journey of a thousand miles begins with a single step.” — Lao Tzu (Tao te Ching)
Last week, I had this idea, and today I think I have a fairly good plan. I am going to make a copy of my old sn-panel hack and make myself another Angular Provider for a generic form field and all of the associated trimmings. My strategy, as usual, is to start out small see what I can get to work, and then build it up piece by piece until it finally does everything that I want it to do. I’ll use the tag snh-form-field to invoke the provider, and then I will create my own snh-* attributes and snh-* styles, just to be sure that I don’t conflict with anything already existing in the platform. Ultimately, I want to be able to support any kind of valid HTML5 input, but to start with, I’m going to limit the initial version to just text and textarea fields. At this point, I don’t want to drive things off of the dictionary; I see that as something that would live outside of this process. Everything will be driven off of the attributes specified in the tag, and if I ever do add something driven off of the dictionary, it will simply leverage this work and use the dictionary to determine what the attribute values should be.
To begin, let’s start out with the basic template. This is pretty much the heart and soul of the entire operation, so might as well start out with the basic HTML framework to be used for all types of input. Here is my first attempt at the essential code needed to produce the simplest of structures to include all of the standard elements:
var htmlText = '';
var name = attrs.snhName;
var model = attrs.snhModel;
var type = attrs.snhType || 'text';
type = type.toLowerCase();
if (SUPPORTED_TYPE.indexOf(type) == -1) {
type = 'text';
}
var required = attrs.snhRequired && attrs.snhRequired.toLowerCase() == 'true';
htmlText += " <div id=\"element." + name + "\" class=\"form-group\">\n";
htmlText += " <div data-type=\"label\" id=\"label." + name + "\" nowrap=\"true\">\n";
htmlText += " <label for=\"" + name + "\" class=\"col-xs-12 col-md-4 col-lg-6 control-label\">\n";
htmlText += " <span id=\"status." + name + "\"";
if (required) {
htmlText += " ng-class=\"" + model + ">''?'snh-required-filled':'snh-required'\"";
}
htmlText += "></span>\n";
htmlText += " <span title=\"" + attrs.snhLabel + "\" data-original-title=\"" + attrs.snhLabel + "\">" + attrs.snhLabel + "</span>\n";
htmlText += " </label>\n";
htmlText += " </div>\n";
if (attrs.snhHelp) {
htmlText += " <div id=\"help." + name + "\" class=\"snh-help\">" + attrs.snhHelp + "</div>\n";
}
if (type == 'textarea') {
htmlText += " <textarea class=\"form-control\" ng-model=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\"" + (required?' required':'') + "></textarea>\n";
} else {
htmlText += " <input class=\"form-control\" ng-model=\"" + model + "\" id=\"" + name + "\" name=\"" + name + "\" type=\"" + type + "\"" + (required?' required':'') + "/>\n";
}
htmlText += " <div id=\"message." + name + "\" class=\"snh-error-msg\" ng-show=\"" + model + "ErrorMsg>''\">{{" + model + "ErrorMsg}}</div>\n";
htmlText += " </div>\n";
return htmlText;
The first thing that you see is that we pull some commonly used variables out the associated attributes, mainly for the sake of clarity and brevity. The first real line of HTML is the outer enclosing DIV of everything else, which we name in accordance with the standard as “element.” plus the “name” of the field. The next line is the outer enclosing DIV of field label, which we name in accordance with the standard as “label.” plus the “name” of the field. Next is the LABEL tag, which doesn’t have a name, followed by the SPAN for the required marker, which we name in accordance with the standard as “status.” plus the “name” of the field. After that comes the SPAN for the field label, which also doesn’t have a name, but uses the snh-label attribute for the title as well as the value. Following the label SPAN is the closing LABEL tag and then the closing DIV tag for the field label elements, completing the field label block.
Just below the field label there is an optional DIV for field-level help. You don’t see that all that much, but it is an option on ServiceNow forms, so I wanted to be sure to include it. After that comes the INPUT element itself, the formatting of which is entirely dependent on the type of input. For now, just to have something to start with, I am only supporting two different types, text and textarea. We’ll add more later, but this will be enough to get us started. After the INPUT element, we have the DIV for validation errors, and then we wrap everything up with the closing DIV tag for the outer enclosure. That completes the basic HTML structure for a form field.
To try it out, we’ll need a simple widget with a few form fields defined. Just to see how things come out, let’s do a few text fields and a few textarea fields, make some required and some not required. And just for fun, let’s wrap the whole thing in the old snh-panel.
Of course, we have to build a Portal Page so that we have somewhere to put our widget, but that’s all basic ServiceNow stuff that we don’t need to go into here. Let’s just assume that we did all that and get right to the good stuff, which is to see how it all comes out when you bring up in the browser.
Not bad! The required marker actually works pretty cool … the minute that you type a single letter into the field, it goes from red to grey. I’m used to that changing once you leave the field, but this does it right then and there while you are entering the data. The form doesn’t validate just yet, but hey — it’s a start. I think I am going to really like this once it has all been put together. Next time, we will add a little more and see just how much further we can get …
“Everything should be made as simple as possible, but not simpler.” — Albert Einstein
Last time, we got far enough along in the System Property value page modifications to demonstrate that we could replace the rendered input element with something else of our own design. Not having a design of our own for an adequate replacement, we implemented the popular creative avoidance strategy by working on all of the other parts and pieces first until we finally ran out of other parts and pieces. Now it is time to come up with a plan and finish this little project up.
I have to admit that I’m not all that proud of what I eventually came up with, but it does satisfy Rule #1, so at this point, I’ll take it and call it good. I tried a number of other things first, but none of those really got me what I wanted, so here we are. The basic plan is pretty simple, and consists of two parts: 1) a hidden input element to replace the text input element so that it can be submitted with the form, and 2) an iframe into which we will put our new input element via a stand-alone page designed for that purpose. I don’t really like the iframe approach, but it does have the benefit of being independently rendered, which gives us the opportunity to leverage the snRecordPicker for our input, which we really cannot do by simply modifying the main page directly after it has been delivered.
So let’s start out with the script that will build the HTML that we will use to replace the original text input element:
function buildHTML(prop) {
var html = "";
html += "<input type=\"hidden\" id=\"" + prop.property + "\" name=\"" + prop.property + "\"/>\n";
html += "<div style=\"width: 100%; height: auto;\">\n";
html += " <iframe id=\"frame." + prop.property + "\" src=\"/$sp.do?id=reference_properties&sysparm_property=" + prop.property + "&sysparm_table=" + prop.tableName + "&sysparm_column=" + prop.column + "&sysparm_value=" + prop.value + "\" style=\"border: none; height: 65px; width: 100%;\"></iframe>\n";
html += "</div>\n";
return html;
}
The hidden input element virtually replaces the original text input element, having the same name and same id. The iframe element is pretty vanilla stuff as well; the only thing of interest really is the src parameter, which points to the Portal Page that we are about to create, and passes along all of the various values needed to make the page do what we want. The Portal Page itself is just a single page with a single container filled with a single widget. The page is not really worth looking at, so let’s just jump right into the widget, as that’s where all of the magic happens. Here is the HTML:
Not much to see there, either. It’s just your standard snRecordPicker with pretty much every attribute defined by a variable. We’ll snag the values for those variables off of the URL for the page, which we populated when we constructed the src attribute for the iframe tag. The widget’s client-side script does most of the heavy lifting here:
The only reason for the server-side script is to fetch the display value of the property if the property is valued at the time that the page is delivered to the browser.
(function() {
if (input) {
if (input.fieldValue) {
var gr = new GlideRecord(input.table);
gr.get(input.fieldValue);
data.fieldDisplayValue = gr.getDisplayValue(input.column);
} else {
data.fieldDisplayValue = '';
}
}
})();
That’s about all there is to it. For every property on the page where Type=reference, the standard text input element is replaced with a hidden input element and an iframe, and inside the iframe is a ServiceNow Service Portal page that contains a single widget containing a single snRecordPicker. The parameters for the picker are passed from the iframe to the portal page via URL parameters, which are picked up by the widget and used to configure the snRecordPicker. All changes to the snRecordPicker are copied over to the hidden input field, so when the form is submitted, the selected value is sent to the server and posted to the database.
There was a minor problem with this initial version when trying to figure out the optimum height for the iframe. The height of the snRecordPicker depends on whether or not the drop-down list of choices is present, and I couldn’t find a CSS-centric way of having the iframe automatically adjust for the change in height, nor could I find a way to have the drop-down list of selectable choices overlay the content below, which is outside of the iframe. Finally, I resorted to plain old Javascript, and set up a variable called c.data.expanded to indicate whether or not the pick list was present on the screen. With a little view selection source magic, I was able to figure out that the component to watch had an id of select2-drop-mask, and so I modified the widget’s client-side code to check the required iframe height every second and adjust if needed:
Once that code was in place, the unexpanded state looked like this:
… and the expanded state looked like this:
It still disturbs my sense of The Way Things Ought To Be for the left-hand edge of the revised input element not to line up with the left-hand edge of all of the other original input elements, but a fix to that was not readily apparent to me, so I have managed to let that go for now and move on to more important things. One day, though, I am going to figure out a way to fix that!
Just to recap, we modified a choice list and added an additional field to a table to provide the capability to define properties of type reference. We then created a UI Script and a Script Include so that we could replace the original input element on the property UI page, and then we created a Service Portal page and associated widget to provide the replacement for the original input element. As soon as I get a chance, I will see if I can wrap all of that up into a single Update Set and get it posted out here in case anyone wants just grab the whole package. All in all, it was a fun little project, but one that I hope to throw away one day when ServiceNow actually supports reference type properties right out of the box and having this little tweak is no longer needed.
Update: Well, it took a little longer than I had hoped to get around to this, but here is that Update Set finally.