Show / hide columns dynamically

To show or hide columns dynamically is a nice feature in the jQuery dataTables component. With a few simple steps you can deliver something similar in your XPages application as I demonstrate in the video.

The technologies used: XPages, Extension Library, Bootstrap.

Add 20 years of experience to your workforce

You can 20 years of experience within IBM Notes and Web development to your workforce by hiring me.

Interested? Read my curriculum vitae on LinkedIn: http://www.linkedin.com/in/patrickkwinten and get in contact.

I am happy to work WITH you !

Question: Is it possible to set via a resource via a theme so it is applied to any XPage in an application?

I received a question if it is possible to set (or add) a resource via a Theme resource so it will become available to any XPage or Custom control?

Yes ofcourse you can e.g. via:

<resource>
<content-type>text/css</content-type>
<href>custom.css</href>
</resource>

but you should keep in mind is that a Theme is ONLY applied in the Render Response phase. So if for example you include an SSJS library to the Theme, you will not be able to use it in the beforePageLoad or afterPageLoad event. A mistake that is common made.

My recommendation would therefor be to use a Theme more for applying default settings or to overwrite properties to a specific type of component, e.g. a default pageName property on the ViewRoot component.

In terms of adding resources I would advice to use a Custom control design element. SSJS that will be computed dynamically only run once per page load / refresh in a theme (just in Render Response), compared to every phase of the lifecycle in a Custom control.

Happy development =)

JavaScript Internationalization & placeholders

Introduction

Some time ago I wrote about moving a Teamroom application up to IBM Bluemix. This month the XPages runtime is now general available.

In the post I mentioned I would come back on some design gotchas I saw while analyzing and preparing the Teamroom application for staging it to Bluemix. So here is (at least9 a first post.

What I noticed for example was the usage of the l18n library in SSJS and placeholders in properties files.

i18n formatting

This is a server script library with methods to format messages for localization, display dates in a locale-specific manner and miscellaneous Internationalization utilities.

So how does this works?

Create two or more strings properties file e.g.

  • strings.properties
  • strings_sv.properties

The strings.properties file content:

compliment=Handsome

hello.world=Hello {0}

The strings_sv.properties file content:

compliment=Snygging

hello.world=Hejsan {0}

Now create an XPage and place e.g. a Computed Field control on it and calculate it’s value:

<xp: text><xp: this.value><![CDATA[#{javascript:compliment = strings.getString(“compliment”);

return i18n.format(strings.getString(“hello.world”), compliment);}]]></xp: this.value></xp: text>

(Do not forget to enable Internationalization for your application in the Application Properties under section International Options)

Placeholders

Notice in the properties file the usage of a placeholder: hello.world=Hello {0} and how it is being referred: strings.getString(“hello.world”), compliment. Here the variable compliment (another string property value) is put in the placeholder.

As a result in the default language I get returned “Hello Handsome” and when I choose Swedish as default language in my browser I get returned “Hello Snygging”.

By wrapping it and formatting it with the L18n library you ensure it is fitted according the active language. This is very handy for dates, amounts etcetera.

Links of interest

More details about JavaScript Internationalization can be found in the IBM Notes Domino Application Development wiki.

 

Quick way to get dynamic (BS) list groups from Notes views

Introduction

For an app I needed lists to let users quickly to have access to a subset of documents. Bootstrap has a nice feature called List Groups which gives you a nice basic UI for unordered lists with list-items.

A list group can contain badges which I find a nice alternative for a tag cloud which to me are not very mobile friendly.

Before we get started let’s show how the end-result could look like:

list-group computed

So how do we do this in XPages & Java?

First I want to point to a snippet Oliver Busse posted about Iterating through a HashMap in a repeat control. If you use that basic principle of binding a HashMap to a Repeat Control  and use a categorized view for filling the Hashmap you are there!

Java class snippet

Below is the snippet from my Java class:

