NotesXSPDocument with Agent runWithDocumentContext - xpages

when i try to pass an NotesXSPDocument to an agent with runWithDocumentContext to manipulate some fields, i never get the new values to the frontend fields. I have tried a fullrefresh and a partialrefresh. When i just print the field value i get the changes successfully.
Here is an example of the XPage
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:panel id="thePanel">
<xp:this.data>
<xp:dominoDocument var="document" formName="from"></xp:dominoDocument>
</xp:this.data>
<xp:button value="Label" id="button1">
<xp:eventHandler event="onclick" submit="true"
refreshMode="partial" refreshId="thePanel">
<xp:this.action><![CDATA[#{javascript:
var agent = database.getAgent("test");
agent.runWithDocumentContext( document.getDocument());
print( "Value-->" + document.getDocument().getItemValueString("InMemReturn"));}]]>
</xp:this.action>
</xp:eventHandler>
</xp:button>
<xp:br></xp:br>
<xp:br></xp:br>
<xp:inputText id="inputText1" value="#{document.InMemReturn}"></xp:inputText>
</xp:panel>
</xp:view>
here is the Agent
Option Public
Option Declare
Sub Initialize
Dim session As New NotesSession
Dim doc As NotesDocument
Set doc = session.Documentcontext
doc.Appenditemvalue "InMemReturn", CStr(Now)
End Sub
Have I missed something?

Manipulating documents in agents that bound to input fields are tricky. The XPages runtime isn't really aware what the agent is doing. Quite often you are actually better off converting an agent into a Java bean and call that one. It gives you the opportunity to clean up code and optimize performance. It also removes the performance penalty of loading the agent runtime for an operation.
"I want to reuse existing code" is often overrated here...
But you asked... so here we go. The documentation suggest you can use
agent.runWithDocumentContext(document.getDocument(true));
to ensure backend changes are applied. Try that and let us know how it went. I actually would take a slightly different approach and bind the input field to a view variable and write that one only back on the save event. Something like:
<xp:inputText id="inputText1" value="#{viewScope.InMemReturn}"></xp:inputText>
and in your SSJS:
var agent = database.getAgent("test");
var doc = document.getDocument(true);
agent.runWithDocumentContext(doc);
viewScope.InMemReturn = doc.getItemValueString("InMemReturn");
and in a querySave event:
document.getDocument().replaceItemValue("InMemReturn",viewScope.InMemReturn);
Let us know how it goes.

You dont save the document in the Agent
Call Doc.save(false,true,false)

Related

XPages: Rich Text Fields have summary to true when saved. Why and how to set the flag to false?

I have a document that was created using a copyallitems. That document has 2 body fields, and they both have the issummary flag to false.
As soon as I do a document1.save(), both rich text fields now have the flag set to true.
Any idea why the flag would be set to true by saving the document? These fields are not used in any views. I thought that rich text fields were not suppose get the summary flagged when saved.
Both rich text fields are set to store content as MIME...
Any clues on how to avoid the flag from being set, or how to remove the flag before saving (or after, or whatever) the document?
Running on Domino Release 9.0.1FP3 HF241
Here is sample code that recreates the problem, when adding more than 32Kb od text in the rich text field:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core"><xp:span style="font-weight:bold"></xp:span>
<xp:label id="label1" styleClass="h1" value="Test Issummary"></xp:label>
<xp:span style="font-weight:bold"></xp:span>
<xp:this.data>
<xp:dominoDocument computeWithForm="onsave" formName="fPage" var="document1"/>
</xp:this.data>
<xp:br></xp:br>
<xp:br></xp:br>
Subject:
 
<xp:inputText id="inputText1" value="#{document1.Subject}"
style="width:569.0px">
</xp:inputText>
<xp:br></xp:br>Status: 
 
