Access document when I have the UID - xpages

I have a combobox on my form that loads client names from a view using the format "name | UID" - this displays the client name on the form but saves the UID in the field.
I now want to use the UID to lookup the name for the client and save it in a field on the XPage that is not visible using the following code:
// ignore when UID is null
if (getComponent("parentUID").getValue() == null)
return false;
var UID:string = getComponent("parentUID").getValue();
var doc:NotesDocument = database.getDocumentByUNID(UID);
// now set your fields
document1.setValue("nachname", doc.getItemValueString ("nachname"));
document1.setValue("vorname", doc.getItemValueString ("vorname"));
I do this in a simple action attached to a button. The next simple action is a Save.
The code crashes with the following error:
Error while executing JavaScript action expression
Script interpreter error, line=8, col=42: [TypeError] Exception occurred calling method NotesDatabase.getDocumentByUNID(java.lang.String) null
I have copied the parentUID to a field on the document and I am getting the correct UID and the document exists in the database?
Any ideas?
PS: I am adding this to an existing application and the current document is not a response document - cannot change that unfortunately :o(

OK, I have found my problem - XPages returned the UID but it included a leading space. When I concatenated the values I did the following: "name | UID" i.e. I added a leading and trailing space to the pipe symbol to make the code legible - this was causing the problems.

It looks like you are missing the get.Value() in your getComponent line
Try getComponent("parentUID").getValue() == null
My guess is that this is causing the code to run when the UID is null. This means that the code is running when it really is null, and your effort to check for that isn't working.
Thanks for checking that.
Can you put in a print() statement and ensure that you have a value in the var UID.
Another thing, please capitalize the word "String" since java classes are capitalized.

Related

Netsuite Invalid API usage. You must use getValue to return the value set with setValue

So I have an odd issue, When I create a new transaction and save, this error in the title gets thrown. But when I edit this transaction after it was created, the getText does not throw this error. Is there something I'm doing wrong or something special needed to getText on a create new record? Here is my code. This is for the afterSubmit method on my User Event Script for Vendor Bill screen. I just noticed getValue does work on create, does not produce this error, just don't understand why? Is this the correct way to get the value on create? To use getValue and getText cannot be used on create? Only for edit?
if (scriptContext.type == scriptContext.UserEventType.CREATE ||
scriptContext.type == scriptContext.UserEventType.EDIT) {
// get bill to index
var Bill = scriptContext.newRecord;
// fails on this call below on create but works on edit
var refno = Bill.getText({ fieldId: 'tranid' });
}
This behavior is described in the API documentation here.
In dynamic mode, you can use getText() without limitation but, in standard mode, limitations exist. In standard mode, you can use this method only in the following cases:
You can use getText() on any field where the script has already used setText().
If you are loading or copying a record, you can use getText on any field except those where the script has already changed the value by using setValue().
Apparently the newRecord object falls under the second criteria. At this point, the object only has values set. tranid will have a value with the transaction's internal ID, but it won't have the transaction name stored. To get the text, you will have to use record.load() to get the full record, or use search.lookupFields() to get just the transaction name.

XPages SSJS - Creating a Document in Another Database

I get the error "Exception occurred calling method NotesDatabase.createDocument() null" for the following:
var db:NotesDatabase = session.getDatabase("", viewScope.targetDb);
if (db != null) {
if(db.isOpen()){
}else{
db.open();
}
} else {
}
var doc:NotesDocument = db.createDocument();
Comments:
The database db is available and "open".
The user has enough rights in the targetDb to create documents.
What is wrong?
I changed db.isOpen to db.isOpen(), according to Paul Stephen Withers tips.
And now db.open() gives the error "Exception occurred calling method NotesDatabase.open() null" although that I can get, in viewScope variables, the server, FilePath, etc.
Change
var db:NotesDatabase = session.getDatabase("", viewScope.targetDb);
to
var db:NotesDatabase = session.getDatabase(currentDatabase.getServer(), viewScope.targetDb);
This works on the web as well as XPinC.
XPages isn't the same as formula, it doesn't like the empty string definition for the server name, which is contrary to the documentation which states (for the server parameter of NotesSession.getDatabase - javascript):]
The name of the server on which the database resides. Use null to
indicate the session's environment, for example, the current computer
Using null or "" gives error 500, it would appear.
The code from the question will work, if :
the if block is removed entirely
the viewScope.targetDb variable has a properly specified notes database file path, which exists on the same server as the current database
the current user has access to the target database ( by the ACL ), with the Create Database right
the target database has a Maximum Internet name and password above Reader as per #Paul
I suspect the cause is you're checking db.isOpen. You should check db.isOpen().
Worth bearing in mind is session.getDatabase(String, String) doesn't return null (unless you're using OpenNTF Domino API). It returns a Database object that is not open. So that if statement is irrelevant. Also best practice is to pass a server name to session.getDatabase() - you'll get a different outcome if the application is ever used in XPiNC with your current code.
Regardless of individuals' user access, "Maximum Internet name and password" on the Advanced tab of the ACL will override that. If maximum internet access is No Access, no one will be able to create documents. But I suspect that's not a factor here.
Pro Tip -- Get the Debug Toolbar and use that to print out messages to the XPage debug toolbar to see what is going on and if your viewScope variable is being set. Also, learn to use the try catch block to catch your exceptions and print out the error message to the debug toolbar. You will find your issue that way.
https://www.openntf.org/main.nsf/project.xsp?r=project/XPage%20Debug%20Toolbar