public Set<Entry<String, Integer>> categoriesMap(String viewName) throws NotesException{
HashMap<String, Integer> categories = new HashMap<String, Integer>();
Database dataDB = dao.getDatabase();
String ViewName = viewName;
ViewNavigator nav = dataDB.getView(viewName).createViewNav();
ViewEntry entry = nav.getFirst();
while (entry != null && !entry.isTotal()){
categories.put(entry.getColumnValues().firstElement().toString(), entry.getChildCount());
ViewEntry tmpentry = nav.getNextSibling(entry);
entry.recycle();
entry = tmpentry;
}
nav.recycle();
return categories.entrySet();
}

The code will run through the provided Notes view and go through the categories and places the name/label and value/totals in a Map and returns a set view of the mappings contained in this map.

Custom Control

Next step is to place the list-group code from Bootstrap in a custom control and make it dynamic by generating the list-items via a Repeat control and bind that control to my Java code:

<?xml version=”1.0″ encoding=”UTF-8″?>
<xp:view xmlns:xp=”http://www.ibm.com/xsp/core”&gt;
<h2>
<xp:text
escape=”true”
id=”computedField1″
value=”#{javascript:compositeData.header}”>
</xp:text></h2>
<ul class=”list-group”>
<xp:repeat
id=”repeat1″
rows=”30″
var=”obj”
indexVar=”idx”>
<xp:this.value><![CDATA[#{javascript:var viewName = compositeData.viewName;
Picture.categoriesMap(viewName);}]]></xp:this.value>
<li class=”list-group-item”>
<span class=”badge”>
<xp:text
escape=”true”
id=”computedField2″
value=”#{javascript:obj.getValue()}”>
</xp:text>
</span>
<xp:link
escape=”true”
text=”#{javascript:obj.getKey()}”
id=”link1″>
<xp:eventHandler
event=”onclick”
submit=”true”
refreshMode=”complete”>
<xp:this.action>
<xp:openPage>
<xp:this.name><![CDATA[#{javascript:var target = compositeData.targetPage;
return target + “?filter=” + obj.getKey();}]]></xp:this.name>
</xp:openPage>
</xp:this.action></xp:eventHandler>
</xp:link>
</li>
</xp:repeat>
</ul>
</xp:view>

Properties

The custom controls takes in some properties set in the Property Definition section. Via this way I can re-use the Custom control for multiple dynamic list groups:

Conclusion

As you see, with a minimal amount of code you can create dynamic lists for your apps. In the sample above I do not handle views with more than 30 categories but I am sure you fix this yourself. Also the active class property is not implemented.

Happy development =)

 

prettytime for your XPages

Introduction

I guess most of us believe that not all users are robots, and especially in social applications where you try to approach humans as human friendly as possible the display of date and time in such format can be off added value.

Timeago

There are many scripts to display date and time in a human friendly format. For a project we are using timeago, a jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. “4 minutes ago” or “about 1 day ago”).

However, in combination with an infinite scroll feature to navigate through document collections we notice that the script not always return instantly the transformed date/time.

That is why I looked at a server-side transformation.

PrettyTime

PrettyTime is an OpenSource time formatting library. Completely customizable, it creates human readable, relative timestamps like those seen on Digg, Twitter, and Facebook.

It turned out the implementation of PrettyTime was quiet simple. I will describe the steps for you.

Install the jar & call the Java class

Download the project jar file and place it in the WebContent \ WEB-INF \ lib folder.  For a computed field on a custom control in a repeat control I have as SSJS code to call the Java class:

<xp:text>
<xp:this.value><![CDATA[#{javascript:var theDate = compositeData.Date;
p = new org.ocpsoft.pretty.time.PrettyTime();
p.format(new Date(theDate))}]]></xp:this.value>
</xp:text>

As a result I get to date displayed as:

prettytime

Pro’s & Con’s

