ServiceNow - query table and insert incident - javascript

I m trying to implement a script that queries a table and checks for certain criteria.
If it is true then it will insert an incident.
I m not sure where this is going wrong, I am guessing it is the while loop.
I m new to scripting in servicenow if someone could assist.
Code is below
var kc = new GlideRecord('cmdb_ci_web_site');
kc.addQuery('owned_by', '=',
current.u_caller_id.sys_id).addOrCondition('u_secondary_site_owner', '=', current.user.sys_id);
kc.query();
While (kc.next())
{
var inc = new GlideRecord('incident');
inc.initialize();
inc.short_description ='Assign New User to PSO or SSO';
inc.u_category = 'KCCC';
inc.current.u_caller_id.sys_id.setDisplayValue();
inc.to_be_encrypted ='Assign New User to PSO or SSO';
inc.impact ='3';
inc.urgency = '3';
inc.insert();
}

This line is suspicious inc.current.u_caller_id.sys_id.setDisplayValue(); I would guess inc.current is undefined.
If that's still not working: I've had problems chaining the OR condition directly. Try setting a new variable for your OR condition:
var kc = new GlideRecord('cmdb_ci_web_site');
var kcOrCondition = kc.addQuery('owned_by', '=', current.u_caller_id.sys_id);
kcOrCondition.addOrCondition('u_secondary_site_owner', '=', current.user.sys_id);
kc.query();

Not really sure as to what you are trying to achieve with this line: inc.current.u_caller_id.sys_id.setDisplayValue();. Since caller_id is a reference field, you dont have to dot walk to it's sys_id to get the value, the system will automatically pick up the sys_id by default.
You can make changes to your script as:
var kc = new GlideRecord('cmdb_ci_web_site');
kc.addEncodedQuery('owned_by='+current.u_caller_id+'^OR u_secondary_site_owner='+current.user);
kc.query();
while (kc.next())
{
var inc = new GlideRecord('incident');
inc.initialize();
inc.setValue("short_description","Assign New User to PSO or SSO");
inc.setValue("u_category", "KCCC");
inc.setValue("to_be_encrypted", "Assign New User to PSO or SSO");
//inc.setValue(relevant_incident_field, current.u_caller_id);
inc.setValue("impact", "3");
inc.setValue("urgency", "3");
inc.insert();
}

Try changing this statement:
inc.current.u_caller_id.sys_id.setDisplayValue();
if you want to set a specific field in inc using the current value try this:
inc.somefieldininc = current.u_caller_id.sys_id;

Related

Suitescript: Can't Get Result From Search

The following is the script that I write for writing back "ship from location" information to Item Fulfillment for a certain customer. But it's not working.
Anyone see a syntax error, know what I might be missing, or what I can test for?
case "2946":
var warehousecode = WH_Code_Lookup(customer , location);
itemfulfillment.setFieldValue('custbody_warehouse_code', warehousecode);// set warehouse code
// Set Ship from location
var columns = [];
columns[0] = new nlobjSearchColumn('address1');
columns[1] = new nlobjSearchColumn('address2');
columns[2] = new nlobjSearchColumn('city');
columns[3] = new nlobjSearchColumn('state');
columns[4] = new nlobjSearchColumn('country');
columns[5] = new nlobjSearchColumn('zip');
var search = nlapiSearchRecord('location', null, new nlobjSearchFilter('internalid', null, 'is', invCheckFlag), columns);
itemfulfillment.setFieldValue('custbodyship_from_address1', search[0].getValue('address1'));
itemfulfillment.setFieldValue('custbodyship_from_address2', search[0].getValue('address2'));
itemfulfillment.setFieldValue('custbodyship_from_city', search[0].getValue('city'));
itemfulfillment.setFieldValue('custbodyship_from_country', search[0].getValue('country'));
itemfulfillment.setFieldValue('custbodyship_from_state', search[0].getValue('state'));
itemfulfillment.setFieldValue('custbodyship_from_postal_code', search[0].getValue('zip'));
if(location == 6){
itemfulfillment.setFieldValue('thirdpartyacctups',edi_customer_search[0].getValue('custrecord_2nd_3rd_pty_ups'));
itemfulfillment.setFieldValue('thirdpartyzipcodeups',edi_customer_search[0].getValue('custrecord_2nd_3rd_pty_ups_zip'));
itemfulfillment.setFieldValue('thirdpartytypeups','BILLTHIRDPARTY');
}
break;
You stated that the code doesn't work. Is there a specific error, as someone asked? Does the search bring back results or is it an issue in the search itself? Did you add any debug code in your script to see if you can pinpoint where the issue may be?

Assign variable value as variable name

