I have an xpage, where fields are created dynamically. By default, there are 3, but you can click a button to add as many as you like, naming convention "ObjectiveDetails1", "ObjectiveDetails2" and so on.
I am trying to handle blank fields... For example, there is content in fields 1 and 2, nothing in 3 and 4, but content in 5. What I want to do, is shift content from field 5 into the first available blank, in this case 3. Likewise, if there is content in fields 1, 2, 4, 5, I then need content in 4, to go into field 3, and content in 5 to go into field 4 etc. At the moment, I'm managing to shift content up 1 only.
So if fields 2, 3, 4 are blank but 5 has content, it only moves the content into 4, where-as I need it to move into field 2.
I hope I've explained this well enough..... Current code is a little messy....
for (var i = 1; i < viewScope.rows+1; i++) {
print("Starting Array.....");
if(applicationScope.get("BreakAllCode")==true){
break;
}
var objFieldName:string = "ObjectiveDetails" +i;
print ("Field Name: " + objFieldName);
var fieldValue = document1.getItemValueString(objFieldName);
print ("Field Value: " + fieldValue);
if (fieldValue =="" || fieldValue==null){
print("EMPTY");
// We now need to delete the 3 fields related to this objective
var updFieldName:string = "ObjectiveUpdates" +i;
var SAFieldName:string = "ObjectiveSelfAssessment" +i;
// Before we delete the fields, we need to check if the next field is blank
// and if not, copy its contents into this field.
for (var n =i+1; n < viewScope.rows+1; n++) {
if(applicationScope.get("BreakAllCode")==true){
break;
}
if(document1.hasItem("ObjectiveDetails" +n)){
print("Next field: " +"ObjectiveDetails" +n);
var nextFieldValue = document1.getItemValueString("ObjectiveDetails" +n);
if (!nextFieldValue =="" || !nextFieldValue==null){
// Now copy the content into the field
var nextFieldName:string = "ObjectiveDetails" +n;
var previousNo = n-1;
var previousFieldName:string = "ObjectiveDetails" +previousNo;
print ("Previous field: " + previousFieldName);
document1.replaceItemValue(previousFieldName,nextFieldValue);
// Now clear the content from next field
document1.replaceItemValue(nextFieldName,"");
}else{
// Do nothing
}
}else{
print("Last field");
}
}
// Remove items from the document
//document1.removeItem(objFieldName);
//document1.removeItem(updFieldName);
//document1.removeItem(SAFieldName);
// Remove fields from our arrays
//viewScope.fields.splice(i-1, 1);
//viewScope.fields2.splice(i-1, 1);
//viewScope.fields3.splice(i-1, 1);
// Update the row variable
//viewScope.rows--;
//document1.replaceItemValue("rows",viewScope.rows);
//document1.save();
// We now need to "re-index" the array so that the fields are numbered corectly
}else{
print("We have a value");
}
}
Update with beforePageLoad:
viewScope.rows = document1.getItemValueInteger("rows");
var rowCount:integer = viewScope.rows;
var newCount:integer = 0;
while(newCount<rowCount){
if (!viewScope.fields) {
viewScope.fields = [];
viewScope.fields2 = [];
viewScope.fields3 = [];
}
viewScope.fields.push("ObjectiveDetails" + (viewScope.fields.length + 1));
viewScope.fields2.push("ObjectiveUpdates" + (viewScope.fields2.length + 1));
viewScope.fields3.push("ObjectiveSelfAssessment" + (viewScope.fields3.length + 1));
newCount++;
}
This should be your core algorithm:
var writeIndex = 0;
for (var readIndex = 1; readIndex <= viewScope.rows; readIndex++) {
var value = document1.getItemValueString("ObjectiveDetails" + readIndex);
if (value) {
writeIndex++;
if (readIndex !== writeIndex) {
document1.removeItem("ObjectiveDetails" + readIndex);
document1.replaceItemValue("ObjectiveDetails" + writeIndex, value);
}
} else {
document1.removeItem("ObjectiveDetails" + readIndex);
}
}
viewScope.rows = writeIndex;
The code
deletes all empty fields,
renames fields to ObjectiveDetails1, ObjectiveDetails2, ObjectiveDetails3,... and
writes the resulting number of rows back to viewScope variable "rows".
If I understood your problem correctly, then this code should work (not tested):
// define variables
var i,j,nRows,values,value,allowContinue,fieldname;
// collect values from document fields
nRows=viewScope.rows;
values=[];
for (i=0;i<nRows;i++) {
values.push(document1.getItemValueString("ObjectiveDetails"+(i+1).toFixed(0)));
}
// fill empty values
for (i=0;i<nRows-1;i++) {
if (values[i]) continue;
allowContinue=false;
for (j=i+1;j<nRows;j++) {
if (value=values[j]) {
values[i]=value;
values[j]="";
allowContinue=true;
break;
}
}
if (!allowContinue) break;
}
// write back to document and remove empty fields on the end
for (i=0;i<nRows;i++) {
fieldname="ObjectiveDetails"+(i+1).toFixed(0);
if (value=values[i]) document1.replaceItemValue(fieldname,value);
else document1.removeItem(fieldname);
}
Related
In google docs one can easily add headings and link to them from inside of the document. But when the heading text changes, the link text does not change.
Is there a way to change that behavior or update the link text automatically?
I know it is about 1 1/2 years, but maybe this will help. I have had the exact same problem and wrote a function that will update all the links to the headings in a document. Since I could not find any built-in functions or add-ons, the only way was to script it.
Some things to consider:
This needs a current table of contents to work. If you don't have (or do not want) a TOC, you can insert one, run that function and delete it afterwards. Also, I have only tested it with a TOC that contains page numbers.
It will update ALL texts of links to headings in the document. However, links to everything else remain untouched.
Please use at your own risk (maybe try it out in a copy of your document). I have tested it, but the testing could have been more thorough. Also, this is my first in scripting Docs.
Paste this in the Script editor of your doc and run replaceHeadingLinks. Links that the script could not update (because they link to a heading that does not exist anymore) will be output in the console.
function replaceHeadingLinks() {
var curDoc = DocumentApp.getActiveDocument();
var links = getAllLinks_(curDoc.getBody());
var headings = getAllHeadings_(curDoc.getBody());
var deprecatedLinks = []; // holds all links to headings that do not exist anymore.
links.forEach(function(link) {
if(link.url.startsWith('#heading')) {
// get the new heading text
var newHeadingText = headings.get(link.url);
// if the link does not exist anymore, we cannot update it.
if(typeof newHeadingText !== "undefined") {
var newOffset = link.startOffset + newHeadingText.length - 1;
// delete the old text, insert new one and set link
link.element.deleteText(link.startOffset, link.endOffsetInclusive);
link.element.insertText(link.startOffset, newHeadingText);
link.element.setLinkUrl(link.startOffset, newOffset, link.url);
} else {
deprecatedLinks.push(link);
}
}
}
)
// error handling: show deprecated links:
if(deprecatedLinks.length > 0) {
Logger.log("Links we could not update:");
for(var i = 0; i < deprecatedLinks.length; i++) {
var link = deprecatedLinks[i];
var oldText = link.element.getText().substring(link.startOffset, link.endOffsetInclusive);
Logger.log("heading: " + link.url + " / description: " + oldText);
}
} else {
Logger.log("all links updated");
}
}
/**
* Get an array of all LinkUrls in the document. The function is
* recursive, and if no element is provided, it will default to
* the active document's Body element.
*
* #param {Element} element The document element to operate on.
* .
* #returns {Array} Array of objects, vis
* {element,
* startOffset,
* endOffsetInclusive,
* url}
*
* Credits: https://stackoverflow.com/questions/18727341/get-all-links-in-a-document/40730088
*/
function getAllLinks_(element) {
var links = [];
element = element || DocumentApp.getActiveDocument().getBody();
if (element.getType() === DocumentApp.ElementType.TEXT) {
var textObj = element.editAsText();
var text = element.getText();
var inUrl = false;
var curUrl = {};
for (var ch=0; ch < text.length; ch++) {
var url = textObj.getLinkUrl(ch);
if (url != null) {
if (!inUrl) {
// We are now!
inUrl = true;
curUrl = {};
curUrl.element = element;
curUrl.url = String( url ); // grab a copy
curUrl.startOffset = ch;
}
else {
curUrl.endOffsetInclusive = ch;
}
}
else {
if (inUrl) {
// Not any more, we're not.
inUrl = false;
links.push(curUrl); // add to links
curUrl = {};
}
}
}
// edge case: link is at the end of a paragraph
// check if object is empty
if(inUrl && (Object.keys(curUrl).length !== 0 || curUrl.constructor !== Object)) {
links.push(curUrl); // add to links
curUrl = {};
}
}
else {
// only traverse if the element is traversable
if(typeof element.getNumChildren !== "undefined") {
var numChildren = element.getNumChildren();
for (var i=0; i<numChildren; i++) {
// exclude Table of Contents
child = element.getChild(i);
if(child.getType() !== DocumentApp.ElementType.TABLE_OF_CONTENTS) {
links = links.concat(getAllLinks_(element.getChild(i)));
}
}
}
}
return links;
}
/**
* returns a map of all headings within an element. The map key
* is the heading ID, such as h.q1xuchg2smrk
*
* THIS REQUIRES A CURRENT TABLE OF CONTENTS IN THE DOCUMENT TO WORK PROPERLY.
*
* #param {Element} element The document element to operate on.
* .
* #returns {Map} Map with heading ID as key and the heading element as value.
*/
function getAllHeadings_(element) {
var headingsMap = new Map();
var p = element.findElement(DocumentApp.ElementType.TABLE_OF_CONTENTS).getElement();
if(p !== null) {
var toc = p.asTableOfContents();
for (var ti = 0; ti < toc.getNumChildren(); ti++) {
var itemToc = toc.getChild(ti).asParagraph().getChild(0).asText();
var itemText = itemToc.getText();
var itemUrl = itemToc.getLinkUrl(0);
var itemDesc = null;
// strip the line numbers if TOC contains line numbers
var itemText = itemText.match(/(.*)\t/)[1];
headingsMap.set(itemUrl,itemText);
}
}
return headingsMap;
}
I have a client script which is doing two things:
Calculate total weight of sales order on add of line
Copy tax code from custom field to native field
The script deploys correctly when adding lines in the UI from the sublist but when using the "add multiple" button and selecting and adding multiple lines at once, the script does not trigger. Here is the script as I have it written so far (I have 2 versions, one which is validateLine and one which is postSourcing).
Validate Line:
function calculateTotalWeight(type){
var lines = nlapiGetLineItemCount('item');
var totalWeight = 0 ;
for(var i=1; i< lines+1 ; i++){
var weight = nlapiGetLineItemValue('item', 'custcol_itemweight', i);
var quantity = nlapiGetLineItemValue('item', 'quantity', i);
var weightTimesQuantity = weight * quantity;
totalWeight = totalWeight + weightTimesQuantity ;
}
nlapiSetFieldValue('custbody_items_total_weight', totalWeight);
}
function validateLine(type){
var taxableCustomer = nlapiGetFieldValue('custbody_taxable');
if (taxableCustomer == 'T'){
var customTax = nlapiGetCurrentLineItemValue(type,'custcol_taxcode');
nlapiLogExecution('DEBUG', 'Custom Tax Value',customTax);
nlapiSetCurrentLineItemValue('item','taxcode',customTax,true,true);
}
return true;
}
postSourcing:
function calculateTotalWeight(type){
var lines = nlapiGetLineItemCount('item');
var totalWeight = 0 ;
for(var i=1; i< lines+1 ; i++){
var weight = nlapiGetLineItemValue('item', 'custcol_itemweight', i);
var quantity = nlapiGetLineItemValue('item', 'quantity', i);
var weightTimesQuantity = weight * quantity;
totalWeight = totalWeight + weightTimesQuantity ;
}
nlapiSetFieldValue('custbody_items_total_weight', totalWeight);
}
function postSourcing(type, name)
{
if(type === 'item' && name === 'item')
{
var custcol_taxcode = nlapiGetCurrentLineItemValue('item', 'custcol_taxcode');
var line = nlapiGetCurrentLineItemIndex(type);
{
nlapiSetCurrentLineItemValue('item', 'taxcode', custcol_taxcode);
}
}
}
How can I get this script to trigger with the add multiple button?
You’ll need to calculate the weight on the recalc event. The following is from a script that works as a scriptable cart/checkout script. It can be deployed in an eCommerce context or the UI context. (i.e. a deployed client script as opposed to a client script attached to a form)
Note:You should set up your tax codes so that they are assigned automatically. It is possible to script those but it's a fair pain to do.
the field custbody_sco_toggle is a checkbox field that keeps the script out of an infinite loop if your recalc scripts might change the order total.
var scriptableCart = (function(){
var cartScript = {};
var isUI = ('userinterface' == nlapiGetContext().getExecutionContext());
var isWeb = !isUI;
function tty(type, title, detail){
var haveWindow = typeof window != 'undefined';
if(isUI && haveWindow && window.console) window.console.log(title, detail);
else if(isWeb || !haveWindow) nlapiLogExecution(type, title, (detail || '') +' '+entranceId +' '+nlapiGetContext().getExecutionContext()); // this slows down the NS GUI
}
function calculateTotalWeight(type){...}
cartScript.recalc = function(type){
tty("DEBUG", "entered "+ type +" with toggle: "+ nlapiGetFieldValue('custbody_sco_toggle'));
if('F' == nlapiGetFieldValue('custbody_sco_toggle')){
try{
nlapiSetFieldValue('custbody_sco_toggle', 'T', false, true);
if(type == 'item'){
calculateTotalWeight(type);
}
}catch(e){
tty('ERROR', 'In recalc for '+ type, (e.message || e.toString()) + (e.getStackTrace ? (' \n \n' + e.getStackTrace().join(' \n')) : ''));
}finally{
nlapiSetFieldValue('custbody_sco_toggle', 'F');
}
}
};
return cartScript;
})();
I'm having some trouble getting the value of a column in a saved search via SuiteScript. Below is my code:
function KW_AutoCloseOldRA() {
var search = nlapiLoadSearch('transaction', 'customsearchopen_ras', null, null);
var columns = search.getColumns();
for (i = 0; i < columns.length; i++) {
nlapiLogExecution('DEBUG', 'Column #' + i + ' is ' + columns[i].getName());
}
var results = search.runSearch();
if (results) {
results.forEachResult(getResults);
}
}
function getResults(res) {
var message = res.getValue('tranid');
nlapiLogExecution('DEBUG', 'Result ' + message);
return true;
}
The search produces two columns, and the name of those columns output as expected in the DEBUG entry (internalid is column 0 and tranid is column 1). When looping through the results however, res.getValue('tranid') is always null. I can't seem to find what I'm doing wrong here.
Try getting the value using the columns object and its index like this:
function KW_AutoCloseOldRA() {
var search = nlapiLoadSearch('transaction', 'customsearchopen_ras', null, null);
var columns = search.getColumns();
for (i = 0; i < columns.length; i++) {
nlapiLogExecution('DEBUG', 'Column #' + i + ' is ' + columns[i].getName());
}
var results = search.runSearch();
if (results) {
results.forEachResult(getResults);
}
}
function getResults(res) {
var cols = res.getAllColumns();
var message = res.getValue(cols[1]);
nlapiLogExecution('DEBUG', 'Result ' + message);
return true;
}
I had this problem on my three sharepoint sites and i manage to resolve this problem by modifying CSS code (cf http://social.msdn.microsoft.com/Forums/en-US/sharepoint2010general/thread/64796605-bcbb-4a87-9d8d-9d609579577f/) on two of them.
I don't know why this doesn't work on my third one which has same updates, same CSS and same html code...
I tried several solutions such as adding indesign="true"(this can't be use because the lists got more than 75 columns). cf
http://www.codeproject.com/Articles/194254/Advanced-fixing-SharePoint-2010-large-lookup-dropd
The only solutions i found required javascript but i don't really want to use it...
If someone have another solution to propose, i would really appreciate.
EDIT:
Thanks to moontear i found something quite great.
I replace the beginning of the script by :
$(document).ready(function () {
$('.ms-lookuptypeintextbox').each(function(){
OverrideDropDownList($(this).attr('title'));
});
// Main Function
function OverrideDropDownList(columnName) {
...
By this way, i just have to include the script and don't care about what columns got problems...
This script seems to be quite great to solve this problem...
Thank you moontear for your comment
The original script come from : http://sharepointegg.blogspot.de/2010/10/fixing-sharepoint-2010-lookup-drop-down.html
$(document).ready(function () {
$('.ms-lookuptypeintextbox').each(function(){
OverrideDropDownList($(this).attr('title'));
});
// Main Function
function OverrideDropDownList(columnName) {
// Construct a drop down list object
var lookupDDL = new DropDownList(columnName);
// Do this only in complex mode...
if (lookupDDL.Type == "C") {
// Hide the text box and drop down arrow
lookupDDL.Obj.css('display', 'none');
lookupDDL.Obj.next("img").css('display', 'none');
// Construct the simple drop down field with change trigger
var tempDDLName = "tempDDLName_" + columnName;
if (lookupDDL.Obj.parent().find("select[ID='" + tempDDLName + "']").length == 0) {
lookupDDL.Obj.parent().append("<select name='" + tempDDLName + "' id='" + tempDDLName + "' title='" + tempDDLName + "'></select>");
lookupDDL.Obj.parent().find("select[ID='" + tempDDLName + "']").bind("change", function () {
updateOriginalField(columnName, tempDDLName);
});
}
// Get all the options
var splittedChoices = lookupDDL.Obj.attr('choices').split("|");
// get selected value
var hiddenVal = $('input[name=' + lookupDDL.Obj.attr("optHid") + ']').val();
if (hiddenVal == "0") {
hiddenVal = lookupDDL.Obj.attr("value")
}
// Replacing the drop down object with the simple drop down list
lookupDDL = new DropDownList(tempDDLName);
// Populate the drop down list
for (var i = 0; i < splittedChoices.length; i++) {
var optionVal = splittedChoices[i];
i++;
var optionId = splittedChoices[i];
var selected = (optionId == hiddenVal) ? " selected='selected'" : "";
lookupDDL.Obj.append("<option" + selected + " value='" + optionId + "'>" + optionVal + "</option>");
}
}
}
// method to update the original and hidden field.
function updateOriginalField(child, temp) {
var childSelect = new DropDownList(child);
var tempSelect = new DropDownList(temp);
// Set the text box
childSelect.Obj.attr("value", tempSelect.Obj.find("option:selected").val());
// Get Hidden ID
var hiddenId = childSelect.Obj.attr("optHid");
// Update the hidden variable
$('input[name=' + hiddenId + ']').val(tempSelect.Obj.find("option:selected").val());
}
// just to construct a drop down box object. Idea token from SPServces
function DropDownList(colName) {
// Simple - when they are less than 20 items
if ((this.Obj = $("select[Title='" + colName + "']")).html() != null) {
this.Type = "S";
// Compound - when they are more than 20 items
} else if ((this.Obj = $("input[Title='" + colName + "']")).html() != null) {
this.Type = "C";
// Multi-select: This will find the multi-select column control on English and most other languages sites where the Title looks like 'Column Name possible values'
} else if ((this.Obj = $("select[ID$='SelectCandidate'][Title^='" + colName + " ']")).html() != null) {
this.Type = "M";
// Multi-select: This will find the multi-select column control on a Russian site (and perhaps others) where the Title looks like '????????? ????????: Column Name'
} else if ((this.Obj = $("select[ID$='SelectCandidate'][Title$=': " + colName + "']")).html() != null) {
this.Type = "M";
} else
this.Type = null;
} // End of function dropdownCtl
});
The code in the solution above is great, but it has two major shortcomings:
1) Doesn't play nicely with Required Field Validators
2) Doesn't play nicely with Cascading Dropdowns via SPServices.
I've fixed these two problems at work, and put my solution here:
http://craigvsthemachine.blogspot.com/2013/04/fixing-complex-dropdown-bug-in.html
I was looking for a solution to the problem of getting a blank default when using a lookup in a field in Sharepoint. Kit Menke's solution to "Dropdown field - first item should be blank" question works perfectly for my first field with a lookup. But I can't make it work if have more that one field in the same list where I need to insert a blank for each lookup field (works only for the first field). I tried adding a new "Web Part" and applying the same code to the second field, but doesn't work. Any ideas? Thanks in advance
Follow-up to my answer here: Dropdown field - first item should be blank
Version 2.0 allows you to add the names of your dropdowns to dropdownNames in the MyCustomExecuteFunction function. As with the first one, this will work only with required single select lookup fields. Also, in order to edit the page again and update your Content Editor Web Part you may have to choose a value for your dropdowns otherwise you get the dreaded An unexpected error has occurred.. Good luck! :D
<script type="text/javascript">
function GetDropdownByTitle(title) {
var dropdowns = document.getElementsByTagName('select');
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns[i].title === title) {
return dropdowns[i];
}
}
return null;
}
function GetOKButtons() {
var inputs = document.getElementsByTagName('input');
var len = inputs.length;
var okButtons = [];
for (var i = 0; i < len; i++) {
if (inputs[i].type && inputs[i].type.toLowerCase() === 'button' &&
inputs[i].id && inputs[i].id.indexOf('diidIOSaveItem') >= 0) {
okButtons.push(inputs[i]);
}
}
return okButtons;
}
function AddValueToDropdown(oDropdown, text, value, optionnumber){
var options = oDropdown.options;
var option = document.createElement('OPTION');
option.appendChild(document.createTextNode(text));
option.setAttribute('value',value);
if (typeof(optionnumber) == 'number' && options[optionnumber]) {
oDropdown.insertBefore(option,options[optionnumber]);
}
else {
oDropdown.appendChild(option);
}
oDropdown.options.selectedIndex = 0;
}
function WrapClickEvent(element, newFunction) {
var clickFunc = element.onclick;
element.onclick = function(event){
if (newFunction()) {
clickFunc();
}
};
}
function MyCustomExecuteFunction() {
// **** ADD YOUR REQUIRED SINGLE SELECT FIELDS HERE ***
var dropdownNames = [
'Large Lookup Field',
'My Dropdown Field'
];
var dropdownElements = [];
for (var d = 0; d < dropdownNames.length; d++) {
// find the dropdown
var dropdown = GetDropdownByTitle(dropdownNames[d]);
// comment this IF block out if you don't want an error displayed
// when the dropdown can't be found
if (null === dropdown) {
alert('Unable to get dropdown named ' + dropdownNames[d]);
continue;
}
AddValueToDropdown(dropdown, '', '', 0);
// collect all of our dropdowns
dropdownElements.push(dropdown);
}
// add a custom validate function to the page
var funcValidate = function() {
var isValid = true;
var message = "";
for (var d = 0; d < dropdownElements.length; d++) {
if (0 === dropdownElements[d].selectedIndex) {
// require a selection other than the first item (our blank value)
if (isValid) {
isValid = false;
} else {
message += "\n"; // already had one error so we need another line
}
message += "Please choose a value for " + dropdownNames[d] + ".";
}
}
if (!isValid) {
alert(message);
}
return isValid;
};
var okButtons = GetOKButtons();
for (var b = 0; b < okButtons.length; b++) {
WrapClickEvent(okButtons[b], funcValidate);
}
}
_spBodyOnLoadFunctionNames.push("MyCustomExecuteFunction");
</script>
How about prepending a null option to the select menu of sharepoint.Like,
$('#idOfSelectMenu').prepend('<option value="" selected>(None)</option>');
I used this approach and append this code only in the NewForm.aspx because in EditForm.aspx it will override the selected option.