<xp:inputText id="inputText2" defaultValue="Draft" value="#{document1.Status}"></xp:inputText>
<xp:br></xp:br>
<xp:br></xp:br>Body:<xp:br></xp:br>
<xp:inputRichText id="inputRichText1" style="width:100%"
value="#{document1.Body}" htmlConversionWarning="noWarning"
htmlFilter="identity" htmlFilterIn="identity">
</xp:inputRichText>
<xp:br></xp:br>
<xp:br></xp:br>
<xp:br></xp:br>
<xp:button value="Save" id="button1"
style="width:122.0px;height:29.0px">
<xp:eventHandler event="onclick" submit="true" refreshMode="complete">
<xp:this.action>
<xp:actionGroup>
<xp:saveDocument var="document1"></xp:saveDocument>
<xp:openPage name="/adminDrafts.xsp"></xp:openPage>
</xp:actionGroup>
</xp:this.action></xp:eventHandler></xp:button>
</xp:view>
Once saved, the document cannot be opened anymore as the infamous 32k error message is displayed.
If I save with less than 32K, the document is ok, but the rich text field has the issummary flag to yes... That is mostly the cause of my problem...
As you are using option computeWithForm make sure your form "fPage" contains your rich text field and is of type rich text. Otherwise it might get converted to a normal text field.
Use option computeWithForm only if you really need to as it an expensive operation.

Xpages: how to do partial refresh correctly