the problem is i want to shorten my code by calling a variable using other variable's value
long working version:
var russia = new Array('15')
var switzerland = new Array('5')
$('.country').mouseover(function(){
switch(this.id){
case 'russia':
active_country_lift(this.id,russia[0])
break
case 'switzerland':
active_country_lift(this.id,switzerland[0])
break
}
})
it will get the id of mouseovered then check if it matched one of the variable by using switch
what i want to obtain is something like this:
var russia = new Array('15')
var switzerland = new Array('5')
$('.country').mouseover(function(){
active_country_lift(this.id,this.id[0])
})
of course the above code wouldn't work but is there a workaround for this?
UPDATE: Arun's answer worked and ill accept it soon and as for the comments requesting for the full code, here's a chunk of it after i applied Arun's
var countries = {
russia: ['-15px'],
switzerland: ['-5px']
}
$('.country_inactive').mouseover(function(){
active_country_lift(this.id, countries[this.id][0])
})
function active_country_lift(country, country_top){
if(!$('#'+country+'_active').hasClass('active')){
$('#'+country+'_active').stop().fadeIn(100).animate({
'top' : country_top
}, 200)
$('#'+country).stop().fadeOut(100)
}
}
it will be used for a world map, feel free to make any suggestions for making it more dynamic
You can store the country info in an object like a key value pair, then use bracket notation to access it dynamically
var countries = {
russia: new Array('-15px'),
switzerland: new Array('-5px')
}
$('.country').mouseover(function() {
active_country_lift(this.id, countries[this.id][0])
})
If you don't have multiple values then
var countries = {
russia: '-15px',
switzerland: '-5px'
}
$('.country').mouseover(function() {
active_country_lift(this.id, countries[this.id])
})
try using eval() function
var russia = new Array('-15px')
var switzerland = new Array('-5px')
$('.country').mouseover(function(){
active_country_lift(this.id,eval(this.id)[0])
})

doPost "unexpected error encountered" Web Form when submitting

