Formatted Script Search Results, Enhanced

“Delivering good software today is often better than perfect software tomorrow, so finish things and ship.”
— David Thomas, The Pragmatic Programmer: From Journeyman to Master

It always seems to happen. The more I play around with some little bauble that I’ve thrown together, the more ideas that pop into my head to make it just a little bit better. I’ve actually found my script search tool to be quite useful now that I have finally gotten it to behave the way in which I would expect it to behave. But the more that I use it, the more that I find that I want add to it.

One thing that I realized after I released the code was that you can also find script in Condition String fields. This blows my whole theory that all column types that contain script have the word script in their name. Still, I can tweak my encoded query just a bit to ensure that these columns are searched as well. I just need to switch from this:

internal_typeCONTAINSscript^active=true^name!=sn_templated_snip_note_template

… to this:

active=true^name!=sn_templated_snip_note_template^internal_typeCONTAINSscript^ORinternal_type=condition_string

Another thing that crossed my mind while I was searching for something the other day was that, in addition to scripts, I would really like to have this same capability for searching HTML. At the time, it seemed like it wouldn’t be too difficult to just clone all of the parts and convert them to a second set that was dedicated to HTML instead of Javascript. When I took a look at doing that, though, I realized that with just little bit of extra code, I could make the parts that I had work for both, and not have to create an entirely new second set.

The first thing that I tackled was my Script Include, ScriptUtils, To start out, I renamed it to SearchUtils, since it was now going to handle both searching all of the script columns and searching all of the HTML columns. Then I added a second argument to the function call called type, so that I could differentiate between script search requests and HTML search requests. The only real difference in the code between searching for script and searching for HTML is which columns on which tables will be queried, which means that the only real difference between the two operations is the query used to find the columns and tables. In the current version, that query was hard-coded, so I switched that to a variable and then set the value of the variable to the new version of my encoded query for scripts, and then overrode that value with a new query for HTML if the incoming type argument was set to ‘html’.

