Switch between Edit and Read-Only mode on web form

A question on Stack Overflow made me remember some code I wrote a few years ago. It allows you switch a form between regular edit mode and read mode, without having to reload the page. It works just like you are used to in the Notes client. So I thought I would post it here on my blog as well.

It is not very complicated. I am using jQuery, but you can of course use plain Javascript if you like. What the code does is to locate all INPUT fields you want to make read-only. It then creates a regular DIV element and set the content of it to the value of the INPUT field. The id and a couple of other attributes are also copied over, then the new DIV is inserted in front of the INPUT field. Finally the INPUT field is deleted.

To make the DIV editable again, the same process is done in reverse.

Below is the jQuery code to make all elements with the data-attribute dominofield read-only. I am using this data-attribute to map input fields to fields in a Domino database. It makes it very easy to create HTML forms and submit them to a Domino database, with one generic agent that will process the Ajax call. The field names and values will be provided in the JSON payload, and the Domino document can then be created or updated and the fields populated with the proper values.

  // Get all input fields used for Domino
  var inputs = $('[data-dominofield]');
  // Process each field
  inputs.each(function() {
    // Build new DIV element
    var input = $(this);
    var div = '<div class="fieldReadOnly" ';
    div += 'data-dominofield="' + input.data('dominofield') + '" ';
    div += 'id="' + input.attr('id') + '">';
    div += input.val() + '</div>';
    // Insert ther new div element in front of input field
    input.before(div);
    // Remove input field
    input.remove();
  });

I also created a fiddle where you can test it yourself.

If you are using Bootstrap, you can also use the readonly attribute and the class .form-control-plaintext to get the same result. This is documented here.

 

0 Comments

Free Code – Wrapper for searches in NetSuite

About a year ago I wrote a SuiteScript 1.0 class as a wrapper around the search functionality in NetSuite. I have updated the code over time, and I want to share the latest version. Among the new features is support for formulas and search expressions. The class should be backwards compatible with the original version, but in addition you can also pass an object to most functions, instead of passing separate parameters. This makes it more flexible and allows me to add more functionality.

Enjoy!

 

/**
 * Encapsulate NetSuite search functionality in an easy-to-use object for SuiteScript 1.0.
 *  
 * Version    Date            Author           Remarks
 * 1.0        11 Nov 2016     kmartinsson      Initial version
 * 1.5        06 Jul 2017     kmartinsson      Added record type to constructor
 * 2.0        23 Aug 2017     kmartinsson      Added Search2 function, with support for objects and adding multiple columns/filters
 * 2.0.1      01 Sep 2017     kmartinsson      Bug-fixes
 * 2.0.2      01 Sep 2017     kmartinsson      Fixed issue with join not being null, added hasOwnProperty check 
 * 3.0        20 Nov 2017     kmartinsson      Removed v1.x code stream, renamed Search2 to Search
 * 3.0.1      06 Dec 2017     kmartinsson      Added JSDoc style comments, updated comments to new JSDoc style
 * 3.0.2      28 Feb 2018     kmartinsson      Fixed bug in sort key which prevented proper sorting. Added alternative keys.
 * 3.0.3      15 Jul 2018     kmartinsson      Added filter expression support
 * 3.0.4      01 Oct 2018     kmartinsson      Added method removeColumns() for use on (external) saved search
 * 
 */

/**
 * Search object
 * @constructor
 * @param {string} recordtype - Optional NetSuite recordtype (internalid)
 */