In comparison with client-side solutions I have detect some con’s and pro’s for a server side solution:

  • Static; the client side solutions are capably of updating the date/time value on the fly.
  • Speed; the server side generated human friendly date is there when a document row is presented.
  • Extensibility; the number of display languages is more numerous for most client-side solutions. Also you can often “configure” the text format when desired.
  • Consistency; having a human friendly date in a local language may be in conflict with internationalization of your XPages app since that might require more work.

Anyway: I happy to hear how you have solved the human friendly date issue.

Happy development!

new release XPages OpenLog Logger and custom runtime error page

Introduction

Good news for me! In an XPage application I wanted to provide an error logging function and preferably to OpenLog. I had problems with implementing the previous version of OpenLog logger but yesterday a new version is released on OpenNTF which took away that pain.

OpenLog logger

The OpenLog logger has some powerful features:

  • It can be used in your managed beans and other Java classes.
  • It can be used directly from SSJS with as little as openLogBean.addError(e,this);.
  • From SSJS all caught errors on the page are logged out together, at the end of the request.
  • Only two method names are used from SSJS, one to add an error, one to add an event, making it easy to pick up
  • From SSJS you only need to pass the information you wish. There is no need to pass nulls or empty strings.
  • From SSJS only one unique error per component is logged, regardless of how many times the error is encountered during the refresh lifecycle.
  • In SSJS, if you use a custom error page, uncaught errors will also be logged.
  • Uncaught errors will be logged for the page the error occurs on, not your custom error page.
  • You can define the OpenLog path and a variety of other variables without needing to change the code.
  • The functionality and code are available as an OSGi plugin (the best practice approach) but can also be included in individual NSFs.

Custom Runtime Error Page

In case you want to implement such functionality then I recommend you also take a look at how to define a custom run time error page. In my project I am using Bootstrap for UI look & feel, so I followed the steps Erick McCormick provides in this blog post.

code-prettify

In Erick’s post you will find that he uses Google’s code-prettify project. A nice feature is to ability to set a skin for the error message box. There are plenty of color themes available for the prettify project but if you use Bootstrap like I do you could try this theme.

A big thank you to the OpenLog logger project members and Erick!

custom_error_page

 

Enforce HTTPS for my XPages

Sometimes it can be benefitial to enforce the https protocol. My use-case was that an XPages app was going to be opened from the mobile Connections app and just the HTTP protocol would case an additional login dialog to appear.

So the following SSJS code is what I came up with:

<xp:this.beforePageLoad><![CDATA[#{javascript:currURL = context.getUrl().getScheme();
if (currURL ==”http”){
var baseURL = context.getUrl().toString().toLowerCase();
safeURL = baseURL.replace(‘http’,’https’);
facesContext.getExternalContext().redirect(safeURL);
}
}]]></xp:this.beforePageLoad>

The code will check if the xpage is called with the http protocol, if so the same page is called but then with the https protocol enforced.

Since the application aggregates a lot of information from Notes views, which the application administrator can add, I also check if any URL’s with the http protocol are being displayed and transform them with the https protocol to reduce the first check:

<xp:eventHandler event=”onClientLoad” submit=”false”>
<xp:this.script><![CDATA[function toSSL() {
var current_host = location.host;
var hosts = [‘serverx.acme.com’,’servery.acme.com’,”serverz.acme.com’,current_host];
$.each( hosts, function( i, l ){
$(‘a[href*=”‘ + l +'”]’, ‘body’).each(function() {
var $a = $(this);
var href = $a.attr(‘href’);
if(href.indexOf(‘https’) == -1) {
var ssl = href.replace(‘http’, ‘https’);
$a.attr(‘href’, ssl);
}
});
});
};
$( document ).ready(function() {
toSSL();
});]]></xp:this.script>
</xp:eventHandler>

collapsible menu with persistent state

Introduction

For a project I needed to have collapsible menus where the state is persistent, in other words after a refresh or a reload it should now if the menu was opened or closed.