var SearchUtils = Class.create();
SearchUtils.prototype = {
	initialize: function() {
	},

	findInScript: function(string, type) {
		var table = {};
		var found = [];
		var encodedQuery = 'active=true^name!=sn_templated_snip_note_template^internal_typeCONTAINSscript^ORinternal_type=condition_string';
		if (type == 'html') {
			encodedQuery = 'active=true^name!=sn_templated_snip_note_template^internal_typeCONTAINShtml';
		}
		var columnGR = new GlideRecord('sys_dictionary');
		columnGR.addEncodedQuery(encodedQuery);
...

Beyond that point, everything else remains the same as it was in the earlier version. That takes care of the Script Include. Now we have to tackle the associated Widget. Here we can use the same basic philosophy, defaulting everything to a script search, and then overriding that default if an HTML search is requested. For a Widget, that request can come in the form of an additional URL parameter that we can also call type. We can establish the default values based on a script search, and then if the URL parameter type is equal to ‘html’, we can then change to the values for an HTML search.

(function() {
	data.type = 'script';
	data.title = 'Script Search';
	if ($sp.getParameter('type') && $sp.getParameter('type') == 'html') {
		data.type = 'html';
		data.title = 'HTML Search';
	}
	data.loading = false;
	data.searchFor = '';
	data.result = false;
	if ($sp.getParameter('search')) {
		data.loading = true;
		data.searchFor = $sp.getParameter('search');
		data.result = new SearchUtils().findInScript(data.searchFor, data.type);
		data.loading = false;
	}
})();

That was all there was to adding an HTML version of the script searching capability. To get to it, I pulled my Search Script menu item up in edit mode by clicking on the little pencil to the right of the title, made a few minor modifications and then selected Insert from the context menu to create a new menu item.

Cloning the Search Script menu item to create the Search HTML menu item

With the new menu item added to the sidebar, the only thing left to do was to click on the item and give it a go.

New HTML Search function in action

Well, that didn’t turn out too bad. I should have changed the name of the button to something that didn’t have the word script in it, but other than that one little nit, it all seems to work. I’ll fix up that button one day, but for now, here is an Update Set that includes all of the parts for the current version.

My Delegates Widget, Enhanced

“No matter how good you get you can always get better, and that’s the exciting part.”
Tiger Woods

The other day I was out on the ServiceNow Developers site and noticed that this project was highlighted on the home page of the Share site as an Editor’s Choice.

ServicePortal delegate widget

This project is quite interesting to me because it is basically an alternative approach to something that I had attempted to accomplish with the My Delegates Widget a while back. I’m always curious to see how other folks address things, so I downloaded it and checked it out. As you would assume from the 5 star rating, it’s pretty nice. In fact, it has a feature that I had not even considered back when I had put mine together: in addition to being able to manage your own delegates, you can also see who has delegated authority to you. I like that. In fact, I liked it so much that I decided to see if I could add that feature to my own slant on building this widget.

The first thing I did was to dust off my old widget, bring it up, and refresh my memory as to how it was that I put it together. This one has been out there for a while, so in addition to adding this new feature, I’m also going to have to clean it up a bit. For one thing, this was built before I read in one our HealthScans that using the name gr for variables that represent a GlideRecord is considered bad form. I think I originally copied that technique from some internal ServiceNow code, so I thought it was a little disingenuous for them to be complaining about that at the time. Still, I’ve stopped doing that ever since, and I’ve been fixing it whenever I come across it in my older stuff.

All that aside, it was a pretty simple addition. I copied the block of code that generated the list of delegates (once I cleaned it up a bit) to make a second one to build a list of the delegations of others. The modification to the query was basically to switch from searching for delegates where user is the current user to searching for users where the delegate is the current user. Also, since this data is not editable (delegation is controlled by the person doing the delegating), I decided to format it as plain English rather than put it in a data table. The final product turned out like this:

function fetchList2() {
	var list = [];
	var today = new Date();
	var delegationGR = new GlideRecord('sys_user_delegate');
	delegationGR.addQuery('delegate', data.userID);
	delegationGR.orderBy('user.name');
	delegationGR.query();
	while (delegationGR.next()) {
		var stillActive = true;
		var endDate = '';
		if (delegationGR.getValue('ends')) {
			endDate = new GlideDate();
			endDate.setValue(delegationGR.getValue('ends'));
			endDate = endDate.getByFormat('M/d/yyyy');
			if (today.after(new Date(endDate))) {
				stillActive = false;
			} else {
				if (new Date(endDate).getFullYear() == 2100) {
					endDate = '';
				}
			}
		}
		if (stillActive) {
			var thisDelegation = {};
			var delegations = [];
			if (delegationGR.getValue('approvals') == 1) {
				delegations.push('Approvals');
			}
			if (delegationGR.getValue('assignments') == 1) {
				delegations.push('Assignments');
			}
			if (delegationGR.getValue('notifications') == 1) {
				delegations.push('CC on Notifications');
			}
			if (delegationGR.getValue('invitations') == 1) {
				delegations.push('Meeting Invitations');
			}
			if (delegations.length > 0) {
				thisDelegation.sys_id = delegationGR.getValue('sys_id');
				thisDelegation.id = delegationGR.getValue('user');
				thisDelegation.user = delegationGR.getDisplayValue('user');
				thisDelegation.ends = endDate;
				thisDelegation.delegations = '';
				var separator = '';
				for (var i=0; i<delegations.length; i++) {
					thisDelegation.delegations += separator;
					thisDelegation.delegations += delegations[i];
					if (delegations.length > 2) {
						separator = ', ';
						if (i == (delegations.length - 2)) {
							separator = ', and ';
						}
					} else {
						separator = ' and ';
					}
				}
				list.push(thisDelegation);
			}
		}
	}
	return list;
}

I also built this widget before I created my Dynamic Service Portal Breadcrumbs widget, so at the time I was always hesitant to leave the page without having a way back. I added that widget to the top of my test page, and then I converted all of the user names on the page to links out to the User Profile page for that person, which adds another nice little feature. The final HTML that formatted the delegations turned out like this:

  <div style="width: 100%; padding: 5px 50px;" ng-show="data.list2Items.length>0">
    <b>I am a Delegate for:</b>
    <div ng-repeat="item in c.data.list2Items track by item.id | orderBy: 'user'" style="padding: 5px;">
      <sn-avatar class="avatar-small-medium" primary="item.id" show-presence="true"/>
       
      <a href="?id=user_profile&table=sys_user&sys_id={{item.id}}" title="{{item.user}}">{{item.user}}</a>
      for {{item.delegations}}
      <span ng-show="item.ends"> until {{item.ends}}</span>
    </div>

All in all, putting this together was a fairly straightforward operation that added a nice new feature to the widget, and gave me a chance to do a little tidying up of some older code. Here’s what it ended up looking like in practice:

My Delegates widget with the addition of delegations of others

Much thanks to Fredrik Larsson for the work he did on his version of a Service Portal delegate widget, and for giving me the idea to make my own a little better. For those of you who like to play along at home, here is an Update Set with all of the latest parts and pieces.

More Fun with Form Fields

“Be not simply good, be good for something.”
Henry David Thoreau

One of the things that I love about incrementally building parts is that you can obtain value from the version that you have right now, yet still leave open the possibility of adding even more value in the future. When I first set out to attempt to construct a universal form field tag, I had no idea of the ways in which that would grow, but I was able to make use of it as it was at every step along the way. The other day I had a need for field that was only required if another field contained a certain value. When I went to set that up using my latest iteration of the form field tag, I realized that the current version of the code does not support that. That’s not really a problem, though; that’s just another opportunity to create a better version!

We already have an snh-required attribute, but in the current version, it simply adds an HTML required attribute to the input element. It would seem simple enough to just replace that with an ng-required attribute instead, and we would be good to go. However, we also have the required indicator to think about — that grey/red asterisk in front of the field label. That needs to go away when something changes and the field is no longer required. But let’s keep things simple and just focus on one thing at a time. In the current version, we use an internal boolean variable called required to control what gets included in the template that we are building. We can continue to use that, keeping it boolean for false, and then making it a string for anything else. The code to do that looks like this:

var required = false;
if (attrs.snhRequired && attrs.snhRequired.toLowerCase() != 'false') {
	if (attrs.snhRequired.toLowerCase() == 'true') {
		required = 'true';
	} else {
		required = attrs.snhRequired;
	}
}

You may wonder at this point why we make it a boolean for false and a string for true, but hopefully that will reveal itself when we look at the rest of the code. The next thing that we can look at is a little snippet of code that repeats itself a few times throughout the script as it is used when building the input element for a number of different field types:

... + (required?' ng-required="' + required + '"':'') + ...

This is a conditional based on the required variable, which will resolve to true for any non-empty string, but false for the boolean value of false. If the value of required is not false, then we use that same variable, which we now know is a string, to complete the ng-required attribute value for the input element. This will work for values of ‘true’ just as easily as for values that contain some kind of complex conditional statement. This was the easy part, and all of the logic was resolved within the code that generates the template.

The required indicator is another story entirely. Since some condition can toggle the element from required to not required, that same condition needs to apply to the required indicator as well. If the value of the snh-required attribute is anything other than simply ‘true’ or false, we will have to incorporate that logic in the indicator element to determine whether or not to show the indicator image. That code now looks like this:

htmlText += "          <span id=\"status." + name + "\"";
if (required) {
	if (required == 'true') {
		htmlText += " ng-class=\"" + model + refExtra + ">''?'snh-required-filled':'snh-required'\"";
	} else {
		htmlText += " ng-class=\"(" + required + ")?(" + model + refExtra + ">''?'snh-required-filled':'snh-required'):''\"";
	}
}
htmlText += "></span>\n";

As before, the first conditional is based on the required variable, and if it is false, then we don’t do anything at all. But in this case, we also have to check to see if it is equal to the string ‘true’, because if it is, we can just do what we were doing before to make this work. If it is not, then we have to include the required condition in the rendered ng-class attribute to toggle the indicator off and on at the same time that the field requirement is being toggled off and on. When the field is not required, the indicator should just go away, and when it is required, it should be there, and it should be red if the field is empty and grey if it has a value.

That’s it for the code changes. To test it, I brought up my old friend the, form field testing widget, and then altered my textarea example to look like this:

<snh-form-field
  snh-model="c.data.textarea"
  snh-name="textarea"
  snh-label="Text Area"
  snh-type="textarea"
  snh-required="c.data.select==2"
  maxlength="20"
  snh-help="This is where the field-level help is displayed. This field should be required if Option #2 is selected above."/>

That should make the textarea field required when Option #2 is selected on the field that is now above:

The textarea is required when Option #2 is selected

… and it should not be required when anything else is chosen:

The textarea is not required when Option #2 is not selected

With everything looking pretty solid, I was ready to generate another Update Set and call it good. Instead, I thought maybe I would just try a few more things, just to be sure. That’s when I discovered the problem.

It’s always something. I tinkered with the last name field to make it only required if the first name value was greater than spaces, and suddenly all of the form fields that followed within that same DIV disappeared.

Missing form fields

That’s not right. Not only is it not right, I have no idea why that is happening. If you put a greater than (‘>’) sign in the value of the snh-required attribute, anything that follows in the same DIV evaporates. I tried a number of things to fix it, and I found quite a few ways to work around it, but I was never able to actually solve the problem. I hate releasing something that has this kind of a bug in it, but since I don’t seem to posses the mental capacity required to remove the flaw at this particular moment in time, that’s what I am going to end up doing. There are work-arounds, though, so I don’t feel that bad about it. Here are some of the ones that worked for me:

  • Enclose the snh-form-field tag with a DIV. Since the problem only wipes out things within the same DIV, if it is the only thing in the DIV, the problem goes away. I actually tried to do that within the template itself, but that doesn’t work; the DIV has to be outside of the tag, not part of the code that is generated by the tag.
  • Encode the greater than sign. Actually, you have to double encode it, as &gt; will not work, but &amp;gt; does the trick. Not my idea of an intuitive solution, but it does work. And again, I tried to do that within the template itself, but that does nothing at all.
  • Don’t use a greater than sign. In my own example, I could have used snh-required=”c.data.firstName” and that would have worked just as well as snh-required=”c.data.firstName>””. Also, you can call a function that contains the greater than condition, which keeps it out of the attribute value as well.

Again, these are just work-arounds. In my mind, you shouldn’t have to do that. Hopefully, in some future version, you won’t. But if you want to play around with it the way that it is, here is the latest Update Set.

Update: There is a better (enhanced) version here (… but it still doesn’t address the > issue.)

Formatted Script Search Results, Corrected

“Never give in, never give in, never, never, never, never.”
Winston Churchill

For the most part, I really liked the way my formatted search result widget came out; however, the fact that I lost my results after following the links on the page was something that I just couldn’t accept. In my rush to get that out, I released a version with that obvious flaw, but I couldn’t just let that be the end of it; there had to be a way to make it remember its way back home without losing track of what was there before. There just had to be.

I tried a lot of things. They say that when you lose something, you always find it in the last place that you look. I always wondered why that was considered such profound wisdom, since it seemed quite obvious to me that once you found it, you would stop looking. Of course you always find it in the last place that you looked. When I finally came across a way to get the results that I wanted, I stopped looking. There may be a better way to achieve the same ends, but once I was able to link out to a page and come back to my original results, I was done. I’m not all that proud of the code, but it works, so I’m good.

The problem turned out to be this statement, which takes you to the next URL, which includes the search string parameter:

$location.search('search', c.data.searchFor);

This uses the AngularJS $location service, which is quite powerful, but apparently not quite powerful enough to leave a trail that you could follow back home again. I tried a number of variations to get things to work, but in the end I abandoned this whole approach and just went full old school. I replaced my ng-click with an onclick, and in my onclick function, I replaced that nice, simple one line of code with several others:

function findIt() {
	var url = window.location.pathname + window.location.search;
	if (url.indexOf('&search=') != -1) {
		url = url.substring(0, url.indexOf('&search='));
	}
	url += '&search=' + document.getElementById('searchFor').value;
	window.location.href = url;
}

Now I will be the first one to admit that this is quite a bit more code than that one simple line that I had before. First, I had to glue together the path and the search string to construct a relative URL, then I had to check to see if a search parameter was already present, and if so, clip it off of the end, then add my new search parameter to the search string, and then finally, set the current location to the newly constructed URL. Aesthetically, I prefer the original much, much better, but this older, brute force method has the advantage of actually working the way that I want, so it gets to be the winner.

I still kept my ng-click, but that was just to toggle on a new loading DIV to let the user know that their input was accepted and now we are working on getting them their results. That simple HTML addition turned out like this:

<div class="row" ng-show="c.data.loading">
  <div class="col-sm-12">
    <h4>
      <i class="fa fa-spinner fa-spin"></i>
      ${Wait for it ...}
    </h4>
  </div>
</div>

One other thing that I tinkered with in this iteration was the encoded query string in the Script Include. There is a particular table (sn_templated_snip_note_template) that kept throwing an error message related to security, so I decided to just filter that one out by name to keep that from happening. The new encoded query string now looks like this:

internal_typeCONTAINSscript^active=true^name!=sn_templated_snip_note_template

There might be a few other clean-up odds and ends included that I can’t quite recall right at the moment, but the major change was to finally get it to come back home again after drilling down into one the listed scripts. If you installed the previous version of this Update Set, I would definitely recommend that you replace it with this one.