function Search(recordtype) {
    this.recordType = null;
    this.columns = [];
    this.filters = [];
    this.filterExpressions = [];
    // Set internal id of saved search to null
    this.internalId = null;
    this.noSavedColumns = false;
    // If record type/ID is supplied, set it now, otherwise default to null
    if (recordtype != null && recordtype != "") {
        this.recordType = recordtype;
    }

    // Helper function to verify the value is empty or null
    function isNullOrEmpty(val) {
        if (val == null || val == '' || val ==[] || val == {}) {
            return true;
        } else {
            return false;
        }
    }

    
    /**
     * Remove all columns included in the search
     * @param none
     * 
     */
    this.removeColumns = function() {
        this.noSavedColumns = true;
    }

    /**
     * Add a column to include in the search
     * @param {object}|{string} column - Object specifying a column to return or string containing columnId
     * @param {string} join - Joined record (internalid) (optional)
     * @param {boolean}|{string} sorting - Sorting (optional)
     *         Options: true = descending, false = ascending, empty/null = no sorting, "yes" (ascending), 
     *         "no", "ascending", "descending" (can be abbreviated "a" and "d" respectively).
     */
    this.addColumn = function(column, join, sorting) {
            var nsSearchColumn = null;
            var paramColName = null;
            var paramJoin = null;
            var paramSummary = null;
            var paramSorted = null;
            // Check if first argument is string or object
            if (typeof column == "string") {
                paramColName = column;
                // Check if second argument is null (for no join)
                if (isNullOrEmpty(join)) {
                    paramJoin = null;
                    // Check if arguent for sorting was provided
                    if (!isNullOrEmpty(sorting)) {
                        paramSorted = sorting;
                    }
                } else {
                    // Check if second argument is boolean, then it is not 'join' but 'sorting'
                    if (typeof join == "boolean") {
                        paramSorted = join;
                        paramJoin = null;
                    } else {
                        paramSorted = sorting;//sorted;
                        paramJoin = join;
                    }
                }
                // Now paramJoin and paramSorted are assigned properly
                if (typeof paramSorted == "boolean") {
                    if (paramSorted == true) {
                        paramSorted = "des";
                    } else {
                        paramSorted = "asc";
                    }
                } else if (typeof paramSorted == "string") {
                    // Get first character of string, in lower case
                    var tmp = paramSorted.slice(0, 1).toLowerCase();
                    // y = ascending sorting, n = no sorting, a = ascending, d = descending
                    if (tmp == 'y' || tmp == 'a') {
                        paramSorted = "asc";
                    } else if (tmp == 'd') {
                        paramSorted = "des";
                    } else {
                        paramSorted = null;
                    }
                }

            } else {
                if (column.hasOwnProperty("name") && column.name != null) {
                    paramColName = column.name;
                } else if (column.hasOwnProperty("columnName") && column.columnName != null) {
                    paramColName = column.columnName;
                } else if (column.hasOwnProperty("columnname") && column.columnname != null) {
                    paramColName = column.columnname;
                } else if (column.hasOwnProperty("column") && column.column != null) {
                    paramColName = column.column;
                } else {
                    throw nlapiCreateError('search.addColumn() - Required Argument Missing', 'The required argument <em>columnName</em> is missing. This argument is required.<br>Received: ' + JSON.stringify(column));
                }
                if (column.hasOwnProperty("join") && column.join != null) {
                    paramJoin = column.join;
                }
                if (column.hasOwnProperty("summary") && column.summary != null) {
                    paramSummary = column.summary;
                }
            }
            nsSearchColumn = new nlobjSearchColumn(paramColName, paramJoin, paramSummary);
            // Check if 'sorted' value exists in object
            if (column.hasOwnProperty("sorted") && column.sorted != null) {
                // Get first 3 characters as lower case
                paramSorted = column.sorted.toLowerCase().substring(0, 3);
            } else if (column.hasOwnProperty("sorting") && column.sorting != null) {
                // Get first 3 characters as lower case
                paramSorted = column.sorting.toLowerCase().substring(0, 3);
            } else if (column.hasOwnProperty("sort") && column.sort != null) {
                // Get first 3 characters as lower case
                paramSorted = column.sort.toLowerCase().substring(0, 3);
            }
            if (paramSorted!= null && paramSorted!="") {
                if (paramSorted == "asc") {
                    nsSearchColumn.setSort(false);
                } else if (paramSorted == "des") {
                    nsSearchColumn.setSort(true);
                } else {
                }
            }
            // Check if 'formula' value exists in object, then add to column object
            if (column.hasOwnProperty("formula") && column.formula != null) {
                nsSearchColumn.setFormula(column.formula);
            }
            // Check if 'functionId' value exists in object, then add to column object
            if (column.hasOwnProperty("functionId") && column.functionId1 != null) {
                nsSearchColumn.setFunction(column.functionId);
                // Push new nlobjSearchColumn into array
            }
            // Check if 'label' value exists in object, then add to column object
            if (column.hasOwnProperty("label") && column.label != null) {
                nsSearchColumn.setLabel(column.label);
            }
            this.columns.push(nsSearchColumn);
            return nsSearchColumn;
        } // end function addColumn


    /**
     * Add multiple columns to include in the search
     * @param {array} columns - array of column objects
     */
    this.addColumns = function(columns) {
            for (var i = 0; i < columns.length; i++) {
                this.addColumn(columns[i]);
            }
        } // end function addColumns

    /**
     * Add a search filter
     * @param {object}|{string} filter - filter object or string containing fieldId
     * @param {string} fieldJoinId - field to use for join (optional)
     * @param {string} operator - operator for filter (optional)
     * @param {string} value - value to filter for (optional)
     */
    this.addFilter = function(filter, fieldJoinId, operator, value) {
            if (typeof filter == "object") {
                var obj = filter;
                var fieldId = obj.field;
                var fieldJoinId = null;
                if (filter.hasOwnProperty("join")) {
                    fieldJoinId = obj.join;
                }
                var operator = obj.operator;
                var value = obj.value;
                // Create filter object
                var nsSearchFilter = new nlobjSearchFilter(fieldId, fieldJoinId, operator, value);
                // Check if 'formula' value exists in object, then add to filter object
                if (obj.hasOwnProperty("formula") && obj.formula != null) {
                    nsSearchFilter.setFormula(obj.formula);
                }
                // Check if 'functionId' value exists in object,then add to filter object
                if (obj.hasOwnProperty("functionId") && obj.functionId != null) {
                    nsSearchFilter.setFunction(obj.functionId);
                }
                this.filters.push(nsSearchFilter);
            } else {
                var fieldId = filter;
                this.filters.push(new nlobjSearchFilter(fieldId, fieldJoinId, operator, value));
            }
        } // end function addFilter


    /**
     * Add multiple search filters
     * @param {array}filters - array of filter objects
     */
    this.addFilters = function(filters) {
            for (var i = 0; i < filters.length; i++) {
                this.addFilter(filters[i]);
            }
        } // end function addFilters

    /**
     * Add filter expression
     * @param {array} expression - array structure describing search expression
     */
    this.addFilterExpression = function(expression) {
        this.filters.push(JSON.parse(expression));
    }

    /**
     * Set filter expression - Replaces any existing filters
     * @param {array} expression - array structure describing search expression
     */
    this.setFilter = function(filterArray) {
        this.filters = filterArray;
    }
    
    /**
     * Set the type of record to search for
     * @param {string} type - internalid of record type to search for
     */
    this.setRecordType = function(type) {
            this.recordType = type;
        } // end function setRecordType


    /**
     * Use an existing saved search as starting point for this search
     * @param {string} internalid - internalid of existing saved search
     */
    this.useSavedSearch = function(internalid) {
        if (!isNullOrEmpty(internalid)) {
            this.internalId = internalid;
            // If internal id of a saved search is provided, load that saved search
            this.savedsearch = nlapiLoadSearch(this.recordType, this.internalId);
        }
    } // end function useSavedSearch


    /**
     * Return search results as a nlobjSearchResult object
     * @param {string} recordtype - Optional NetSuite recordtype (internalid)
     */
    this.getResults = function(recordtype) {
            var results = [];
            if (recordtype != null && recordtype != "") {
                this.recordType = recordtype;
            }
            if (this.internalId != null) {
                // If internal id of a saved search is provided, load that saved search
                var savedsearch = nlapiLoadSearch(this.recordType, this.internalId);
                // Add new filters to saved search filters
                var newfilters = savedsearch.getFilters().concat(this.filters);
                // If existing columns in saved search should not be use, replace then
                var newcolumns = [];
                if (this.noSavedColumns) {
                    savedsearch.setColumns(this.columns);
                    newcolumns = this.columns;
                } else {
                    // Add new columns to saved search columns
                    newcolumns = savedsearch.getColumns().concat(this.columns);
                }
                // Perform the search
                var newsearch = nlapiCreateSearch(savedsearch.getSearchType(), newfilters, newcolumns);
                // 
            } else {
                // Otherwise build the search ad-hoc and set columns and filters
                var newsearch = nlapiCreateSearch(this.recordType, this.filters, this.columns);
            }
            var resultset = newsearch.runSearch();
            // Loop through the search result set 900 results at a time and build an array
            // of results. This way the search can return more than 1000 records.
            var searchid = 0;
            do {
                var resultslice = resultset.getResults(searchid, searchid + 900);
                for (var rs in resultslice) {
                    results.push(resultslice[rs]);
                    searchid++;
                }
            } while (resultslice != null && resultslice != undefined && resultslice.length >= 900);
            return results;

        } // end function getResults

} // end class search
0 Comments

Convert US state abbreviations in Javascript

I was working on a NetSuite project today, and I ran into a problem. I used DataTables to display sales orders. The data is retrieved through an Ajax call to a RESTlet on the server.

One of the columns to display is the state of the shipping address. The table had a number of columns, so I was happy that the state coming over during the early testing were the abbreviated state. But today I noticed that after real data had been entered into the system, the state was the full name. And I had no space left in the table for that.