I am trying to get a partial refresh to ONLY refresh the chunk of the page that I need to refresh. I understand that if I do a normal partial refresh the entire JSF lifecycle gets called. I understand that a way around this is to set "Set partial execution mode" and to select the ID I want to refresh.
However I can't get it to work.
Below I have put in a very simple example. When I put a value in the execID then I do not see the refreshed form row. When I don't put the execID in I DO see the values of the form rows, but I believe I am not doing a partial refresh.
I am not understanding something. Any help would be very much appreiciated.
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core"
xmlns:xe="http://www.ibm.com/xsp/coreex">
<xe:formRow id="flyApplication" labelPosition="inherit"
label="Application(s)">
<xp:checkBoxGroup id="field1" layout="lineDirection"
styleClass="twoColumnCheckBoxGroup">
<xp:eventHandler event="onchange" submit="true"
refreshMode="partial" refreshId="pnlModules" execMode="partial" execId="pnlModules">
<xp:this.action><![CDATA[#{javascript:var v = getComponent("field1").getValue();
print (v);}]]></xp:this.action>
</xp:eventHandler>
<xp:selectItems>
<xp:this.value><![CDATA[#{javascript:["Yes","No"]}]]></xp:this.value>
</xp:selectItems>
</xp:checkBoxGroup>
</xe:formRow>
<xp:panel id="pnlModules">
<xe:formRow id="fr2" labelPosition="inherit"
label="Module(s)">
<xe:this.rendered><![CDATA[#{javascript:var v = getComponent("field1").getValue();
if (v == "Yes")
{return true}
else
{return false}}]]></xe:this.rendered>ddd<xp:checkBoxGroup id="field2" layout="lineDirection"
styleClass="fourColumnCheckBoxGroup">
<xp:this.value><![CDATA[#{javascript:"a"}]]></xp:this.value>
<xp:selectItem itemLabel="Values" itemValue="Values"></xp:selectItem>
</xp:checkBoxGroup>
</xe:formRow>
</xp:panel>
</xp:view>
Partial Execution requires that the control that triggers the event be inside the panel that is getting partially executed.
Keep in mind that partial refresh and partial execution are two different things but can be used together if you keep in mind what I said above.

Edit box in repeat control with default value does not update on delete

I have a Repeat control in which I have a edit box which has passed a default value.There is a Delete button to delete that row.
just for test I have used a computed field along with the edit box.Computed field is also passed the same value as edit box.Now both computed Field and Edit Box has same value,When I click on Delete button randomly,it gets delete but only computed field updates properly in repeat control wherever deleted,
In case of Edit box,it shows the last record disappears.
So the issue is, the value in edit box does not get update like computed field does.I have done the test by writing following code.
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.data>
<xp:dominoDocument var="document1" formName="testing">
</xp:dominoDocument>
</xp:this.data>
<xp:inputText id="inputText1" multipleSeparator=",">
<xp:this.defaultValue><![CDATA[#{javascript:var v:java.util.Vector = new java.util.Vector();
v.add('1');v.add('2');v.add('3');v.add('4');v.add('5');v.add('6');
return v;}]]></xp:this.defaultValue>
</xp:inputText>
<xp:br></xp:br>
<xp:repeat id="repeat1" rows="30" var="r" indexVar="i" first="0">
<xp:this.value><![CDATA[#{javascript:return getComponent("inputText1").getValue();}]]></xp:this.value>
<xp:br></xp:br>
<xp:div style="text-align:center">
<xp:label value="#{javascript:r}" id="label1"
style="text-align:center">
</xp:label>
<xp:button value="Delete" id="button1">
<xp:eventHandler event="onclick" submit="true"
refreshMode="complete">
<xp:this.action><![CDATA[#{javascript:var v:java.util.Vector = getComponent("inputText1").getValue();
if(v != null){
var sdtString = getComponent("inputText2").getValue();
if(v.contains(sdtString))
v.remove(sdtString);
};}]]></xp:this.action>
</xp:eventHandler>
</xp:button>
<xp:inputText id="inputText2">
<xp:this.defaultValue><![CDATA[#{javascript:getComponent("label1").getValue();}]]></xp:this.defaultValue>
</xp:inputText>
</xp:div>
<xp:br></xp:br>
</xp:repeat>
</xp:view>
This is the example code for testing to get the exact issue.
Edit 1: Real Scenario
We have an application to select multiple dates for a meeting and hence using the notes free time we mark multiple dates and then users are allowed to edit/delete the same in another window..Since, it was not possible/feasible enough to save all the fields in SSJS, we rather preferred binding each field with the data-source under the repeat control by using custom properties of the custom control (hope I am making some sense). Every fields is mapped as #chintan pointed out as follows:
dataSource[compositeData.to]
As described in the first part of the question the fields are not getting updated since we set them using default values. However, based on the suggestion we tried to set the field using the script library which does work well, however, might seem stupid but it messes the date field. When we set the value using the following:
var d:java.util.Date = new java.util.Date(compositeData.selectedDate);
getComponent("from").setValue(d);
It jumbles up the month, date and year field and shows a complete different value (the same code works well when put as the default value).
Hope this makes sense.
Any kind of solution can be appreciated.
inputText2's defaultValue gets executed only once at first page load. Then the XPage memorized that repeat 1 has inputText2 defaultValue 1, repeat 2 has inputText2 defaultValue 2 and so on.
Example: as you can see in print log, inputText2's defaultValue doesn't get calculated again after deleting row 3 and later row 1.
Turn it around and set inputText2's value in label1's value code:
<xp:label
value="#{javascript:getComponent('inputText2').setValue(r); r}"
id="label1"
style="text-align:center">
</xp:label>
then it will set inputText2's value properly. You don't need inputText2's defaultValue property anymore.
As an alternative you can define inputText2's value property and bind it to a row-specific data source or viewScope variable.
As you described in your "Edit 1 Real Scenario", you want to edit and delete pairs of dates. I created the following example. Instead of dates I just use strings for simplicity. Keep the dates in a viewScope variable and edit/delete them right there:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view
xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.beforePageLoad><![CDATA[#{javascript:viewScope.dates=[
{"from":"a", "to":"b"},
{"from":"c", "to":"d"},
{"from":"x", "to":"y"}];}]]></xp:this.beforePageLoad>
<xp:br />
<xp:repeat
id="repeat1"
rows="30"
var="r"
indexVar="i"
value="#{viewScope.dates}">
<xp:br></xp:br>
<xp:div>
<xp:button
value="Delete"
id="button1">
<xp:eventHandler
event="onclick"
submit="true"
refreshMode="complete">
<xp:this.action><![CDATA[#{javascript: viewScope.dates.remove(i);
}]]></xp:this.action>
</xp:eventHandler>
</xp:button>
<xp:inputText
id="inputText1"
value="#{r.from}">
</xp:inputText>
<xp:inputText
id="inputText2"
value="#{r.to}">
</xp:inputText>
<xp:button
value="Update"
id="button2">
<xp:eventHandler
event="onclick"
submit="true"
refreshMode="complete">
<xp:this.action><![CDATA[#{javascript: "";
}]]></xp:this.action>
</xp:eventHandler>
</xp:button>
</xp:div>
<xp:br></xp:br>
</xp:repeat>
<xp:text
escape="false"
id="computedField1">
<xp:this.value><![CDATA[#{javascript:
var length = viewScope.dates.length;
var result = "";
for (var i = 0; i < length; i++) {
result += viewScope.dates[i].from + " - " + viewScope.dates[i].to + "<br />";
}
result
}]]></xp:this.value>
</xp:text>
</xp:view>
Create the viewScope variable as an array of objects.