The content of the menu is dynamic and rather complicated containing sub levels with multiple actions in them. Each level item would trigger to rebuild the presented document collection via Java (perhaps more common known as a faceted search).

dijitTitlePane

Since we are using the Extension Library I took a look at the controls but I could not find one that fulfills my requirements (accordion, dojo accordion pane, dojo tab pane, outline). To prevent to embed “another” Jquery plugin I looked across the Dojo site and found the titlePane dijit.

A TitlePane is a pane that can be opened or collapsed, with a title on top. The visibility of the pane’s contents is toggled by activating an arrow “button” on the title bar via the mouse or keyboard. It extends ContentPane but since it isn’t used inside other layout widgets it’s not in the dijit.layout module.

To be honest I am not a Dojo warrior and mostly are satisfied with jQuery plugins but this sounded like something that I could use. For now I only have to menu sections to collapse; a KPI section and a Filter section. Each section has there level 1 and level 2 items.

Since the application works as much as possible with partial refresh and each filtering affects the content of these 2 sections I also needed to save the state of the panes (open or closed). This sounded like a combination of client (open / close the pane) and server side (save the state in a scope variable) actions. Hmmm. From day 1 I have found this mixture of CSJS and SSJS a problem child which you tend to forget/mess up. I decided to implement the approach Oliver Busse promotes in the following post “Writing and reading scoped variables via client side Javascript“. This approach probably makes the code less cluttered with mixture of languages.

I also noticed that the titlePane dijit is not error-proof implemented in the Bootstrap4XPages project in the Extension Library but I found a fix described in the post “fix for down caret icon in dijit.TitlePane when using Bootstrap from ExtLib“. I got a response from Brian Gleeson (IBM): A fix for the dijit.TitlePane issue has been delivered, and should show up in the next Extension Library release. Great & thank you Brian!

So having conquered the circumstances described above what became the result and how did I implement it?

Result

Let’s start with the result:

menu01

Image 1: first section opened.

menu2

Image 2: both sections opened.

Implementation

Each of the KPI and Filter item (can) have sub levels with different presentation and functionality which I will not describe for simplicity reasons.

dijitTitlePane

The titlePane dijit is not so hard to implement. Add the dojo module to your resources:

<xp:this.resources>
<xp:dojoModule name=”dijit.TitlePane”></xp:dojoModule>
</xp:this.resources>

Next add a div to your XPage and set the dojoType and title property. The mat-card styleclass provides a material design presentation.

Attributes

Also define custom attributes for open and toggleble for the div element. These are properties of the titlepane dijit.

Event handler

The event handler checks the state of the pane and writes the state to a scoped variable when the title section of the pane is clicked. For a complete description how to implement Oliver Busse’s utility I would like to direct you to his site.