So I did a quick search and found a snippet of code that converted between abbreviation and full name and vice versa. I made some minor modifications to the code, mainly to clean it up and also make the code easier to read. I introduced two constants to indicate which kind of conversion to use, and replaced the traditional loop through the array with a for…of iteration.

You can find the code here: https://github.com/TexasSwede/stateAbbreviations

And this is how you use it:

var stateName = convertRegion("TX",TO_NAME);                       // Returns 'Texas"
var stateAbbreviation = convertRegion("Florida",TO_ABBREVIATED):   // Returns "FL"

This code is of course not specific to NetSuite, it is plain Javascript. You can use it in a Domino web application or even in a Notes form. And naturally you can use it in pretty much any web application where you can use Javascript.

Enjoy!

0 Comments

Domino 10 and Beyond – my thoughts

It has now been a little over a month since IBM announced the new direction of IBM Notes, Domino, Verse and Sametime. I have been thinking through what I think this means for the product and the ecosystem of third-party tools and business partners. Some people view the move of development from IBM to HCL Technologies as an abandonment of the product family. But that is not how I see it.

IBM has, despite their size, limited resources to dedicate to development of the Domino family of products. They have new products and services they are trying to bring to market, and by having HCL take over the development and add more resources, this is a win both for IBM and for Notes/Domino.

With more developers dedicated to the product, I expect to see more frequent updates and new features added quicker than we have been used to the last 5-6 years. The product management and future direction of the platform is still managed by IBM, but with more non-IBM resources at their hands I hope the product managers will be able to push harder for the addition of new technology and updates, bringing Domino back to a first class development platform.

Domino was an outstanding product, but for the last 6-8 years the innovation mostly stopped. New technologies were not added at the pace they were adapted by the rest of the world, and the support for new protocols like TLS 1.2 was lagging. IBM also but on Dojo as the framework for XPages, while the rest of the world mostly went to jQuery.

But if IBM allows HCL to update some aging parts and add new functions, requested by the community, I can see this being a great platform. And IBM says they will listen to the community and the users. Starting this month, IBM is bringing the Domino 2025 Jam to four cities in North America: Toronto on 12/8, Dublin (Ohio) on 12/13, Chicago on 12/14 and Dallas on 12/15. here will also be several events in Europe as well as a virtual Jam sometime in the future.

At the Domino 2025 Jam developers and users will be able to suggest what features they find important, what needs to be fixed, and where they want to see the product go in the future. I don’t think the Jam will have a huge impact on the upcoming Domino 10 release next year, but it may help IBM prioritize where to put their effort. Where I see the Domino 2025 Jam being helpful is in the longer timeframe, especially if it is repeated every 12 to 18 months to verify that the product direction is still what the market is looking for.

I also would like to see IBM addressing at least the most requested changes on IdeaJam.

Let me describe some of the functions and features I want to see in an upcoming version of IBM Domino.

Javascript Everywhere

For the last 20+ years we have mainly been using Lotusscript, both in the client and for agents on the server. It is a powerful language, but if you have been working with other more modern languages (Lotusscript is based on Visual Basic) there are many limitations and functions you are missing.

I would like to see Javascript made into a fully supported language everywhere. Both in the client and on the server. Add support for jQuery, to make it easy to address elements, and create a Javascript API to complement the Lotusscript functions.

In addition to making it easier to create and parse JSON (used in and by most web applications today), it would open up the product to new developers who may come from a more traditional web development background.

I would love to see Lotusscript get a modernization, but I doubt that will happen. In order to improve Lotusscript, a quite lot of changes are needed. Instead I think the future improvements should be on the Javascript API side.

External API

Any modern product needs a public API so other tools and applications can integrate with it. I would like to see support in Domino for LoopBack, like IBM is doing in LiveGrid. When you create a view, there would be a matching API created to create, read, update and delete documents, as well as list all records, perform searches, etc.

But there should also be additional more specialized API:s available, perhaps the most common functions should be exposed as API calls out of the box.

Integration with External Services

Notes and Domino also needs integration with external services, e.g IBM Watson, Mongo DB or Node-RED. Why not support for IFFTT? Expose the calendar as a Google Calendar feed. But also make it easy to connect external services to Notes and Domino. Make it easy to use Oauth 2.0 to login to a Domino-hosted service and vice versa.

New Domino Designer

Unlink Domino Designer from the Notes client. Create a Eclipse plug-in (and make sure it stays updated to work with new versions of Eclipse). This will help new developers to start working with Domino, using tools they are already familiar with. The goal should be that someone familiar with Javascript should be able to open Eclipse and start writing code for Domino, and the only thing they need to learn is the Domino Object Model.

Add ready-to-use web components/plugins, so the developer can easily add for example a name-lookup into Domino Directory or a date/time selector. Support CSS frameworks like Bootstrap, and make it easy to modify the look of the applications.

Notes Client

The Notes client makes it easy to quickly build applications. You get a lot of the core functionality of the applications “for free”, like views, forms, etc. But you are also limited in how the application looks. You can change the look of views somewhat by selecting background colors, fonts and a few other attributes. On forms you can select between two different looks for some of the fields, while other fields can not be modified at all. What I would like to see is a way to easily restyle everything by using CSS. Then you can make the forms and views look much more modern. Let the developer create “themes”, a set of CSS rules and perhaps images that can be applied to new applications in seconds. These themes could be published online, for other developers to use.

These are just some of the ideas I have for improvements to Domino. What are you ideas?

5 Comments

My MWLUG presentation: Elementary!

Yesterday I presented at MWLUG, and I want to share my presentation with both the ones attending and anyone who was not able to be there. I am posting two version, one with just the slides, and one with speaker notes, where I tried to capture the content, if not the exact verbiage of the session.

I hope to be able to post the demo database with the code later this week or early next week.

 

1 Comment

My presentation at MWLUG

Tomorrow, August 8, you are welcome to attend my presentation “Elementary!” at MWLUG 2017. In about 45 minutes I will show how to easily incorporate Watson functionality in your own applications, both on the web and in your Notes client applications.

I will be using Node-RED and IBM BlueMix to do this, and I think many will be surprised how easy it is, and how little code is needed. For example I will implement translation from English to Spanish with two (2) lines of server side code. To call this from the web you just need another handful of lines.

I hope to see you tomorrow at 5pm!

0 Comments

Load and Modify External File in NetSuite

When building a suitelet in NetSuite you can either inject HTML, CSS and Javascript in a field, or generate a full HTML page and render it into the suitelet. No matter which method you use, you normally have to write line after line of SuiteScript code where you build the HTML using string concatenation. This is not only difficult and tedious to write, making sure you match all the single and double quotes and semi colons, it also makes the code much harder to maintain.

