Suitescript: Can't Get Result From Search - javascript

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?

Related

ServiceNow - query table and insert incident

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;

"The property or field 'Id' has not been initialized. It has not been requested..." when trying to access GUID of Library in SharePoint via JavaScript

I am trying to access the ID of Library using client-side object model in SharePoint 2013. But I am getting error as:
The property or field 'Id' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
Below is my code:
var context = SP.ClientContext.get_current();
var web = context.get_web();
var items = SP.ListOperation.Selection.getSelectedItems(context);
var currentLibrary = web.get_lists().getById(SP.ListOperation.Selection.getSelectedList(context));
context.load(currentLibrary, 'id'); // Tried with 'Id' but still throws error
console.log(currentLibrary);
console.log("currentLibrary.get_id = " + currentLibrary.get_id()); // THROWS ERROR!
What am I doing wrong here?
The error:
The property or field 'Id' has not been initialized. It has not been
requested…
occurs since List object has not been requested.
Use SP.ClientContext.executeQueryAsync method to execute the current pending request asynchronously on the server
A working example:
var context = SP.ClientContext.get_current();
var web = context.get_web();
var listId = SP.ListOperation.Selection.getSelectedList(context);
var list = web.get_lists().getById(listId);
context.load(list, 'Id'); //tell SharePoint to load List Id property
context.executeQueryAsync( //submit query to the server
function(){
console.log("ID:" + list.get_id()); //process result in success callback
},
function(sender,args){
console.log(args.get_message()); //handle error in error callback
}
);
my issue happened to be a silly one, the column I was returning was originally created with the name Requestor_DisplayName, and later changed to Employee_DisplayName so when using:
oListItem.get_item('Employee_DisplayName');
I got the >
"The property or field 'Id' has not been initialized. It has not been requested…" error
The issue had nothing to do with the SP.ClientContext.executeQueryAsync method itself...
When I changed the code to:
oListItem.get_item('Requestor_DisplayName');
It ran with out issue. You can use SP CAML Query Helper Online to inspect your your list and columns (as well as build CAML Queries) this is how I discovered my issue:
Hope this helps someone in the future!
Thanks.
SG.
Well back again editing this answer as today made another discovery about this error message similar in concept, I did not realize SharePoint will trim your column names after 32 Characters in length...
I got the exact same error message as before in the Developers Tool > debug console (IE f12) but about a different column of course.
"The property or field 'Operations_Approver1_Display_Name' has not been initialized. It has not been requested…"
I was left scratching my head after checking column names in list settings as I had in my JSOM, the column name was "Operations_Approver1_Display_Name" (Yes I was once a COBOL developer so I like long and Meaningful Names LOL)
oListItem.get_item('Operations_Approver1_Display_Name');
All seemed to check out, I thought "Well maybe I have a type in original column name and don't remeber fixing it" So of course I naturally opened up, SP CAML Query Helper Online (man I lobe this tool, yes the b was on purpose LOL).
This is how I discovered that SharePoint has a limit of 32 Characters for column names, just wanted to update this answer since it is highly ranked on search. As you can see in the screenshot below that the InternalName name of the column has been cut short by one character from its "Title" column name (Leave it to me to make this Name 33 characters long just 1 over the limit)
using Vadim answer:
var oItem ='';
function retrieveWebSite() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
var clientContext = new SP.ClientContext.get_current();
this.oWebsite = clientContext.get_web();
clientContext.load(this.oWebsite);
var lstObject = oWebsite.get_lists().getByTitle('Listname');
oItem = lstObject.getItemById(5);
clientContext.load(oItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
});
}
function onQuerySucceeded(sender, args) {
var look = oItem.get_item('LookupColumnName').get_lookupValue();
var title = oItem.get_item('Title');
var id = oItem.get_id();
alert("Loook up column value: "+look);
alert("Title column: "+title);
alert("Id column value: "+id);
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
you are looking for ids then do like this:-
var context = SP.ClientContext.get_current();
var web = context.get_web();
var items = SP.ListOperation.Selection.getSelectedItems(context);
for (var i = 0; i < items.length; i++) {
var id= items[i].id;
}
Thanks :)

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