How to make #DbLookup in XPages verify the existence of a value in another database?

I have an XPage that is doing an #DbLookup with a user's input and trying to find that value in a view in a different database yet on the same server.
I have already verified that the view is in fact sorted by the first column and therefore #DbLookup friendly. The following code below appears in the server-side Javascript OnClick event handler for a button on my XPage.
My problem is that the an error occurs when trying to assign the value of lRep to the 'firstNameLabel'. lRep is returning a null value from the dbLookup even though the a record under the 'FirstName' field exists with the key 'P301993'. This dbLookup should be finding a returning a single 'FirstName' result. However, it is not.
var resultLabel = getComponent("firstNameLabel");
var dbName = new Array(#DbName()[0],"UKCSandbox.nsf");
var lRep = #DbLookup(dbName,"customerLookup","P301993","FirstName");
resultLabel.setValue(lRep.toString());
Unless your formatting was lost in copy and paste, your code has flaws. This is not Java, this is JavaScript. Line endings matter and functions don't act on the object, but return a value. Also #DbLookup returns a string when you have exactly one match, so checking for string doesn't help you.
Your code should look like that:
var ukcNumber = Registration.getItemValueString('UKCNumber').toUpperCase();
var resultLabel = getComponent("ukcNumberLabel");
var dbName = #DbName();
dbName[1] = "UKC\\UKCSandbox.nsf";
var lRep = #DbLookup(dbName,"customerLookup",ukcNumber,1);
resultLabel.setValue((lRep) ? "Success" : "Failed");
Does that work for you?
Update: 2 things to check:
does the lookup work in the same database using #DbName?
XPages have the same security constraints as Java agents. Do you have enough rights in the server document to do a 'get value from other database'? Default is No!
Have you tried making the dblookup work outside of xpages, i.e. with ScanEZ or in the Notes client?
Check your ukcNumber variable so it contains a value.
Edit
Check so the user has rights to do the lookup in the other database.
Also try a similar code on an old Notes Form and see if you get the same result.
Why can't you use keyword '[FAILSILENT]' in your #DBLookup call. It'll return "", if no entry matches with your key.
If you still have issues, use SSJS/java code to see where it's breaking up.

xpages validate database exist

I'm new to javascript and xpages here. I'm upgrading an old notes application to xpages. In my xpage I have a field, a save button, and an error messages control. The field is used to save the value of a nsf path/name that the user typed in to be used later on (e.g: //SAS/address.nsf). How do I validate if that path/database exist? The previous lotusscript is like this(it uses 2 field, one to get the server path, the other to get the db path. but for current xpage, the requirement is to use one field only):
svr$= source.FieldGetText("ServerPath")
dbsvr$= source.FieldGetText("DBPath")
Dim db1 As New NotesDatabase(svr$ , dbsvr$)
If Not db1.IsOpen Then
Messagebox "Cannot find the database."
Call source.GotoField("DBPath")
continue = False
Exit Sub
End If
In the field in the xpage, I've added a validateExpression validator. In the expression property, I compute the following SSJS:
var dbdir:NotesDbDirectory = session.getDbDirectory(null);
var db:NotesDatabase = dbdir.openDatabase(document1.getItemValue("dbpath"));
return db.isOpen();
In the validator's message property, I put "Cannot find database".
The error I'm keep getting is:
Expression is invalid.
Expression did not return a boolean value.
Any way to fix this? Is it the wrong use of validator? I've already test with local database and database on other server. None seems to work. All those database I tried I had access rights to them.
You should probably use sessionAsSigner in order to open the database as the signer of the XPage - instead of as anonymous (if you are not logged in). Also, consider adding try/catch around your dbdir.OpenDatabase() in order to catch errors opening a database with an invalid path.
Also, notice that the validateExpression validator must return a boolean true or false. In your case dbdir.openDatabase() will return null if the database can not be opened - which means that db.isOpen() will fail to work since it can not operate on a null object.
You could consider using the customValidator validator which must return an error message (and not a boolean true or false).
I hope this can help you complete the validation.
Use try/catch block for attempt to open database. If everything is OK, just return true in try block. Catch block will return false, what will handle most of the possible fails: wrong server, broken connection, invalid path, no access, and so on.
try {
// open database here and touch some property, doc count, for example
return true;
} catch (e) {
return false; // failed to open database
}

Unexpected ArgumentExecption when accesing a Field Value in a SPListItem

I have the following helper method that returns the value from a field.
public static string GetValueFrom(SPListItem item, string fieldName)
{
string value = string.Empty;
if (item.Fields.ContainsField(fieldName))
{
SPField field = item.Fields.GetField(fieldName);
if (item[field.InternalName] != null)
{
value = item[field.InternalName].ToString();
}
}
return value;
}
However for one Field (normal Choice Field) I am getting a ArgumentExecption on this line
if (item[field.InternalName] != null)
I am using
SPListItem item = list.GetItemById(itemId);
To get the item.
I cant find why I am getting the exception when I am checking to see if the field exists?
Any ideas as to why I am getting this Exception for only one field.
Update.
When debugging
The call to GetField() returns the correct field object.
Field.InternalName contains the correct Internal name of the field
If I try and access the value using item["internal name of the field"] it still throws and exception for only this one field.
Sometimes strange things happens and we do not have logical answer to those questions. Try by deleting the list and then creating the list again from scratch. DO NOT try to save it as template and DO NOT try to create the list from that template.
One possible reason of such type of ugly messages is that the security/permissions are not allowing to manipulate that field/column.
Another possible reason of such type of unwanted/unexpected messages is that when the field was created for the first time, its data type was different and later on it was changed to choice. Technically there should be no problem in doing so but sometimes we face odd behavior.
Have you tried debugging? Questions you should answer (because we can't):
Is field a valid value, or null, after the call to GetField()?
If field is not null, what does field.InternalName actually return?
If field.InternalName returns a valid value, can you access it by hard-coding that value in the indexer? i.e. item["fieldInternalName"]
Finding that information may help you solve the problem yourself, but if it doesn't add it to your post so the community has a better chance of helping you.
I do experienced this many a times. The reason for this is if you are logged-in as a non Admin Account(System Account) the default List View Lookup Threshold for the User is 8 for the lookup columns. i.e for the default view the user can access upto the 8 lookup fields only. If you change the List Throttling to >8 it will be resolved. But increasing this will degrade the performance.
Go to Central Admin >> Manage Web Applications >> Select the Web Application >> General Settings Dropdown >> Resource Throttling >> Change the "List View Lookup Threshold" to more than 8
Thanks,
-Codename "Santosh"

Resources