What if you could just create a regular HTML file, put it in the File Cabinet and then render it into a suitelet? And what if you could use one line of code to inject values from NetSuite in the correct place in the HTML? This could be search results from the use of my search function.

That is what the function looks like:

/**
 * Load file from NetSuite File Cabinet and replace placeholders with actual values
 * 
 * Version    Date            Author           Remarks
 * 1.00       07 Nov 2016     kmartinsson      Created class/function
 * 1.01       08 Nov 2016     kmartinsson      Consolidated setValue and setHTML into
 *                                             one method and added noEscape parameter
 */
// ***** Read and process external file, replacing placeholders with proper values *****
function ExternalFile(filename) {
   //Get the file by path/name, can also be internal id
   var fileId = filename;
   // Load file content and store data
   var file = nlapiLoadFile(fileId);
   var data = file.getValue();
   this.content = data;

   this.setValue = function(placeholder, value, noEscape) {
      // Check if noEscape is passed, if it is and if true then don't escape value.
      // This is needed when value contains HTML code.
      if (typeof noEscape == "undefined") {
         this.content = this.content.replace(new RegExp(placeholder, 'g'), nlapiEscapeXML(value));
      } else {
         if (noEscape == true) {
            this.content = this.content.replace(new RegExp(placeholder, 'g'), value);
         } else {
            this.content = this.content.replace(new RegExp(placeholder, 'g'), nlapiEscapeXML(value));
         }
      }
   }

   this.getContent = function() {
      return this.content;
   }
}

Reference this function in your Suitescript 1.0 code like this:

// Load extrenal HTML file
var html = new ExternalFile("SuiteScripts/BinTransfer.html");
// Insert NetSuite URL for CSS files
var cssFileName = nlapiLoadFile("SuiteScripts/css/drop-shadow.css").getURL();
html.setValue("%cssDropShadow%", cssFileName, true);
cssFileName = nlapiLoadFile("SuiteScripts/css/animate.css").getURL();
html.setValue("%cssAnimate%", cssFileName, true);
// Insert array returned from a search
html.setValue("%binarray%", JSON.stringify(binArray), true);
// Replace placeholders with values
html.setValue("%showAll%", "false");
html.setValue("%company%", companyName);

The last (optional) argument “noEscape” decides if the value should be URL encoded (false/omitted) or not (true) using the function nlapiEscapeXML(). In most cases you don’t need to specify this argument, but if you need to pass HTML or other code into the function you need to set it to true to avoid the code being modified.

As you can see in my example above, I get the NetSuite URL for my CSS files as well. Instead of hard coding the NetSuite URL into the HTML page, I calculate it and insert it when the page is loaded. Not only does it make the page easier to read the code, it also makes it much easier to maintain.

This is a snippet from the HTML file:

<!-- Load plugins/drop-shadow.css from File Cabinet -->
<link href="%cssDropShadow%" rel="stylesheet">
<!-- Load bootstrap-notify.js and animate.css from File Cabinet -->
<script src="%jsBootstrapNotify%"></script>
<link href="%cssAnimate%" rel="stylesheet">

Much easier to read!

Thanks to this little function I have built suitelets who does nothing but load a traditional HTML file with Bootstrap, jQuery, even jQuery Mobile for mobile devices. The page contains Javascript/jQuery that call RESTlest to read and write data. Now I can build suitelets with all the power I have in traditional web development at the same time as I get access to the full NetSuite functionality!

This can also be used to generate XML files to convert into PDF.

Happy coding!

 

0 Comments

Easy NetSuite Search

In an attempt to expand my knowledge to other platforms than Notes and Domino, I have now been working with NetSuite for a number of months. I have mainly been working with the ERP part of the cloud based system.

The language used is called SuiteScript, and it is Javascript with a NetSuite-specific API to work directly with the databases. Knowing Javascript makes it easy to get started, just like knowing Visual Basic makes it easy to learn Lotusscript. And just like with Lotusscript, you have to learn the NetSuite specific functions.

Since I like my code clean and easy to read (which will make future maintenance easier), I have created a number of functions to encapsulate NetSuite functionality.

The first one I created was to search the database. The search in NetSuite is done by defining the columns (i.e. fields) to return as an array of search column objects. Then an array of search filters is created, and finally the search function is called, specifying what record type to search and passing the two arrays to it as well. This is a lot of code, and with several searching in a script it can be very repetetive, not to mention hard to read.

Here is an example of a traditional NetSuite search:

var filters = [];
filters.push(new nlobjSearchFilter('item', null, 'anyof', item));
filters.push(new nlobjSearchFilter('location', null, 'noneof', '@NONE@'));
var columns = [];
columns.push(new nlobjSearchColumn('internalid'));
columns.push(new nlobjSearchColumn('trandate').setSort());
columns.push(new nlobjSearchColumn('location'));
var search = nlapiSearchRecord('workorder', '', filters, columns);

Using my function, the code wold be simplified to this:

var search = new Search('workorder');
search.addFilter('item', null, 'anyof', item);
search.addFilter('location', null, 'noneof', '@NONE@');
search.addColumn('internalid'));
search.addColumn('trandate',true);  // Sort on this column
search.addColumn('location');
var search = search.getResults();

The function also support saved searches. Simply add the following line:

search.useSavedSearch('custsearch123');

There is a limitation in SuiteScript so that a maximum of 1000 records can be returned by a normal search. There is a trick to bypass this, but it requires some extra coding. So I thought why not add this into the function as default? So I did.

Below is the code for the search function. I usually put it in a separate file and reference it as a library in the scripts where I want to use it. This first version does not support more advanced functionality like formulas in the filters. But for most searches this function will be usable.

/**
 * Module Description
 * 
 * Version    Date            Author           Remarks
 * 1.00       11 Nov 2016     kmartinsson
 * 1.05       27 May 2017     kmartinsson      Added support for record type in constructor
 *
 */