how to store and save correctly field values from repeat controls

I created a simple repeat control, having inside it 2 simple inputTexts. Outside this repeat control, there is an editable inputText3 ( binded to dataSource ). I'm using it to make some calculations inside the repeat control. The calculations are displayed correctly. I have 2 buttons, for newLine and delete/hideLine. For the moment, those 2 fields inside the repeat control are not binded to the datasource.
i have a button which save the doc., and list it inside a viewPanel, having the first column inputText3, clickable. I noticed that if I open the document ( in edit or read mode ) this editable field value is correctly displayed, but the fields inside the repeat control are all null, even if I add some values before using the save method.
I try also to create 2 fields inside the form ( / datasource ) and binding this inputTexts to them, but again the repeat control fields are empty.
<xp:repeat id="repeat1" var="varRepeat" indexVar="index">
<xp:this.value><![CDATA[#{javascript:parseInt(sessionScope.dField)
}]]></xp:this.value>
...
<xp:inputText id="inputText1"></xp:inputText>
<xp:inputText id="inputText2"></xp:inputText>
The editable field outside the repeat:
<xp:inputText id="number" value="#{docrepeat.valtotala}"
defaultValue="100">
</xp:inputText>
.
<xp:this.data>
<xp:dominoDocument var="docrepeat" formName="docrepeat"></xp:dominoDocument>
</xp:this.data>
I'm definitely missing something here, hope to reach to a functional solution.
Should I bind the 2 inputText using the var property of the repeat?
Or how can I achieve this?
repeat control code:
<xp:repeat id="repeat1" var="test" indexVar="index" rows="8">
<xp:this.value><![CDATA[#{javascript:parseInt(sessionScope.DField)
}]]></xp:this.value>
<xp:panel>
<xp:table >
<xp:tr>
<xp:td>
<xp:inputText id="inputText1">
<xp:eventHandler event="onchange"
submit="false">
<xp:this.script><![CDATA[try
{
var idx="view:_id1:inputText3";
var index=document.getElementById(idx).value;
var number="view:_id1:number";
var val=document.getElementById(number).value;
var sum = val;
for(var i=0;i<index;i++) {
var input1="view:_id1:repeat1:"+i+":inputText1"
var nr1=document.getElementById(input1).value;
sum-=nr1;
document.getElementById("view:_id1:repeat1:"+i+":inputText2").value = sum;
}
// calculating some %
document.getElementById("view:_id1:test").value = parseInt((sum*100)/val);
}
catch(e)
{
alert("not working");
}]]></xp:this.script>
</xp:eventHandler>
</xp:inputText>
<xp:inputText id="inputText2"></xp:inputText>
</xp:td>
</xp:tr>
</xp:table>
</xp:panel>
</xp:repeat>
My little scenario was described here: Xpages how to obtain/create this calculations module
I think your datasource inside the repeat is a view. You need to add a datasource of object data inside the repeat. The way to do this is to create a panel inside the repeat and give that panel a datasource as follows.
<xp:repeat id="repeat1" rows="30" value="#{view1}"
var="rowData">
<xp:panel>
<xp:dominoDocument var="objectData1"
formName="Item"
documentId="#{javascript:return rowData.getNoteID();}"
ignoreRequestParams="true" action="openDocument">
</xp:dominoDocument>
!!!put your stuff in the panel!!!
</xp:panel>
</xp:repeat>
So what is going on is the repeat grabs the datasource which is a view. So it will iterate through all of the entries in the view. But the view datasource does not know what to do with documents. So you create the objectData which will grab the noteID of that specific document and make that available to the repeat as a document(referenced by noteID). Making it available as a document will allow it to save values. You probably won't be able to use the value picker but just type in the field names and it will work.
Not sure I am completely understanding your problem. But you also need to save the datasource. So you could either put a save button in the panel to save that specific document or make the save button save all data sources. I prefer being able to save each document separately as it allows for applications that multiple can edit at the same time.

