The number one mistake that people make within the ServiceNow Service Portal is cloning and customizing OOB widgets just to add some functionality. This is a bad idea on many different levels:
- Clones will jot be updated during an upgrade
- Functionality will be lost if cloned into scoped application
- Increased your development cost
- Increased your testing cost
$rootScope.$on
The OOB widgets broadcast events at almost every stage. This allows us to make our own custom widgets that listen for those events and add some functionality to the OOB widget without having to clone or modify the OOB widget. For our example we are going to add a redirect functionality to the OOB form widget.
Form Widget Requirements
Let’s say a customer wants the form widget to redirect to a specific page once after the form has been submitted. The page is dependent on the table that the form is utilizing.
The first thing we need to do is identify the event that is broadcasted by the OOB widget when the form is submitted. We do this by identifying the function that is called on click for the submit button. Then we look for $broadcast or $emit.
function constructResponseHandler(response) { return function() { $rootScope.$broadcast("sp.form.submitted", {sys_id: (response.isInsert) ? response.sys_id : $scope.data.sys_id})
We have identified that the event name is sp.form.submitted now we can start developing our custom widget.
Custom Wiget
The first thing we need to do is import $rootScope and $location in our client script. Then we add our logic to listen for the submit event.
$rootScop.$on('sp.form.submitted', function(res){
//redirect logic
$location.$$search = { ...page and parameters here... };
$location.search($location.$$search);
});
Reusability
We can make this widget reusable by adding widget options to all different redirect logic to be driven via widget instance options which will increase scalability for this custom widget.
Conclusion
We have added custom functionality to the OOB wiget while at the same time not modifying the code for the OOB widget. This allows us to meet the customers needs while at the same time maintaining ServiceNow best practices.