//***** Encapsulate search functionality *****
function Search(recordtype) {
   this.columns = [];
   this.filters = [];
   // If record type/ID is passed, no need to set it later
   if (recordtype == null || recordtype == "") {
      this.recordType = null;
   } else {
      this.recordType = recordtype;
   }
   // Set internal id of saved search to null
   this.internalId = null;
   // *** Set array of column names to return
   this.setColumns = function(columnArray) {
      for (var i = 0; i < columnArray.length; i++) { // Check if we have an array, used for joins and sorts if (columnArray[i].isArray()) { // We have an array. Now we need to figure out what it contains if (columnArray[i].length > 2) {
               // We have 3 values, must be id, join and sort
               this.addColumnJoined(columnArray[i][0], columnArray[i][1], columnArray[i][2]);
            } else {
               // We have 2 values, can be id + join or id + sort. Let's find out!
               if (typeof(columnArray[i][1]) == "boolean") {
                  // Boolean value in second parameter means sorting
                  this.addColumn(columnArray[i][0], columnArray[i][1]);
               } else {
                  // Not boolean means a join
                  this.addColumnJoined(columnArray[i][0], columnArray[i][1]);
               }
            }
         } else {
            this.addColumn(columnArray[i]);
         }
      }
   } // end function setColumns

   // *** Add column to existing array of column names
   this.addColumn = function(columnName, sorted) {
      if (sorted == undefined || sorted == null) {
         this.columns.push(new nlobjSearchColumn(columnName));
      } else {
         if (sorted) {
            this.columns.push(new nlobjSearchColumn(columnName)).setSort(true);
         } else {
            this.columns.push(new nlobjSearchColumn(columnName));
         }
      }
   } // end function addColumn

   // *** Add joined column with to existing array of column names
   this.addColumnJoined = function(columnName, joinName, sorted) {
      if (sorted == undefined || sorted == null) {
         this.columns.push(new nlobjSearchColumn(columnName, joinName));
      } else {
         if (sorted) {
            this.columns.push(new nlobjSearchColumn(columnName, joinName)).setSort(true);
         } else {
            this.columns.push(new nlobjSearchColumn(columnName, joinName));
         }
      }
   } // end function addColumnJoined

   // *** Add a filter for the search results
   this.addFilter = function(fieldId, fieldJoinId, operator, value) {
      this.filters.push(new nlobjSearchFilter(fieldId, fieldJoinId, operator, value));
   } // end function addFilter

   // *** Set the type of record to search for (default is null)
   this.setRecordType = function(recordType) {
      this.recordType = recordType;
   } // end function setRecordType

   // *** Set the saved search to use (internal id, default is null)
   this.useSavedSearch = function(internalId) {
      this.internalId = internalId;
   } // end function useSavedSearch

   // *** Return search results, supports >1000 results through nlapiCreateSearch
   this.getResults = function() {
      var results = [];
      if (this.internalId != null) {
         // If internal id of a saved search is provided, load 
         // that saved search and create a new search based on it
         var savedsearch = nlapiLoadSearch(this.recordType, this.internalId);
         // Add new filters to saved filters
         var newfilters = savedsearch.getFilters().concat(this.filters);
         // Add new columns to saved columns
         var newcolumns = savedsearch.getColumns().concat(this.columns);
         // Perform the search
         var newsearch = nlapiCreateSearch(savedsearch.getSearchType(), newfilters, newcolumns);
         // 
      } else {
         // Otherwise build the search ad-hoc and set columns and filters
         var newsearch = nlapiCreateSearch(this.recordType, this.filters, this.columns);
      }
      var resultset = newsearch.runSearch();
      // Loop through the search result set and build a result array
      // so the search can return more than 1000 records.
      var searchid = 0;
      do {
         var resultslice = resultset.getResults(searchid, searchid + 800);
         for (var rs in resultslice) {
            results.push(resultslice[rs]);
            searchid++;
         }
      } while (resultslice.length >= 800);
      return results;

   } // end function getResults

} // end class search

 

1 Comment

IBM Connect 2017 – I will be speaking in San Francisco

I will be speaking at IBM Connect in San Francisco now in February. Rob Novak has resurrected “The Great Code Giveaway” and asked me to present it together with him. Who would turn down that opportunity? So some time between February 21 and 23 you can see Rob and me on stage at Moscone West. The exact time and location has not been announced yet.

I hope to see you in San Francisco and that you will find our presentation and code useful!

1 Comment

IBM Notes, Domino and the future

As some may already know I was recently laid off after 14 years as a Notes and Domino developer at my workplace. I suspected for a while that some staff reduction would be coming soon, but I was a bit surprised that I was included since I am the only Notes developer in the company.

I had for a while considered to do consulting and freelance development. My wife as well as several friends have been encouraging me for years. So this was just the push I needed.

Demand Better Solutions Logo

I am starting my own company, Demand Better Solutions, where I will focus on Notes and Domino Development, application modernization and migration as well as building brand new web applications and websites.

I realize that me being laid off is just a business decision. It is not personal. Several of the business critical applications at my former employer are developed using IBM Notes, but the executives have for years been talking about moving away from the platform. Of course they don’t realize the huge amount of work needed to do this, but never the less this was/is their ultimate goal.

The reason is that they feel (based on what they hear from other executives) that Notes is old technology. The fact that IBM has been slow in modernizing the interface, and that many of the templates still look like back in 1999 when version 5.0 was released does not help this perception.

Last fall all our email at my old job was moved to Outlook, and ever since I have heard users complaining about missing Notes and certain functionality they were used to. A lot of integration between Notes applications and Notes mail were also lost, and I had to re-create it in different ways. You often hear stories about people complaining about the Notes client, but most of our users wanted nothing but to get it back…

My old employer also uses Visual FoxPro, a product where the last version was released in 2004. It has officially been discontinued by Microsoft, but we use it for several important applications. So I don’t think that even a product being discontinued is driving a huge number of migrations. It is the perception of how modern the product is that matters. And that perception is almost 100% the way the product looks.

To a user the interface is the product.

Create a modern looking application and nobody will question (or care) what tool was used to build it.

The last 3-4 years I have been learning new web technologies, like jQuery, Bootstrap, Ajax, JSON. I have been able to use much of that at work, as well as in several side projects. I also started learning C# and .net. After the layoff I sat down and started looking at (among others) php and mySQL as well as researched frameworks like AngularJS.

As a developer I have to keep up with new technologies, or I will be left behind. But it is hard when you work full-time, have side work and then have a family and house to take care of. Having some free time the last few weeks enabled me to focus on learning some new things.

I don’t think the Notes client will be developed much more, almost everything is moving towards web applications these days anyway. But IBM Domino is something totally different. It is an very capable and powerful development platform. With some skills in web technologies and a good understanding of the Domino platform one can build some amazing applications.

IBM recently released FixPack 7 and announced that the current version of Notes and Domino will be supported for at least five more years, until September 30, 2021. New functionality will be provided through Feature Packs, not version upgrades.

But Domino is just one tool of many. I am looking at LDC Via as another data store, as it very closely resembles Domino with a MongoDB-based NoSQL backend. Salesforce also has many similarities with Domino. The transition would therefore be fairly easy. AngularJS is another popular technology, with version 2.0 soon to be released. And we of course have IBM’s BlueMix offering, where MongoDB is just one of many technologies offered.

As a developer we need to learn new things constantly, the language or tools we use does really not matter. We should pick the proper tool, whatever fits the project.

Do you want to modernize your Notes and Domino applications?
Let me and Demand Better Solutions help you!

2 Comments

My MWLUG presentation