I'm stuck on this web form after submitting. The below code worked in a previous web form I created with the help of Serge and a few others here some time ago. I'm attempting to re-purpose the code to make a PTO request web form. Right now, when submitting it spits out a "unexpected error encountered error and I'm lost on attempting to locate the issue. I'm thinking it may be how I've added panels together and their relationship? This is a work in progress, so i know clickhandlers will be added to provide response after submit etc. At the moment I'm looking to make sure it's passing entries in form to the spreadsheet. Thanks for any assistance.
//Setting the spreadshet ID and style of the form
var submissionSSkey = 'PUT YOUR KEY HERE'
var PanelStyle = {'background':'#c0d6e4','padding':'40px','borderStyle':'ridge','borderWidth':'15PX','borderColor':'#31698a'}
// Script-as-app template.
function doGet(e) {
//Creating the Appplication
var app = UiApp.createApplication();
//Creating panels to house the web form, instructional text, data pickers and setting style
var vertPanel = app.createVerticalPanel().setTitle('XYX Company PTO Request Form').setStyleAttributes(PanelStyle).setPixelSize(350,250);
var mainPanel = app.createFormPanel().setPixelSize(350,150);
var grid = app.createGrid(4,4).setId('ptogrid');
var ptoStart = app.createDateBox().setWidth('200').setName('ptoStartDate');
var ptoEnd = app.createDateBox().setWidth('200').setName('ptoEndDate');
var submitButton = app.createSubmitButton('<B>Submit</B>');
//Assigning widgets to the grid for positioning
grid.setText(1, 0, 'PTO Start Date')
.setWidget(1, 1, ptoStart)
.setText(2, 0, "PTO End Date")
.setWidget(2, 1, ptoEnd)
.setText(3, 0, '')
.setWidget(3, 1, submitButton)
//Instructions for completion of the PTO form by users.
vertPanel.add(app.createHTML("<b>PTO Request Form</b>"));
vertPanel.add(mainPanel);
vertPanel.add(app.createHTML("<br><b>Instructions:</b></br>" +
"<p>Select the starting date and the ending date for your PTO request. "+
"If you are taking a single day of PTO enter the starting and ending date as the same date. "+
"Click Submit once you've enter the dates. A request will be sent to your manager for reivew / approval.</p>"));
//Grabbing active users session information in order to look up user group assignment and manager
var employee = Session.getActiveUser().getEmail();
//Uses the UserManager class to get info by passing in the getActive user from base class
var userFirst = UserManager.getUser(Session.getActiveUser()).getGivenName();
var userLast = UserManager.getUser(Session.getActiveUser()).getFamilyName();
var wholeName = userFirst +" "+ userLast;
mainPanel.add(grid);
app.add(vertPanel);
return app;
}
function doPost(e) {
var app = UiApp.getActiveApplication();
var ptoStart = e.parameter.ptoStartDate;
var ptoEnd = e.parameter.ptoEndDate;
//var wholeName = e.parameter;
var timeStamp = new Date();
//Access spreadsheet store values
var sheet = SpreadsheetApp.openById(submissionSSkey).getSheetByName('PTO Requests');
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 11).setValues([[timeStamp,ptoStart,ptoEnd]]);
app.close();
return app;
}
I'm pretty sure the error comes from the spreadsheet ID, the sheet name or the range definition, please double check these parameters and see if it solves the issue.
I checked on my account with wrong values and it generated the same issue you have, it works as expected with correct values.
Edit: your comment seems to confirm that...( didn't see it when I answered...)
Note: the error was easy to find by looking at the execution transcript in the script editor UI, it would even give you the line of code where the error occured.

Javascript API - Error 401 - Missing api_id when clicking on SearchBox

I have two symptoms that make me think there's something wrong with my Nokia appId/token. One is that when I try to use the searchbox, I get a javascript error "Error 401 - Missing api_id". The second is when I go to developer.here.com and to My Apps, and look at the hit history of my app, I see zero hits. What am I doing wrong?
nokia.Settings.set("appId", "[My ID]");
nokia.Settings.set("authenticationToken", "[MY TOKEN]");
var my_lat = 41.88
var my_lon = -87.63
map = new nokia.maps.map.Display(document.getElementById('mapcanvas'), {
'components': [
// Behavior collection
new nokia.maps.map.component.Behavior(),
new nokia.maps.map.component.ZoomBar(),
new nokia.maps.map.component.Overview(),
new nokia.maps.map.component.TypeSelector(),
new nokia.maps.map.component.ScaleBar()
],
'zoomLevel': 11, // Zoom level for the map
'center': [my_lat, my_lon] // Center coordinates
});
// Initialize search box:
var searchBox = new nokia.places.widgets.SearchBox ({
targetNode: 'searchbox',
searchCenter: function () {
return {
latitude: my_lat,
longitude: my_lon
}
},
onResults: function (data) {
renderResults (data);
}
});
// Handle the results of the search. This callback function
// receives the raw places data as an array. For each element
// in this array, it creates an HTML list element and fills
// it with the name of the place:
function renderResults (data) {
var previewList = document.getElementById ('results');
previewList.innerHTML = '';
var results = data.results.items;
for (var i = 0, l = results.length; i < l; i++) {
var result = results[i];
var resultLi = document.createElement ('li');
resultLi.innerHTML = result.title;
previewList.appendChild (resultLi);
}
}
The problem was how I was getting the javascript lib.
This is what worked. Note the "with=maps,places".
<script type="text/javascript" src="http://api.maps.nokia.com/2.2.4/jsl.js?with=maps,places"></script>
Here's what did not work
<script type="text/javascript" src="http://api.maps.nokia.com/2.2.4/jsl.js"></script>
<script type="text/javascript" src="http://api.maps.nokia.com/2.2.4/jsl.js?with=places"></script>
Your code looks correct - my assumption would be that the appId and token you are using are not valid.
Firstly to prove this is the case start with the code behind the Places Widget example. Copy the code to your PC or local server and see if you can get a local copy working for you - if you type the word Airport into the search box you should get suggestions appearing after the first three letters, and markers on the map once you click search.
Now try replacing the app id and token wih blanks:
nokia.Settings.set("appId", "");
nokia.Settings.set("authenticationToken", "");
The application should no longer work. If this is also the case when you enter your appId and token then it looks like you have incorrectly copied them, used the app name by mistake (or something is up with the back-end).
The most comprehensive guide to creating a new appId and token can be found here - I would follow it from scratch and create a new one if necessary. When logged in and you click on Manage Apps the appId and token can be found in the boxes on the right. Double click on the box to select all and ensure that you don't inadvertently miss the final character which may not quite fit in the box.
Go back to your working demo example and replace the demo appId and token with the ones associated with your account. Hopefully it should now work for you.

Populate SUM of column from accessdb into textbox using javascript

I have a webpage with a few textboxes; and an access database with columns that contain numeric data, dates and user id's.
I need help to SUM a column WHERE the date is >= 1/1/2013.
Lets just say i cant use server side scripting with my current setup. I need this done only by JS or jquery.
Here is the code i came up with to retrieve the sum. but the textbox is returned with this value "[object]".
Also, im not sure how to write the "WHERE" condition.
I'm sure its something simple im missing. any help will be greatly appreciated!!
function retrieve_records() {
var adoconn = new ActiveXobject("ADODB.Connection");
var adoRS = new ActiveXobject("ADODB.Recordset");
adoconn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='database.mdb'");
adoRS.Open("Select SUM(database_column_name) As Total FROM tablename", adoconn, 1, 3);
textbox1.value = adoRS;
adoRS.close();
adoconn.close();
}
Thanks!
Marvin.
This is cobbled to gether from a knowledge of ADO and Access rather than Javascript.
var cmd = new ActiveXObject("ADODB.Command");
cmd.ActiveConnection = adoconn;
var strSQL = "Select SUM(database_column_name) As Total FROM tablename WHERE aDate=?";
cmd.CommandText = strSQL;
var param = cmd.CreateParameter("adate", 7, 1,, "2013/12/31");
cmd.Parameters.Append(param);
var adoRS = cmd.Execute();
textbox1.value = adoRS.Fields(0)
Fields(0) because you only have one field, Fields('Total') should also work. The date is a string above, it should work with Access, but you might like to use a proper date.

Categories

Resources