<xp:div
id=”titlePaneKPI”  dojoType=”dijit.TitlePane” title=”Sales KPI”  styleClass=”mat-card”>
<xp:this.attrs>
<xp:attr name=”open” value=”false”></xp:attr>
<xp:attr name=”toggleable” value=”true”></xp:attr>
</xp:this.attrs>
<xp:eventHandler event=”onclick” submit=”false”>
<xp:this.script><![CDATA[var KPI = dojo.dijit.byId(“#{id:titlePaneKPI}”);
if (KPI.open){
setScopeValue(“view”, “MenuKPI”, “1”);
}
else{
setScopeValue(“view”, “MenuKPI”, “0”);
}]]></xp:this.script>
</xp:eventHandler>

</xp:div><!– /dijit.TitlePane –>

Odd behaviour

I also noticed a strange behaviour of the titlePane. At start I had multiple controls on my xpage to see their differences and capabilities. When I removed the Dojo Accordion Pane the carets for the dijitPane behaved odd:

menuodd

Note the plus (+) and minus (-) signs after the caret😕

So in front of the TitlePane dijit divs I placed a Dojo Accordion Pane and set the display style property to none (via a styleclass):

<xe:djAccordionPane id=”djAccordionPane1″

styleClass=”paneAccordian”>
</xe:djAccordionPane>

titlePane content

The content of the titlepane can be anything, in my case via a repeat controls a list group with list-group-items is generated.

  • Lead Flow

    <!– /col-xs-12 col-sm-12 col-md-12 col-lg-12 –>
    </div><!– /row –>

    Qualified Opportunities

    <!–/col-xs-12 col-sm-12 col-md-12 col-lg-12 –>
    </div><!– /row –>

    </div><!–/list-group–>

  • Personally I find it a good practice to comment the closure of elements, especially when using Bootstrap nowadays.

    Event handler when loading the page/custom control

    The last thing to include is an event handler that opens or closes the titlePane dijits depending on their last states that are stored in scoped variables.

    I placed the event handler on the custom control where the titlepanes reside in so it gets initiated every time a partial refresh takes place for the custom control.

    <xp:eventHandler event=”onClientLoad” submit=”false”>
    <xp:this.script><![CDATA[function getMenuState(){
    var KPI = dojo.byId(“#{id:titlePaneKPI}”);
    var Filter = dojo.byId(“#{id:titlePaneFilter}”);
    var KPI_status = getScopeValue(“view”, “MenuKPI”);
    var Filter_status = getScopeValue(“view”, “MenuFilter”);
    if(KPI_status==”1″){
    dijit.byId(“#{id:titlePaneKPI}”).set(‘open’,true);
    }
    if(Filter_status==”1″){
    dijit.byId(“#{id:titlePaneFilter}”).set(‘open’,true);
    }
    }
    getMenuState();]]></xp:this.script>
    </xp:eventHandler>

    I was not able to store the function in a CSJS library because it kept telling me then that dojo could not find any note to act upon, but this is probably due to my lack of guru knowledge of Dojo.

    Wrap up

    That is about it! With little programming and a couple of hordes I managed to apply a menu with a consistent state when performing partial refreshes!

    I am looking forward to hear what alternative solutions you have produced, perhaps they can serve me in the future. Happy coding!

     

    indexVar property from xp:repeat control not available in styleClass property of xp:button control

    In an application we are using Bootstrap (BS) and in BS you can highlight the state of a button by adding an active (style)class. In my situation the button(s) reside in a repeat control and basically a click on a button will update a part of the screen and change the collection of documents displayed.

    So my initial idea was to set a scope variable with the ID of the button clicked and update also the repeat control containing the buttons and modify the styleclass property based upon this scope variable.

    How to get the client ID of an xp:control I found in the answer of Tim Tripcony on a question on Stackoverflow.

    However I noticed a difference in the ID when an xp:control resides in a repeat control; it contains an incremental number from the repeat control e.g.

    view:_id1:_id81:repeat2:0:button2
    view:_id1:_id81:repeat2:1:button2

    If you use the same method (

    getComponent("button1").getClientId(facesContext)

    for an attribute or something you would miss the incremental number e.g.

    view:_id1:_id81:repeat2:button2

    So I posted a question on Stackoverflow about my options and thanks you for all the quick replies.

    Some answers directed me to use the indexVar property of the repeat control and add place that in my scope variable and use it in the computation for the styleclass property of the button.

    But then an error appeared on screen…

    [ReferenceError] ‘index’ not found

    I tested the computation with other xp:controls like a xp:link control or xp:computed text but no errors there.

    So I assume this ‘feature’ (as my collegue names it) is just not implemented yet in XPages for the xp:button control?

    Tip of the day: isDocument() for nested data in the Data View control

    You can show nested data in the details section of the Data View control. Read about it here: Data Views – Part 10: Nested Repeat in the Detail Section.

    In case you have a ‘flat’ Data View (one without collapisble categories) you do not need to detect if your ‘var’ property is a document. But when you have a categorized Data View you better check it otherwise opening/closing categories will give an error…