I have been very busy ever since the MWLUG conference in Austin, but now you can finally view my presentation and download the sample code. Enjoy!

 

MWLUG_2016

I will post the code for my Phonegap Demo next week.

Reminder: you need to sign the database (or at least all the agents) with an ID who has the rights to run agents, or the Ajax calls will not return anything.

If you are interested in having your Notes applications modernized and moved to the web, feel free to contact me at karl-henry@demandbettersolutions.com.

0 Comments

MWLUG in Austin – I will be presenting again

I have been selected to present at MWLUG in Austin on August 17-19. My presentation will be kind of part two of my presentation last year in Atlanta. It will focus less on the basics and go more into the fun and more advanced stuff. Kind of an extended version of my Connect 2016 presentation.

The title is “Think Outside The Box – Part 2”, and I will discuss and show how you can build a modern web front-end using standard techniques like Javascript/jQuery and frameworks like Bootstrap and jQuery Mobile and have it work against a Domino backend. I will demonstrate how to easily read data from and write data to the Domino database, and how to consume data using free plugins like BootstrapTable and FullCalendar.

I will also discuss the difference between JSON and JSONP and why the latter usually is better when building this type of integration. You will leave with a sample database containing the source code all the demos I will be showing as well as Lotusscript script libraries with classes I built to easily build agents that will interact with the website.

The idea is that you should be able to attend my session in Austin even if you haven’t seen any previous presentation. I will assume you have basic web design skills (HTML, CSS and a working understanding of Javascript) but you don’t have to be an expert at all. I also recommend some Lotusscript knowledge, as I will be providing all attendees with plenty of code to bring home and start using yourself.

I hope to see you in Austin in August! If you haven’t registered yet, go ahead and do it now! There are still seats left.

0 Comments

My Connect 2016 presentation & demo database

Connect2016_DemoDesignAs I promised, I would post my IBM Connect 2016 presentation on my blog.

Presentation (PDF): {link} 

Demo database (ZIP): {link}

You can also find the presentation on SlideShare.net.

To the right you see the database design, you want to look in the Agent section for the agents and in the Pages section for the HTML pages.

Note: You need to sign the database with an ID that have the proper rights. Otherwise the code will not work.

Enjoy!

 

6 Comments

IBM Connect 2016 coming up!

Connect2015_People1In the end of January it is once again time to head to Orlando for the yearly conference that for many years was known as Lotusphere. For the last few years it have been renamed IBM Connect (as well as ConnectED in 2014), and last year most people (including me) thought that 2015 was the end of this conference.

But perhaps due to the popularity of the 2015 edition, IBM decided to have the conference again this year, but in a new location as the contract with Swan and Dolphin (where the conference had been held since the first one in 1993) had expired.

The fountain at WDW Dolphin
The fountain at WDW Dolphin

The new venue is Hilton Orlando. It is closer to the airport and there are also more restaurants around than at Swan and Dolphin. It is close to SeaWorld as well as to the Universal Studios theme parks. Personally I am excited about the new venue. “Swolphin” (as Swan and Dolphin often was referred to) started to get old and worn down, despite a refresh of the rooms back in 2003-2005 some time. Yes, after this many years (18 in a row for me) Swolphin started feeling like a home away from home. You know where everything is, you know the staff and the shortcuts between hotels and sections within the hotel.

So a new location makes Connect 2016 more exciting, it will feel like a new conference but hopefully with many of my old friends attending. I have already found several interesting sessions using the session tool. Philippe Riand and Jesse Gallagher will for example talk about the Darwino application development platform, which allows you to integrate your Domino applications with IBM Bluemix an IBM Connections. Another must-attend session is called IBM Domino App.Net and talks about how to utilize Bluemix to build XPages applications in the cloud.

In addition we of course have all the sessions we have come to know and love: UserBlast with Mat Newman, Admin Tips Power Hour presented by Chris Miller, Spark Ideas, and of course the Opening General Session (OGS) with a secret guest speaker as the tradition requires.

HP_GringottsAfter the fiasco last year with the Tuesday evening special event the organizers went back to holding the event in one of the local theme parks. For the second time it will be held in the Wizarding World of Harry Potter – Hogsmead, which is part of Universal’s Islands of Adventure. Last time I had a blast, so much that last year I took a couple of vacation days to visit Hogsmead again as well as the then newly opened Diagon Alley extension over in the Universal Studios park next-door. You need a park-to-park admission pass to visit both parks, but that allows you to take the Hogwarts Express between the two parks.

ConnectSessionLetterFor me personally Connect 2016 is a milestone. It will be my 20th Lotusphere/Connect and for the first time I will present a session!

This is not a full one hour session, but a new format called Lightning Talk. Those are shorter 20 minute sessions, and not all of them are listed in the session tool on the conference site yet. I think this is a very interesting concept, and I believe it will be successful. I can see myself attending a number of shorter sessions like this to get a good overview of a particular subject, then go on and learn more later.

My session is called “Think outside the box” and I will show how you can connect to a Domino backend from a traditional web application and retrieve data in JSON format. This data can then be used to populate fields/values on a page or used in jQuery/Bootstrap plugin like calendars and data tables. This is a version of the presentation I did at MWLUG in Atlanta, but shorter and with some new content added.

I hope to see you at Connect 2016 in Orlando, perhaps even at my session. If you haven’t registered yet, it is time to do it now. Stay tuned for more posts here leading up to the conference.

1 Comment

Calling a Notes web agent from another server using JSONP

In my MWLUG presentation (as well as in a couple of entries on this blog) I talk about how you can access Domino data from a regular webpage using jQuery and a Lotusscript agent returning data as JSON. The issue with this solution is that the web page must be on the same web application path as the Domino agent. You can’t do what’s known as cross-domain Ajax.

For example if the Domino server is domino.texasswede.com but you have the webpage hosted at www.texasswede.com, it will not work. The security in Javascript does not allow calls across servers like that. There is however an easy solution, and it is called JSONP. What you do is to return not JSON but a call-back function with the JSON data as the argument.

So instead of returning this:

{ "firstName":"Karl-Henry", "lastname":"Martinsson","email":"texasswede@gmail.com" }

you would have the Lotuscript agent return this:

personCallBack({ "firstName":"Karl-Henry", "lastname":"Martinsson","email":"texasswede@gmail.com" })

Let’s assume we call the agent GetPersonData.jsonp.  On the calling side (in the jQuery code) you would then use this code:

$.ajax({
    url : "http://domino.texasswede.com/database.nsf/GetPersonData.jsonp?OpenAgent",
    dataType:"jsonp"
});

Finally you write the Javascript call-back function that will accept the data:

function personCallBack(data) {
    $("#firstName").html(data["firstName"]);
    $("#lastName").html(data["lastName"]);
    $("#emailAddress").html(data["email"]);
}