Strange behaviour with Typeahead - search string returned along with results

Apologies for the length. I'm having a play with fancy typeahead, and I ran across an issue that I can't explain. I've found a fix, but the fix doesn't make sense, so I'm wondering if anybody can look at my example and explain what is happening, and if it is a bug of some sort? I have stripped out most of the functionality to provide a bare bones example to demonstrate.
The scenario: I've got a text box, with fancy typeahead. Beside that, I have a button to append the newly found value into a second field. I use the second field to drive a repeat control showing all values chosen to date. Code below
The result: To test this, type 'ab' in the field, and select any choice, then click on the 'add' link. The repeat shows (, abcd) as you would expect. Test 2, repeat that process twice. The repeat will show (, abcd, ab, abcd). For some reason, the 'ab' is being added into the second field. The third test - type ab, choose a choice, add. Type 'bc', choose a choice, add. Type cd, but instead of choosing a choice, click the save button. The repeat then shows (, abcd, bc, abce, cd). I can't explain that at all.
The workaround: To get this to work properly, I can change the link's refresh type from partial to full. I have no idea why this makes it work, but it does. I don't know if I really want to do that, but I will if I have to. This is on a fairly complex form and I'd rather not do a full refresh unless I have to.
The code: Here's a cut-down xpage that demonstrates the problem:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core" xmlns:xc="http://www.ibm.com/xsp/custom">
<xp:this.data>
<xp:dominoDocument var="document1" formName="Test">
</xp:dominoDocument>
</xp:this.data>
<xp:panel id="mainPanel">
<xp:button value="Save" id="button1">
<xp:eventHandler event="onclick" submit="true"
refreshMode="complete">
<xp:this.action>
<xp:saveDocument var="document1"></xp:saveDocument>
</xp:this.action>
</xp:eventHandler>
</xp:button>
<xp:inputText id="objName1" value="#{document1.objName}">
<xp:typeAhead mode="full" minChars="2" valueMarkup="true"
var="searchValue" id="typeAhead1">
<xp:this.valueList><![CDATA[#{javascript: //In here I usually do some searching to find a result set, but for the purposes of a test, let's just do an array
var mapResults:java.util.TreeMap = new java.util.TreeMap();
mapResults.put("abcd", "abcd");
mapResults.put("abce", "abce");
mapResults.put("abcf", "abcf");
mapResults.put("abcg", "abcg");
mapResults.put("abch", "abch");
mapResults.put("abci", "abci");
//Now format the results
var returnList = "<ul>";
//All results are in the TreeMap and are sorted. Now add them to the output
var iter:Iterator = mapResults.entrySet().iterator();
while (iter.hasNext()) {
var nextEntry = iter.next();
returnList += "<li>" + nextEntry.getValue() +"</li>";
}
//Lastly, close off the UL tag and return
returnList += "</ul>";
return returnList;}]]></xp:this.valueList>
</xp:typeAhead>
</xp:inputText>
<xp:link escape="true" text="Add Another Object" id="link1">
<xp:eventHandler event="onclick" submit="true"
refreshMode="partial" id="eventHandler1" refreshId="mainPanel">
<xp:this.action><![CDATA[#{javascript:var currentVals = document1.getItemValueArray("addObjName");
//check for null value in first item in array - happens
//if we clear the array from the 'cross' buttons in the repeat
if (currentVals[0] == null) {
currentVals = new Array("");
}
//get the value from the object name field and whack it on the end
var newValue = getComponent("objName1").getValue();
//Put the value into a test field so we can prove that the value wasn't added below
document1.replaceItemValue("test1", newValue);
//Now add it to the field - where is the search text coming from?
currentVals.push(newValue);
document1.replaceItemValue("addObjName", currentVals);
getComponent("objName1").setValue("");
}]]></xp:this.action>
</xp:eventHandler>
</xp:link>
<xp:repeat id="repeat1" rows="30" var="rowData" indexVar="index"
repeatControls="false">
<xp:this.value><![CDATA[#{javascript:document1.getItemValueArray("addObjName")}]]></xp:this.value>
<xp:panel tagName="div">
<xp:link escape="true" id="link2" title="Remove from list">
<xp:image url="/vwicn081.gif" id="image1">
<xp:eventHandler event="onclick" submit="true"
refreshMode="partial" refreshId="mainPanel" id="eventHandler2">
<xp:this.action><![CDATA[#{javascript://remove an entry (string) from a list of strings (thanks to Mark Leusink)
Array.prototype.removeEntry = function( entry:String ) {
if ( #IsNotMember(entry, this)) {
return this;
}
var res = #Trim( #Replace(this, entry, "") );
return (typeof res == "string" ? (res.length==0 ? [] : [res]) : res);
}
var oldArray:Array = document1.getItemValueArray("addObjName");
var myArray = oldArray.removeEntry(oldArray[index]);
document1.replaceItemValue("addObjName", myArray);
}]]></xp:this.action>
</xp:eventHandler>
</xp:image>
</xp:link>
<xp:text escape="true" id="computedField1" value="#{javascript:rowData}">
</xp:text>
</xp:panel>
</xp:repeat>
<xp:text escape="true" id="computedField2">
<xp:this.value><![CDATA[#{javascript:"and here is what was added in the link:"}]]></xp:this.value>
</xp:text>
<xp:text escape="true" id="computedField3" value="#{document1.test1}">
</xp:text>
</xp:panel>
</xp:view>
Any takers? Is there a logical explanation for this, or should I just use my work-around and stop being a pedant?
UPDATE
Using the XPage above, I can also replicate the following scenario:
Step 1: Type 'abc' in the field, select 'abcd from the choices, click on the 'add' link. All good.
Step 2: Type 'ab' then wait, then type 'c', then choose 'abce'. Add again. This adds ab, abc, abce.
Step 3: Type ab then wait, then type c, then don't choose a choice, but hit Save instead. This adds ab, abc - even though the link has not been clicked to add the value to the second field.
Step 4: Type ab, wait, type c, choose 'abcf' and click Add. Only abcf is added this time.
I'm trying to reconcile this against Sven's answer below. Partial update works, so I know he's right. In step 2 above, I'm thinking that the typeahead code is executing twice, each time triggering the onClick event for the link, and lastly the onClick event for the link is running. Similar thing in Step 3 - the link isn't being clicked at all in that example, but the onClick code is still running. In step 4, after the save, typeahead is executing twice, but this time it isn't executing the onClick code.
Now I think I get it, even if I don't like it. As Sven says, The $$xspsubmitid identifies the element which submitted the data to the server - in the last submit action. So in this case it remembers the previous submit state and repeats that - so when you are doing it immediately after a plain save, you don't get any extra code, but when you are doing it after an event in the link, it submits the page in the same way that the link did - complete with onClick code.
There's probably a reason why doing this is a good thing, but my head hurts and the problem is solved! Thanks Sven!
It is your typeahead which updates the value of your field / your array. When typing a second or more characters in the input box, the current data in your input box is sent to the server and this updates the value in the document. When clicking onto the link, the value is added again.
EDIT:
You can fix this by changing the mode of the typeahead to "partial"
EDIT 2:
The difference between the refresh modes of a typeahed is how the data are sent to the server: In case of a full refresh, the data are sent with a POST request, in case of a partial refresh, the data are sent as a GET request.
Let's have a look at the different HTTP requests:
1.) Partial mode
2.) Full mode
As you can see in the two picutrures, in full mode there are more "fields" sent to the server. The interessting one is the $$xspsubmitid: Currently it is empty. But as soon we click the link, the field is filled with the id of the link:
The $$xspsubmitid identifies the element which submitted the data to the server. In this case the link, and the server processes the code of the link.
And now comes the problem with the typeahead in full mode:
As you can see, the $$xspsubmitid is always added to the POST request, and that's why the server executes the click event of the link for each typeahead request.

Resources