You can of course make this as advanced as you like but this is the basics. I have updated the JSON class I use for stuff like this to include a method to return JSONP. The new function is called SendJSONPToBrowser() and takes a string with the name of the call-back function as argument, for example like this:

Call json.SendJSONPToBrowser("personCallBack")

Below is the updated class (if you downloaded my sample database from MWLUG you have the older version of it). Enjoy!

 

%REM
	Library Class.JSON by Karl-Henry Martinsson
	Created Oct 9, 2014 - Initial version
	Updated Nov 6, 2015 - Added JSONP support
	Description: Class to generate simple JSON from values
%END REM

Option Public
Option Declare

Class JSONdata
	Private p_json List As String
	
	Public Sub New()
		'*** Set default value(s)
		me.p_json("ajaxstatus") = ""
	End Sub
	
	%REM
		Property Set success
		Description: Set success to true or false
	%END REM
	Public Property Set success As Boolean
		If me.success Then 
			Call me.SetValue("ajaxstatus","success")
		Else
			Call me.SetValue("ajaxstatus","error")
		End If
	End Property
	
	%REM
		Property Get success
		Description: Not really used...
	%END REM
	Public Property Get success As Boolean
		If me.p_json("ajaxstatus") = |"success"| Then
			me.success = True
		Else
			me.success = False
		End If
	End Property
	
	%REM
		Sub SetMsg
		Description: Set msg item
	%END REM
	Public Sub SetMsg(message As String)
		Call me.SetValue("msg",message)
	End Sub
	
	Public Sub SetErrorMsg(message As String)
		Call me.SetValue("errormsg",message)
		me.success = False
	End Sub
	
	Public Sub SetValue(itemname As String, value As String)
		Dim tmp As String
		Dim delimiter As String
		'*** Check for quote (double and single) and fix value if needed
		tmp = Replace(value,Chr$(13),"<br>")
		tmp = FullTrim(Replace(tmp,Chr$(10),""))
		If InStr(tmp,|"|)>0 Then
			If InStr(tmp,|'|)>0 Then
				tmp = Replace(tmp,|"|,|"|)
				delimiter = |"|
			Else
				delimiter = |'|
			End If
		Else
			delimiter = |"|
		End If
		'*** Store value with delimiter in list
		me.p_json(itemname) = delimiter & tmp & delimiter
	End Sub
	
	Public Sub SetData(itemname As String, value As String)
		'*** Store value in list
		me.p_json(itemname) = value
	End Sub
	
	%REM
		Function GetJSON
		Description: Return a JSON object as text
	%END REM
	Function GetJSON As String
		Dim json As String
		'*** Opening curly braces + CR
		json = "{" + Chr$(13)
		'*** Loop through all list elements and build JSON
		ForAll j In me.p_json
			json = json + |"| + ListTag(j) + |":| + j + "," + Chr$(13)
		End ForAll
		'*** Remove the comma after the last item
		json = Left$(json,Len(json)-2) + Chr$(13)
		'*** Add closing curly bracket and return JSON
		json = json + "}"
		GetJSON = json 
	End Function
	
	%REM
		Sub SendToBrowser
		Description: Print JSON to browser, with correct MIME type
	%END REM
	Public Sub SendToBrowser()
		'*** MIME Header to tell browser what kind of data we will return (JSON).
		'*** See http://www.ietf.org/rfc/rfc4627.txt
		Print "content-type: application/json"
		Print me.GetJSON
	End Sub
	
	%REM
		Sub SendJSONPToBrowser
		Description: Print JSON to browser, with correct MIME type
	%END REM
	Public Sub SendJSONPToBrowser(callbackFunction As String)
		'*** MIME Header to tell browser what kind of data we will return (Javascript).
		'*** See http://www.rfc-editor.org/rfc/rfc4329.txt
		Print "content-type: application/javascript"
		Print callbackFunction + "(" + me.GetJSON + ")"
	End Sub
	
End Class

 

0 Comments

Microsoft releases Visual Studio 2015

Microsoft today released the latest version of their development environment Visual Studio. There are even free versions, including the complete IDE Visual Studio Community and the code editor Visual Studio Code (available for Widnows, Linux and OSX).

Visual Studio now includes even more tools for cross platform mobile development for iOS  and Android. There is even an Android emulator included. The web development part supports tools and frameworks like Angular, Bootstrap, jQuery, Backbone and Django.

And naturally the IDE also supports Windows, including Windows 10 (expected to be released at the end of the month).

I have been using tools in the Visual Studio family for many years, I started with a beta of Visual Basic 1.0 a long time ago, and used all version up to and including VB 6.0. I also played around some with Visual C++ and even Visual J++. After that I focused mainly on Lotus Notes development, but recently I have started some C#/.NET projects at work using Visual Studio Community 2013.

0 Comments

MWLUG in Atlanta – I will be presenting!

It is less than 7 weeks left until MWLUG, the Midwest Lotus User Group conference. This year the conference takes place in Atlanta, between August 19 and 21. During the three days there will be over 40 technical session and workshops on collaboration, receptions and networking opportunities, as well as access to experts of IBM solutions, both from IBM and other companies. The topics includes application development, system administration, best practices, customer buisness cases and innovation/future plans by IBM. Breakfast and lunch is included for two days as well. And all this for the cost of only $50 per person! The event takes place at Ritz-Carlton in downtown Atlanta. There is a block of rooms reserved at a special conference rate of $149.00 per night.

One of the sessions will also mark my personal debute as a speaker at a conference. I will present “Break out of the box – Integrate existing Domino data with modern websites” where I will talk about how to integrate websites built either within Domino or on other platforms with backend data that resides in a Domino database. I will talk about how you can build a modern looking website using tools like jQuery and Bootstrap and seamlessly integrate them with existing data on your trusty Domino server using JSON and Ajax. I will also provide plenty of example code ready for you to bring home and start playing with.

A number of IBM Champions will be presenting, as well as IBMers and other industry experts. So no matter your interest, I am sure you will find plenty of good sessions. I am sure I will have a hard time picking which sessions to attend!

So what are you waiting for? Go to http://www.mwlug.com and register! See you there!

 

1 Comment

Microsoft and jQuery Ajax calls – not using standards

I recently started using C# and .NET for the first time to build a web application. It is just a proof of concept application where I am trying to implement CRUD (Create, Read, Update and Delete) though jQuery and Ajax calls from a simple webpage. The application should let me retrieve a list of all companies in the database, get information about a specific company (based on a company id), update an existing company (and create a new company in the database if it does not exist) and finally allow a company to be deleted.

I been doing these things for years using IBM Domino as the backend, simple reading the query string and parsing the name-value pairs before performing actions based on the values. So when I started using Visual Studio I naturally thought things would work the same there.

But I found out that ASP.NET is using a different method to address web resources. It uses the concept of routes, so instead of adding information passed to the server using the query string, the data is passed in the actual URL:
To get a list of all companies you would call /api/Company, and to get information about a specific company you add the company id (/api/Company/Q1234). If I want to pass two arguments to the server, for example to get all companies in a specific city and state, you would call /api/Company/TX/Dallas.

In my opinion, this gives you much less flexibility than if  you pass arguments in the query string. You must put the arguments in the correct order, and it is much harder to use optional arguments. One example of where I used optional argumenst is for sort order. In some cases I want the companies to be returned in descending order, instead of the default ascending. Or I want to sort on a specific column/values. In those cases I pass along a special argument, but normally I don’t. Less data to transfer that way, and cleaner code. But it still works.

It is when you want to perform a POST of form data to the server that it get really complicated and annoying. This is the sample code using the ASP.NET Web API generated by Visual Studio 2013:

// POST: api/Company
public void Post([FromBody]string value)
{
    ... do stuff here
}

As you perhaps can tell, this function only take one argument, which is pretty useless in a real application. And you can’t just add additional arguments in the declaration. One way to do it (as described here) is to use a data transfer object containing all the arguments, which then is used in the function:

public class CompanyDTO
{
    public string CompanyID { get; set; }
    public string LegalName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZIP { get; set; }
}

// POST: api/Company
public string Post(CompanyDTO Company)
{
    return Company.LegalName + " in " + Company.City + ", " + Company.State;
}

The issue here is that you need to put the arguments in exactly the same order in the Ajax call (and hence the query string) as they are declared in the code. You also can’t (as far as I understand) send only updated values, you need to always send all the fields, even if just one field has been changed.

So what should one do? The best solution I found this far is to pass the data from the browser as a string, containing JSON. Not as a JSON object, as that will not work.

So do not do this:

$.ajax({
    type: "POST",
    url:  "api/Company/",
    data: {'city':'Dallas','legalname':'Test Company, LLC'},
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

The browser will just convert the JSON object to name-value pairs, and you end up with null in your code. Instead, change the jQuery code to this:

$.ajax({
    type: "POST",
    url:  "api/Company/",
    data: "{'city':'Dallas','legalname':'Test Company, LLC','Owner':'Karl-Henry Martinsson'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

Now it will work! Notice the small change, I added quotes around the JSON. An added bonus is that you don’t need to pass along all fields, just the ones you want/need in any order. And if you pass along a field/name that is not defined on the server, it will simply be ignored.

You probably don’t want to build the data string manually. Perhaps you want to loop though certain fields and retrieve the values to pass to the server. You would do something like this:

// Create a new empty object
var Company = { };
// Loop through all elements with the class 'dataField' and
// build an object with the ID of the element as the name.
$('.dataField').each(function() {
  Company[this.id] = this.value;
});

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "/api/Company",
  data: JSON.stringify(Company),
  dataType: "json"
});

I use JSON.stringify to convert the JSON object to a string before sending it to the server.

So this is what I found out. Hopefully it will help someone. I am still a bit frustrated that Micorosft once again decided to do things a different way than the rest of the world, but I guess one should not be surprised at that.

 

 

 

 

3 Comments

File Upload in Classic Domino Web using jQuery and Bootstrap

This week I was asked to create a simple web form where customers could fill out a few fields, attach two files and submit it for review. The document with the information and attachments are saved into a Domino database, so it can be processed thought the Notes client by the internal staff.

These days I mainly use Bootstrap (and jQuery) to design the webpages, since Bootstrap makes it very quick and easy to get a nice clean look of the page. Using jQuery allows me to do some nice manipulations of the DOM, hiding and showing sections as needed for example, or disable the submit button until all required fields have been filled out.

It has been a long time since I worked with the file upload control in Domino, and it was as ugly as I remembered it. But I knew I had seen some nice jQuery/Bootstrap file upload controls, so I located one that I liked in the Jasny plugin library. If you haven’t already, take a look at those components!

So how do I tie this control to the Domino file upload control? As so many times before, Jake Howlett and his excellent site CodeStore comes to the rescue. He wrote an article back in 2005 about how to fake a file upload control, and that code can be used as-is, and combined with the Jasny plugin.

Here is what my code looks like after doing that:

<div class="col-md-6">
  <label>Producer Agreement</label>
  <!-- File Upload -->
  <div class="fileinput fileinput-new input-group" data-provides="fileinput" title="Attach file here">
    <div class="form-control" data-trigger="fileinput">
      <i class="glyphicon glyphicon-file fileinput-exists"></i>&nbsp;
      <span class="fileinput-filename"></span>
    </div>
    <span class="input-group-addon btn btn-default btn-file">
      <span class="fileinput-new">Select file</span>
      <span class="fileinput-exists">Change</span>
      <input type="file" name="%%File.1" class="required">
    </span>
    <a href="#" class="input-group-addon btn btn-default fileinput-exists" data-dismiss="fileinput">Remove</a>
  </div>
</div>

On the second file upload control I just change the name to “%%File.2”. The form tag must have the encoding set to multipart/form-data, so this is what it looks like for me:

<form name="SubmissionForm" id="SubmissionForm" 
action="AgencySubmission?CreateDocument" method="post" 
enctype="multipart/form-data">

It all worked perfectly. I was able to attach the files and submit the form, and the files showed up in the Notes client. What I did not like was the dreaded “Form processed” message. I tried a few different things, using the $$Return field, etc. But nothing worked.

To make a long story short(er), and without diving too deep into details, I had the form setup to render as HTML, not as a Notes form, thus using ?ReadForm to display it. But when I changed it to Notes on the form properties, the Domino server added it’s own Javascript code to submit the form (in addition to extra HTML). I found out a way to trick Domino to “hide” that Javascript code, so only my jQuery/Javascript code was sent to the browser.

Then I wrote my own code to do a HTTP POST submission of the form as multipart/form-data:

$('form#SubmissionForm').submit(function(event){
  // Disable the default form submission
  event.preventDefault();
  // Gat all form data  
  var formData = new FormData($(this)[0]);
  $('input').each( function() {
    formData.append($(this).attr('id'),$(this).val());
  });
  // Submit form to Domino server using specified form
  $.ajax({
    url: 'AgencySubmission?CreateDocument',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,   // Important!
    processData: false,   // Important!
    success: function (returndata) {
      window.location = 'SubmissionThankYou.html';
    }
  });
  return false;
});

That’s it! It worked like a charm. And this is what the final result looks like:

FileUploadControl_Bootstrap

Of course, if you are able to use XPages, there are nice file upload controls there that you can use.

6 Comments

End of content

No more pages to load