Connect 2014 SHOW102: XPages Still No Experience Necessary

Post on 14-May-2015

1.219 views 3 download

Tags:

description

Paul T. Calhoun, panagenda Kathy Brown, PSC Group IBM Connect 2014, Orlando

Transcript of Connect 2014 SHOW102: XPages Still No Experience Necessary

© 2014 IBM Corporation © 2014 IBM Corporation

SHOW102: XPages: Still No Experience Necessary

Kathy Brown, PSC Group, LLC Paul T. Calhoun, Panagenda

Agenda

Who We Are What We Are Building What Are XPages? Creating the Application Refining the Application

Who We Are

Kathy Brown – Consultant at PSC Group, LLC

Blogger at www.runningnotes.net IBM Champion Author

– SocialBizUg.org’s Notes Dev Tips newsletter – The View

Speaker at Lotusphere and user group events around the world Twitter addict

– @RunningKathy and 14 other accounts Geek, Nerd Girl, and Loud Laugher

Who We Are

Paul T. Calhoun – Senior Software Engineer – Panagenda (paul.calhoun@panagenda.com) – Owner – NetNotes Solutions Unlimited, Inc. (pcalhoun@nnsu.com)

IBM Champion – 2013 – 2014

Certified – Administrator – Developer

Speaker, Mentor, Trainer – Connect, LUGS

Grandfather – Ask to see my pictures !!!

Trademarks used in this presentation

IBM®

IBM® Lotus ®

IBM® Notes®

IBM® LotusScript

Java™

JavaScript™

5

Agenda

Who We Are What We Are Building What Are XPages? Creating the Application Refining the Application

What We Are Building An XPages Help Desk Application

– User can enter tickets – Resources can be assigned – Comments can be added

What we will need – Basic CRUD

• Create, Read, Update, Delete What we will use

– XPages components • OneUI • Core Controls • Extension Library • Custom Controls • and more!

Agenda

Who We Are What We Are Building What Are XPages? Creating the Application Refining the Application

What are XPages?

Design Elements and tools for creating Web applications Embraces standard languages

– HTML, XML, CSS, JavaScript, Java Built on top of Java Server Faces (JSF)

– XPages is a front-end that Domino Developers can understand Everything you code gets placed inside of Java Objects

– You never need to deal with those Java Objects though! You do not NEED to know Java to build XPages apps

– But it will help and should be something to strive for – Java in XPages is somewhat similar to LotusScript Custom Classes

What Does XPages Fix?

Separates UI from Data – Allows multiple Data sources per Page

• Data from “n” views from different .nsf’s – Easy access to data from other databases

Improves Data capabilities – Allows @DbLookup from inside a view

• Similar to a JOIN in relational DB’s. – Can use Java Objects (Beans) as data sources – Iterate your data anyway you want via “Repeat Control”

Runs inside Notes Client (XPiNC - XPages in Notes Client) – Replicate your web applications – Allows for consistent experience between Notes and Web Clients

“New” Design Elements XPage

– Blank “canvas” to create presentation layer for data – Similar to Notes Form

• But not really as you can have none or multiple datasources Custom Control

– Similar to Subform • But not really as you can have none or multiple datasources • Can be used more then once on a page • Can accept Parameters that you define later

Sever Side JavaScript – Language of choice for the beginner

Themes – Allow consistent look and feel across appliations – oneUI and WebStandard are built in – Create your own by extending oneUI and WebStandard – Themes can be used to push CSS files to every page of your app – Like a Global “Use” statement

XPages: Scoped Variables Scoped Variables

– In memory variables to store data – No need to rely on cookies / URL parsing

• but you still can if you want (but you won’t want to) applicationScope

– Like a database profile document – Available to all users

sessionScope – Life of the user session – Limited to the application it was declared in

viewScope – Life of the current Page

requestScope – Life of a single request – Very short

Getting Started Building the App

The most recent version of the starter files will be available at http://runningnotes.net We’re using Domino and Designer 9.0.1

– Starting with version 9.0 the core Extension Library is included Everything you see here should work on:

– Domino/Designer 8.5.x with Extension Library – Domino/Designer 9.0.x

• No update pack or Extension Library needed as it’s built in

Starter Files

We have a downloadable kit available to start This kit contains :

– Starter database – Finished Database – Slides – Script Snippets

Starter Database contains several forms and views, but no XPages code Download the kit to your machine and extract the files Copy the starter application to your Notes Data Directory

– usually something like c:\program files\lotus\notes\data

Starter Database Non-Xpage elements already added: Forms

– form_comment – form_resource – form_ticket – keywords

Views – vwComments – vwCommentsByKey – vwKeywords – vwTickets – vwTicketsByStatus

Example Documents – Some keyword documents – Some ticket documents

Development Process Does Not Change with XPages

It’s still a best practice to “develop locally” and “test globally” using an .ntf design template. For the purposes of this demo we will not use a template and we’ll work directly on our local server. This is convenient when starting a database as we’ll be doing a lot of testing as we go. So this eliminates

a lot of “Refresh Design” steps. Typically when an application reaches a certain stage of development it can be copied to an .ntf file to

become a true template.

Configuring Domino Designer for XPages Development

There are several things that can be configured that will make your XPage development experience easier The following are recommendations for setting properties in the Domino Designer BEFORE you start

developing

18

Configuring Domino Designer for XPages Development

Change your memory allocation – Edit the jvm.properties file located in the client installation directory under

• framework/rcp/deploy

Configuring Domino Designer for XPages Development

Edit with any text editor – Xmx – Total amount of RAM for Designer AND Client

• Set to at least 512m • Don’t set equal to the amount of system RAM

– Xms – Starting Heap size • Set to at least 128m • Don’t set equal to Xmx value

– Xmca – Memory block size • Set to at least 512k • Thanks a “k” NOT A “m”

Always set in multiple of “4” Will not take effect until client is

restarted if it is running when edited

Configuring Domino Designer for XPages Development

Monitor Memory Used In Designer Preferences

– Select General – Check “Show heap status”

Even though this is a checkbox, it does not “remember” the setting.

– It has to be checked each time you start designer.

Heap status is displayed in the lower left hand corner of the designer client.

– Monitor the amount of memory being used – Click the trash can icon to trigger garbage

collection

21

Configuring Domino Designer for XPages Development

Set XML Editor formatting for viewing XPage source In Designer preferences

– Select XML | XML Files | Editor – Change Line width – Check “Split multiple attributes each on a new line” – Check “Clear all blank lines”

Any new XPages source will adhere to these settings Existing XPages can be “reformatted” to adhere to these

settings by using the keyboard shortcut – <shift><ctrl><f>

22

Configuring Domino Designer for XPages Development

Before and after XPage Source Formatting

23

Open the Starter application from Domino Designer

Open the Starter application from Domino Designer

Make sure to choose Local - then find on your hard drive – It should have been first copied to your Notes Data Directory

Working Sets

Working sets are ways in Designer to group and organize your applications. – If using a working set you might see this screen. Choose Yes to add it. – If you’re not using a working set it will just be added to your application list

• Using Working Sets is a BEST PRACTICE !!!

Copying to Server

Right click on the starter file and copy it to your server if you’re using one

Opening from Server

Add the server version to your working set

Results

You end up with 2 applications. The local and a COPY on the server. – Since we did a file copy these will not replicate – We will focus on the server for this demo - you can right-click and “Remove” local if you want. – Using the server is more convenient for rapid testing and allows security to work

Agenda

Who We Are XPages What We Are Building What Are XPages? Creating the Application Refining the Application

Beginning to Code

Goals – Set some application properties – Create an overall layout for the web application

• Will be reusable so any pages we add get the same look and feel • Add the ability to Login / Logout to the app

– Create a home page – Test

Set the Theme and Default Error Handling

Application Configuration | Xsp Properties - General Tab - Set Application theme to: – Choose Oneuiv2.1 – This makes base css and dojo JavaScript resources available – Oneuiv2.1 is a theme provided by Domino and gives our application the “look and feel” similar to mail,

the teamroom, etc. – Using Oneuiv2.1 means we do not have to individually style anything, although we can if we want to

(more on this later) Select the “Display XPage runtime error page”

– This will provide more meaningful information is the XPage throws an error

Create the Layout for the Application

2 Custom Controls – 1 for the Main Layout – 1 to hold a Navigation Bar on the left side

Extension Library controls required for this – Many controls are added to the core product – App Layout Control provides the overall look and feel

• The App Layout Control can be added to each XPage for consistent navigation and layout throughout the application

– Form Tables and Form Rows allow us to easily layout fields – Tool Tips and Dialogboxes are available – Many many more tools available

Create layout_Main

Create a custom control to become the main layout of the application Custom controls - New Custom Control - “layout_Main”

Drag “Application Layout” onto Design Area

Just click OK on the wizard

Should Look Like This Green dots are areas for future custom controls You can drag controls onto the green dots (targets) Placing a control onto a target on the layout means the control will be used whenever the layout is used Leaving a target as a green dot means different controls may be used on different instances of the layout

Enable Green Dot for Middle Column Select the layout control by clicking on it. Then use properties tab to select.

Embrace the Source tab

Note by clicking the Middle Column that the source has updated.

– This “callback” allows Custom Controls to be added later

– We click the Middle column as that will be the placeholder for the page’s main content

– We do not click the left column as we’ll add the navigation menu to the layout custom control itself. This way it will be available to every page.

Create Ability to Login / Logout

Select the App layout control that you dropped on the page Add Login and Logout Node

Remove the Label This SHOULD make an Automatic Login AND Logout node

– But there is a bug, just the login gets created – Workaround will be to create a manual logout node

• We’ll do this in just a bit – For now, just clear the label field

Login/Logout Workaround

Before we create logout - Display the current user name Create a User Node

Login/Logout Workaround

In the Label field – Click on the blue diamond and select “Compute Value…” – Include the server-side javascript that will return the user name or anonymous

Display Current User

Server Side JavaScipt is used to create a NotesName object If the current user is not “Anonymous” we display a little welcome message

// Create Notes Name Object from the current effective user var userName:NotesName = session.createName(session.getEffectiveUserName()); // If the user is not Anonymous then return a welcome message if (userName.getCommon()!="Anonymous") { return "Welcome, "+userName.getCommon()+"!"; }

Server Side JavaScript

If that was your first real exposure to Server Side JavaScript (SSJS), congratulations! – That wasn’t so bad, right?

A few things to note: – Syntax is similar, but not the same as LotusScript – Semicolons, you need them – // is a comment, not ‘ – Assume EVERYTHING is case sensitive

• Proper Capitalization is important • @Unique() will work, while @unique will not

– Oh! And you can use some @Formula (not all, but quite a lot) • Parentheses are important

Adding Logout Fix

Add a Basic Node and set the label to “Logout” Add the SSJS code to the computed value with the following:

return facesContext.getExternalContext().getRequest().getContextPath() + "?Logout&redirectTo=" + facesContext.getExternalContext().getRequest().getContextPath()

var uName = session.getEffectiveUserName(); if (uName == "Anonymous") { return false; } else { return true; }

href property -

rendered property -

Home Page

Create a new XPage called “home.xsp” – Custom controls are never rendered directly to the browser. They must be placed on an XPage.

Drag layout_Main Onto Page

Note the green dot is back. This is because we enabled the middle column earlier. We will use this to add different controls to different pages.

Check the Source

Note: all that does is create a tag to represent the custom control

Drag a Panel onto the Green Dot

In Source mode this creates a facet tag. You can easily add content in here. This is the “body” of your web page

A panel is a container for other controls

Check the Source

In Source mode this creates a facet tag. You can easily add content in here. This is the “body” of your web page.

Content goes between the <xp:panel> tags

Add Some Text to Your Home Page

Gives us a place holder for later You can use source or design - Save this page and close

Set the Launch - Go Back to Application Properties

On the launch tab, set Launch to “Open designated Xpage”, XPage “home”. Don’t forget to save and close this.

Testing Locally

If developing with a local application, then the XPage can be tested by launching the XPage from the “Preview in Browser” action

53

Testing on the Server

If developing with a server based application, then ensure the “Sign agents or XPages to run on behalf of the invoker” has a GROUP name that includes the developer ID that saved/signed the XPage and Custom Control design elements

– This setting not being configured properly is one of the top reasons XPages do not render from a server !

54

Testing on a Server

If the signer of the XPage is configured properly in the Server Document, then the XPage can be tested by launching the XPage from the “Preview in Browser” action as well.

55

Configuring Additional Test Browsers

Additional test browsers can be configured in the Designer Preferences

Initial Home Page

Should look similar to this Note the blue and black

banner bars on the top – That styling is thanks

to our theme Note the “Login” and

links on the bottom of the page

– Those elements are from the layout control

Summary

We have an Application in progress We inherited some forms and views from the starter database We setup our application properties

– We added a theme and set the default home page Created a custom control for our application layout Created a home page and added the layout control Added a panel - which will render as an html <div> to the main body and added some content Tested in the browser

Next Up

Create Custom Control for the Help Ticket Create Custom Control to View tickets Create a Custom Control for the Navigation menu list

Create Custom Control for Ticket

New Custom Control - Name it cc_Ticket Note we’re using a prefix to separate controls for layout from other custom controls

Create Data Bindings We want to bind this control to a document

– As mentioned earlier, data and UI have been separated • Data in the document, UI on the XPage

– Binding allows us to put them back together however we want • i.e. we can have multiple data sources on a single XPage

In properties Data Tab - Add - Domino Document

Create Data Binding ...

Select form_ticket and name the data source ticketDoc – Unless there will be multiple data sources it is a BEST PRACTICE to leave the document data source

name as “document1”

Add Code to the beforePageLoad Event

This will allow us to pre-populate fields and scoped variables – Click anywhere in the editor white space in the Design tab – Click on the “Events” tab – Select the beforePageLoad event in the left navigator

Add Code from Script Snippets

This code creates a unique key and Date for a new document It also puts the key field into viewScope memory for later use

Here’s How this Code Looks in Source Note the tag and use of JavaScript inside the curly braces

– Comments describe the code

<xp:this.beforePageLoad><![CDATA[#{javascript:if (ticketDoc.isNewNote()) { // If this is a new document - generate a unique key var tempKey = session.evaluate("@Unique"); // Add the unique key to the document itself ticketDoc.replaceItemValue("ticketKey", tempKey ); // Add the key to viewScope so we can use it later as needed viewScope.put("vsTicketKey", tempKey); // Set the ticket Date to current Date/Time ticketDoc.setValue("ticketDate", @Now()); } else { // This is not a new document so retrieve the key and put in viewScope viewScope.put("vsTicketKey", ticketDoc.getItemValueString("ticketKey")) }}]]></xp:this.beforePageLoad>

Populating Fields the Quick Way

We could go to the Data tab and drag the fields in. This would create a table (we’ll see an example of this later). But for a better UI we will use more controls from Extension Library.

Adding Fields to Your Page

Drag the FormTable control to your control FormTable contains formRow and can also optionally contain formColumn tags This gives you a nice CSS styled layout of your labels and fields

– Without needing to know or change CSS (although you can change it if you want to)

Update Label Position From the Form Table’s All Properties panel, change the labelPosition to “left” This will allow you to move all labels later if desired with one click (rather than one for each label)

– Note other properties like formTitle

Add Title to Form Table

Select the Form Table Add the formDescription and formTitle

Drag Form Layout Row onto Form Table Body’s Green Dot

This creates one row that will contain a label and a field, automatically

Adjust Label Placement on the Row

From the Form Layout Row, change the labelPosition to “inherit” Changing the label position will now be one click on the Form Table (the one we just set to “left”)

Check the Source

Set up the First Form Layout Row

Set Label to “Ticket ID:” Drag Computed Field to right most Green Dot

Bind Computed Field to “ticketKey” Field

Check the Source

Note: This is a formRow inside a formTable tag. We are about to add multiple rows To get multiple fields on a row there is also a formColumn tag which allows you to add more columns.

This app does not use Columns.

<xe:formTable id="formTable1" labelPosition="left"> <xe:formRow id="formRow1" labelPosition="inherit" label="Ticket ID"> <xp:text escape="true" id="computedField1" value="#{ticketDoc.ticketKey}"> </xp:text> </xe:formRow> </xe:formTable>

Add the Ticket Date Field We will continue filling out the fields for the ticket form. Same principle but not all will use the computed

field control. Most we want editable. Next add the date field by starting to paste this under the last </xe:formRow> tag in source This is the row for “ticketDate”

<xe:formRow id="formRow2“ label="Date" labelPosition="inherit"> <xp:text escape="true" id="computedField2" value="#{ticketDoc.ticketDate}"> <xp:this.converter> <xp:convertDateTime type="date" dateStyle="short"> </xp:convertDateTime> </xp:this.converter> </xp:text> </xe:formRow>

Changing the Display Properties

The source code on the previous slide contains a converter. This is represented in the GUI design on the value tab and the display type

Add the Caller Name Field Note the use of the Name Picker <xe:namePicker> control

– The “for” of the namePicker needs to match the ID of your Target control – Typically NamePickers require you to be logged in to work since your address book likely has higher

security

<xe:formRow id="formRow3“ label="Caller“ labelPosition="inherit"> <xp:inputText id="inputText1" value="#{ticketDoc.ticketCaller}"> </xp:inputText> <xe:namePicker id="namePicker1" for="inputText1" dialogTitle="Select the caller"> <xe:this.dataProvider> <xe:dominoNABNamePicker> </xe:dominoNABNamePicker> </xe:this.dataProvider> </xe:namePicker> </xe:formRow>

Combo Boxes

We’re about to add several Combo boxes You can hard code values, compute values, or do a combination If you use @DbColumns() or @DbLookups() to get the values watch out for the 64k limitation that they still

have

Add Ticket Category This is a combo box. Note there is Server Side JavaScript Code for looking up the values

<xe:formRow id="formRow6“ label="Category“ labelPosition="inherit" for="category1"> <xp:comboBox id="category1" value="#{ticketDoc.ticketCategory}"> <xp:selectItems> <xp:this.value><![CDATA[#{javascript://We start with a blank array and concat choices, so the first item in the list is blank. //that way, we can validate whether or not the user made a selection var mychoices = new Array(""); var mydb = new Array(database.getServer(),database.getFilePath()); var myotherchoices = @DbLookup(mydb, "vwKeywords", "category", 2); var mytotalchoices = mychoices.concat(myotherchoices); return mytotalchoices; }]]></xp:this.value> </xp:selectItems> </xp:comboBox> </xe:formRow>

ComboBox Code Should Look Like This:

More Combo Boxes

We’re going to do three more combo boxes for Platform, Priority, and Status – They will work exactly the same. The only difference is the field we’re binding to and the keyword that

we pass into the view

Now Add the Row for Platform

Note the change in value for each field, and different keyword in the DbLookup

83

<xe:formRow id="formRow7" label="Platform:" labelPosition="inherit" for="platform1"> <xp:comboBox id="platform1" value="#{ticketDoc.ticketPlatform}"> <xp:selectItems> <xp:this.value><![CDATA[#{javascript://We start with a blank array and concat choices, so the first item in the list is blank. //that way, we can validate whether or not the user made a selection var mychoices = new Array(""); var mydb = new Array(database.getServer(),database.getFilePath()); var myotherchoices = @DbLookup(mydb, "vwKeywords", "platform", 2); var mytotalchoices = mychoices.concat(myotherchoices); return mytotalchoices;}]]></xp:this.value> </xp:selectItems> </xp:comboBox> </xe:formRow>

Now Add the Row for Priority Note the change in value for each field, and different keyword in the DbLookup

84

<xe:formRow id="formRow8" label=”Priority:" labelPosition="inherit" for=”priority1"> <xp:comboBox id="platform1" value="#{ticketDoc.ticketPriority}"> <xp:selectItems> <xp:this.value><![CDATA[#{javascript://We start with a blank array and concat choices, so the first item in the list is blank. //that way, we can validate whether or not the user made a selection var mychoices = new Array(""); var mydb = new Array(database.getServer(),database.getFilePath()); var myotherchoices = @DbLookup(mydb, "vwKeywords", "priority", 2); var mytotalchoices = mychoices.concat(myotherchoices); return mytotalchoices;}]]></xp:this.value> </xp:selectItems> </xp:comboBox> </xe:formRow>

Now Add the Row for Status Note the change in value for each field, and different keyword in the DbLookup

<xe:formRow id="formRow9" label=”Status:" labelPosition="inherit" for=“status1"> <xp:comboBox id="platform1" value="#{ticketDoc.ticketStatus}"> <xp:selectItems> <xp:this.value><![CDATA[#{javascript://We start with a blank array and concat choices, so the first item in the list is blank. //that way, we can validate whether or not the user made a selection var mychoices = new Array(""); var mydb = new Array(database.getServer(),database.getFilePath()); var myotherchoices = @DbLookup(mydb, "vwKeywords", "status", 2); var mytotalchoices = mychoices.concat(myotherchoices); return mytotalchoices;}]]></xp:this.value> </xp:selectItems> </xp:comboBox> </xe:formRow>

Add A Default Value for the Status ComboBox

Select the status field On the Data tab, enter “Open” for the default value

Add the Description Row

Note the “style” line - this is to make the size of the field wider – Any style markup on the control overrides the theme

<xe:formRow id="formRow10" label="Description" labelPosition="inherit"> <xp:inputTextarea id="ticketDescID" value="#{ticketDoc.ticketDescription}" style="width:60%;height:3em"> </xp:inputTextarea> </xe:formRow>

When all that is done your design screen looks like:

Add a Tool Tip

This is a common Dojo element made easy with the Extension Library – Drag a Tooltip below your form table layout

Configure ToolTip

Enter the Label of the Tooltip Enter the “for” value. This is the ID of your control for the field “ticketDescription”

– Note - it’s the ID of the control - not the name of the field

Adding Buttons to the Form Table

The formTable contains a footer facet. Drag a Panel onto the green dot.

Note what the change looks like in source. We’ll be working here for the buttons by adding code inside the <xp:panel> tags

Adding the Save Button

Inside the new Panel drag a button to the panel

// Hide button if it's in save mode return ticketDoc.isEditable();

We only want to show this button if in edit mode. Click the blue diamond to compute the rendered property. Then add the code.

Save Button Properties

We can compute whether or not the button is visible Either enter the code in the source pane, or click the blue diamond next to “Visible” on the Button tab, or

click the blue diamond next to “rendered” on the All Properties tab – The “Pretty Panes” contain common properties. All Properties contain everything

Save Button Properties ...

In order to make the button *do* something, click on the Events tab of the button Click “Add Action...”, change the Action to “Save Document” and the Data source name to “ticketDoc”

Adding the Close Button from Source

Next, inside the same panel under the </xp:button> add the code below – Or you could drag another button, set the label to “Close” and do the Open Page Simple Action

<xp:button value="Close" id="button2"> <xp:eventHandler event="onclick" submit="true" refreshMode="complete"> <xp:this.action> <xp:openPage name="$$PreviousPage"></xp:openPage> </xp:this.action> </xp:eventHandler> </xp:button>

Adding the Edit Button via Source Note as we’ve seen before we’re computing when to render this button

– the “!” in the beginning reverses the True/False value – We want a false if the ticketDoc is editable

<xp:button value="Edit“ id="button3"> <xp:this.rendered> <![CDATA[#{javascript:// Hide button if it's in edit mode !ticketDoc.isEditable()}]]></xp:this.rendered> <xp:eventHandler event="onclick“ submit="true“ refreshMode="complete"> <xp:this.action> <xp:changeDocumentMode mode="edit" var="ticketDoc"> </xp:changeDocumentMode> </xp:this.action> </xp:eventHandler> </xp:button>

Forcing a Space

In the source pane, after each button tag, add &#160; This forces a space Alternately in the design pane add the space using <ctrl><space> keyboard combination

</xp:button> &#160;

cc_Ticket Status Check

Should look like this. Don’t forget to save!!

Summary

Created Ticket Custom control – Used computed Fields, Edit Box, ComboBox, and Multi-line Edit box

• Created Lookups for our comboboxes • Added some basic CSS to style a field

– Used Form Rows to give us a nice layout Created Save, Close and Edit buttons

– Added appropriate rendering

99

Create a Custom Control to View Tickets Create a new custom control as before. Call it cc_Tickets and go to the beforePageLoad event Add via Script Editor: viewScope.put(“vsStatus”, “Open”)

– This is an in memory scoped Variable that will live for the life of the page. We’re setting the default status we want to see to “Open”.

100

Add A Panel To Select Type of Tickets

Drag a Panel onto the page. – Give it the ID of “statusPanel” – Could also be added directly in source after the beforePageLoad tag

<xp:panel id="statusPanel"> </xp:panel>

101

Inside the Panel add a Combobox

This gets all the tickets’ status values and returns them as options for the user to select from We will bind the value of the Combo Box to the viewScope var we set earlier Once a value is selected (“onchange”) the panel containing the view (“statusPanel”) will get refreshed This time we’re mixing a hard coded option of “Choose Status” which is the default value with

@DbColumn code – To get our status we’ll lookup from existing tickets and using @Unique() to return one value for each

status – The reason for this is to only show statuses where we have actual data

Every time the Combo Box is changed a partial refresh is triggered on the panel

102

Inside the Panel add a Combobox <xp:comboBox id="comboBox1“ value="#{viewScope.vsStatus}">

<xp:selectItem

itemLabel="&lt;&lt;Choose Status&gt;&gt;"></xp:selectItem>

<xp:selectItems>

<xp:this.value><![CDATA[#{javascript:// Not the most robust solution. Has a 64K limit and some other issues

// But @Formulas still work in XPages

@Unique(@DbColumn("","vwTicketsByStatus",1));}]]></xp:this.value>

</xp:selectItems>

<xp:eventHandler event="onchange“ submit="true“ refreshMode="partial"

refreshId="statusPanel">

</xp:eventHandler>

</xp:comboBox>

103

Add the View Drag the Container Control “View” onto the Design pane inside Panel The “Select Data Source for View” dialog appears Set the view to be: vwTicketsByStatus Deselect $5 UNID - we don’t want to display it

104

View Control on Your Page

The view is automagically created, including a pager

105

Add a Checkbox to the First Column

Select the first column Display Tab - select “Check box” - then Save the custom control

106

Customize the CSS on the View

From Resources, Style Sheets, click New Style Sheet Called “application.css” Save and close

107

Adding CSS Add the following code Save and close These classes will add shading to the odd rows The “HOVER” classes add different shading (and font color and weight) when the mouse hovers over the

rows .oddRow { BACKGROUND-COLOR: RGB(248, 248, 248); } .oddRow:HOVER { BACKGROUND-COLOR: RGB(98, 120, 150); color: #FFFFFF; font-weight:bold; } .evenRow:HOVER { BACKGROUND-COLOR: RGB(98, 120, 150); color: #FFFFFF; font-weight:bold; }

108

Add the New CSS Resource to Your Custom Control

Include the style sheet as a resource on your custom control Note: Since this CC will always be shown inside of “layout_Main” you could also add it there. Then it

would be available for any future Custom Controls or XPages

109

Customize the CSS on the View On the cc_Tickets custom control, select the View Panel On the All Properties tab, enter “oddRow, evenRow” to rowClasses That’s it! Just like the styling markup directly on our description field overrides the theme, our CSS

resource applied to the control also overrides or “extends” the theme

110

Adding Buttons to Work against Selected Documents

We’re going to add buttons for: – Delete – Close – Waiting – ReOpen

We’re going to create a single custom control for the buttons and keep all our code in one place – We will create a script library to hold this code.

We’re going to pass in properties at runtime to control the buttons

111

Create a SSJS Script Library

Code - Script Library - New Script Library – Make sure to choose Server JavaScript – We’re going to add functions that we’ll use shortly

112

Add Function for getSelected

This function will return an array with the selected documents’ IDs

function getSelected(viewName:string) { // Pass in the name of a viewPanel and return the selected ID's as an array print("Running Array") var viewPanel=getComponent(viewName); // this gets a hold of the viewPanel var docArray = viewPanel.getSelectedIds(); // This gets the array of selected documents return docArray }

113

Add Function for processDocuments function processDocuments(action:string, array) { //Based on the Action that's passed in, update the documents // Loop through all the documents var doc:NotesDocument print("Length: " + array.length) for(i=0; i < array.length; i++) { var docId=array[i]; doc = database.getDocumentByID(docId); // Switch is like a "Select Case" in LotusScript switch(action) { case "Delete": doc.removePermanently(true); break; case "Close": doc.replaceItemValue("ticketStatus", "Closed"); doc.save(); break; case "Waiting": doc.replaceItemValue("ticketStatus", "Waiting on User") doc.save(); break; case "Open": doc.replaceItemValue("ticketStatus", "Open"); doc.save(); break; default: print("should Never get here"); } } doc.recycle() }

114

Add Function for getTicketCounts function getTicketCounts() { // Return a Map of the ticket types and counts // TreeMap is different then HashMap as it's Sorted by the key value var ticketMap:java.util.TreeMap = new java.util.TreeMap(java.lang.String.CASE_INSENSITIVE_ORDER); var myView:NotesView = database.getView("vwticketsByStatus"); var vec:NotesViewEntryCollection = myView.getAllEntries(); var entry:NotesViewEntry = vec.getFirstEntry(); var tmpEntry:NotesViewEntry = null; // We need some temp. variables var tmpStatus:string = ""; var tmpCount:integer = 0; while (entry != null) { tmpEntry = vec.getNextEntry(); // Get the current Ticket Status - Using first column value of the view. // This is faster then getting the actual NotesDocument tmpStatus = entry.getColumnValues()[0] // Get the count from the map for the current status tmpCount = ticketMap.get(tmpStatus) // Now add back to the Map the new count ticketMap.put(tmpStatus, tmpCount + 1) // Recycle because Admins don't appreciated it when the server crashes. entry.recycle(); entry = tmpEntry; } return ticketMap; }

115

Looking at the SSJS Library

The first 2 functions should look like this:

116

Save Script Library and Exit

XPages and Custom Controls can access Script Libraries as resources. We will add it to the control later.

117

Create Button Custom Control

Create a New Custom Control call it btn_ProcessDocuments

118

Add the Property Definitions Find Property Definition under the Properties Tab.

– Add a “New Property” for viewPanelName, action, and buttonName – Each type should be string

Property definitions are items for passing in information to a custom control – We will pass in information like “action” and our script will take that information and determine what

will happen when the button is clicked – This is what allows the same custom control to be used for our different buttons

119

Adding a Script Library In the Resources tab, click “Add” and select “Javascript Library” Then select the SSJS Utilities JavaScript library

<xp:this.resources> <xp:script src="/SSJS Utilities.jss" clientSide="false"> </xp:script> </xp:this.resources>

120

Add a Button to the Control

compositeData is an object available to SSJS of all the properties and values Use “compositeData” from the property definitions created earlier, to get the name of the button

<xp:button id="button2" value="#{javascript:return compositeData.buttonName}"> </xp:button>

121

Finishing the Button In the “onclick” event call code in the script library to process documents Save and Close

<xp:eventHandler event="onclick" submit="true" refreshMode="complete"> <xp:this.action> <![CDATA[#{javascript:var array = getSelected(compositeData.viewPanelName); processDocuments(compositeData.action, array)}]]> </xp:this.action> </xp:eventHandler>

122

What Does that Code Do?

compositeData is an object that lets you access the custom properties – These properties will be set later when the custom control is added to an XPage or other custom

control We will compute the label for the button at run time.

– Example we might want the buttons to show different languages We will use the viewPanel name to determine the selected documents We then use the action parameter to pass in the selected documents and desired action to our script

library

123

Add the Button Custom Control to cc_Tickets

Open the cc_Tickets Custom Control that was created earlier Above the view panel add button custom control

124

Updating the Custom Properties Adding values to the Custom Properties allows the control to be customized for each instance

– Remember we created the Property Definitions earlier, this is where we input the values for this specific instance

125

Use The Source, Luke Use Source to quickly Add Buttons for setting the ticket status to: close, Waiting, and Open

– Note forced spaces in between for niceness

&#160; <xc:btn_ProcessDocuments action="Close“ buttonName="Close Tickets" viewPanelName="viewPanel1"> </xc:btn_ProcessDocuments> &#160; <xc:btn_ProcessDocuments action="Waiting“ buttonName="Set to Waiting" viewPanelName="viewPanel1"> </xc:btn_ProcessDocuments> &#160; <xc:btn_ProcessDocuments action="Open“ buttonName="ReOpen"> <xc:this.viewPanelName><![CDATA[#{javascript:"viewPanel1"}]]> </xc:this.viewPanelName> </xc:btn_ProcessDocuments>

126

Status Check: cc_Tickets Should Now Look Like This:

Since the labels are computed they don’t show at design time but will render correctly

127

Summary

Created a custom control to show/edit Tickets – Used a viewScope variable to set some defaults – Used formTable and formRow to display the fields and labels – Added a tool tip – Added buttons to save and edit and close the ticket

Created a custom control to view tickets – Used the View control

Created a Script Library to hold three SSJS functions Created a custom control for a button

– Allows passing parameters in at runtime via properties – compositeData object

128

Next

Add the Ticket and Tickets custom controls to XPages Add to Navigation Create additional supporting Pages

129

Create Ticket XPage

XPages - New XPage. Name the XPage “ticket”. Click OK.

130

Drag In the Controls for the Ticket XPage

Drag the layout_Main custom control onto the blank page Drag the cc_ticket control into the middle facet target

131

The Controls for the Ticket Xpage - Source The Source Pane will look like this. Save and Close.

132

Create the Tickets View XPage

Just like creating the “ticket” XPage, create one for “tickets”

XPages - New XPage Title the XPage “tickets” Drag the layout_Main onto the page Drag the cc_tickets custom control onto the

middle facet target Save and Close

133

Test

Open the tickets XPage Open the ticket XPage Preview both in browser

134

Create a New Ticket via a Button on Placebar

Open the “layout_Main” custom control to edit Click on the Application Layout to select it in the Properties panel Click on the Place Bar tab, click Add Item, and select “Page Link Node”

135

Create a New Ticket via a Button on Placebar...

Fill in the label field and select the “ticket” page to open

136

Create a New Ticket via a Button on Placebar...

Hide the button when the user is on the Ticket page Click the empty blue diamond next to “rendered” and select “Compute value...”

137

Create a New Ticket via a Button on Placebar...

Enter the following Server Side Javascript and click OK – This will display the button only if the user is on the ticket.xsp XPage

var url = context.getUrl(); if(@Contains(url, "ticket.xsp") == true) { return false; } else { return true; }

138

Nav Bar...

Create a new CC called layout_Nav to hold the applications navigation menu

139

Nav Bar...

Drag Navigator into Design Page

140

Adding Home to the Nav Bar

Go to properties for the navigator Navigation Items - Click Add Item - Choose Page Link Node Set Label to Home and chose home in the page dropdown

141

Adding Tickets to the Nav Bar

Go to properties for the navigator Navigation Items - Click Add Item - Choose Page Link Node Set Label to Tickets and chose tickets in the page dropdown

142

Add the Nav Bar to the Layout

Open the custom control created earlier, “layout_Main” Drag the custom control just created (“layout_Nav”) and drag it into the left-hand target of the main layout

143

Create a Keywords “Form”

Create the custom control for the “form” Custom control - New Custom Control - Name it “cc_keyword_form” Click on the “Data” tab Add the keyword form as the data source

144

Create a Keywords “Form”...

Select the two fields and drag them onto the control Select the “Add Submit button to generated code” option

145

Get the viewScope to Know Which Document to Open Click on the data tab Change the default action to “Edit document” Input viewScope.get(“selectedKeyword”) into the editor

146

Create a Keywords “View”

Create the custom control for the “view” Custom controls - New Custom Control -

“cc_keyword_view” Drag the Container Control “View” onto the Design

pane The Select Data Source for View dialog appears,

use the “vwKeywords” view for the source

147

Create a Keywords “View”... Click on the first column to select it Click on the events tab In the server side script editor for the on click event, enter

– viewScope.put("selectedKeyword",rowData.getUniversalID()); – This sets the viewScope used by the “form”

148

Create a Keywords XPage for Form and View Together

Setting the viewScope on the “view” when the user clicks a row allows the “form” to know which document to open for editing on the page

– Set the viewScope with the doc ID of the selected row – Get the doc ID from the viewScope – Have the form use the doc ID to know which doc to edit

149

Create a Keywords XPage for Form and View Together...

Create the keywords XPage XPages - New XPage - named “admin”

150

Create a Keywords XPage for Form and View Together...

Drag the “layout_Main” control onto the page Drag a panel container control into the middle facet

151

Create a Keywords XPage for Form and View Together...

Drag the “cc_keywords_form” and “cc_keywords_view” controls into the panel

152

Create a Keywords XPage for Form and View Together...

Use the Outline to organize elements

153

Adding the Keywords Tab for Navigation Open the “layout_Main” custom control Click on the Title Bar tab Click Add Item, choose a Page Link node Change the label to “Home” and select the home page from the dropdown for page

154

Adding the Keywords Tab Repeat those steps to add another page link node Call it “Admin” and select the admin page for the page You now have a different way of navigating the application You can set the “render” property to hide the Admin tab if appropriate

155

CRUD

At this point, we can: – Create tickets (placebar button) – Read tickets (tickets view) – Update tickets (ticket custom control) – Delete (custom control button)

156

Agenda

Who We Are What We Are Building What Are XPages? Creating the Application Refining the Application

157

Refining the Application

Adding Comments via Repeat Control Login/Logout Workaround Validation

158

Adding a Repeat Control

Create a new Custom Control – Name: “cc_CommentView” – Data source: Domino View, “vwCommentsByKey”

Add a panel to the control Drag a Repeat Control into the panel

159

Binding the Repeat Control

Give the collection a name: “commentData” – This is allows us to “call” the data and do something with it

Bind the repeat control: This creates the collection of entries that our repeat control will use

var cView:NotesView = database.getView("vwCommentsByKey"); var vec:ViewEntryCollection = cView.getAllEntriesByKey(compositeData.ticketKey, true) return vec

160

Displaying the Repeat Control Drag a table into the Repeat Control

– 1 row, 4 columns: 3 computed fields in the 2nd, 3rd, and 4th cell Into the first cell, drag another table

– 2 rows, 2 columns: 2 labels in top row, “Hours” & “Minutes”; 2 computed fields in bottom row

<xp:table> <xp:tr><xp:td><xp:table><xp:tr> <xp:td> <xp:label value="Hours" id="label1"></xp:label> </xp:td><xp:td> <xp:label value="Minutes" id="label2"></xp:label> </xp:td> </xp:tr><xp:tr> <xp:td></xp:td><xp:td></xp:td></xp:tr></xp:table></xp:td> <xp:td></xp:td> <xp:td></xp:td> <xp:td></xp:td> </xp:tr> </xp:table>

161

Adding Fields to the Repeat Control

Now the cool part! Add a computed field to the cell below “Hours” Bind the data:

– commentData.getColumnValues()[4] This uses the collection created when we bound the repeat control as our “view”, binding this computed

field to the column value and displaying it inside the repeat control will automagically display each “record” once in a panel, repeated on the page

Add the rest of the computed fields and bind them per the script snippet

162

Looking at the Repeat Control

Becomes this

This

163

Validation

Validation can be found in two different places on a control, depending on the type of control.

164

Validation

Click on the Ticket Caller edit box. Simple validation can be added on the Validation tab. Select the check box next to “Required field”. Enter “Enter a ticket caller” for the error message.

165

Validation

Select the Ticket Priority field On the All Properties tab, click the plus sign next to “validators” Select “xp:validateRequired”

166

Validation

Click the dropdown next to “loaded” and select “true” Enter the message “Select a ticket priority” in the message field

167

Validation The previous steps are all that is needed for validation However, we can improve validation by adding nicer error messages Drag the Display Error control to the ticketCaller row In the Display Error tab select the ticketCaller field to “Show error messages for” Repeat for other rows with field validation

168

Validation

In order for the Display Error controls to work, client side validation needs to be disabled Go to Application Properties, XPages tab Select “Off” for Client Validation

169

Validation

By default this will create table errors and row errors, in addition to the error message control Click on the Form Table control, go to All Properties and set “disableErrorSummary” and

“disableRowError” to “true”

170

File Upload

Add another Form Layout Row, label it “File Upload” Drag the “File Upload” control onto the custom control and bind the field to the “ticketFiles” field

171

File Upload

The Source pane for the file upload control

File Upload - FYI

Prior to 9.0.1 the page would require a full refresh on save in order to save and retain the attachment 9.0.1 includes a bug fix that allows partial refresh to save attachments

173

File Download Create another form row Drag the File Download control onto the row Make the following selections

174

Reference

Suggested sessions – AD201 : IBM Domino Application Development: Today and Tomorrow – JMP101 : Java for XPages Development – BP202 : Rapid XPages Development Using the Application Layout Control – Many Many more....

Useful links – XPages.info – OpenNTF.org

• http://openntf.org/XSnippets.nsf – notesin9.com – XPagesWiki.com – http://www-10.lotus.com/ldd/xpagesforum.nsf – http://stackoverflow.com/questions/tagged/xpages

Access Connect Online to complete your session surveys using any: – Web or mobile browser – Connect Online kiosk onsite

8

176

Acknowledgements and Disclaimers

© Copyright IBM Corporation 2014. All rights reserved.

U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

IBM, the IBM logo, ibm.com, are trademarks or registered trademarks of International Business Machines Corporation in the United States, other countries, or both. If these and other IBM trademarked terms are marked on their first occurrence in this information with a trademark symbol (® or ™), these symbols indicate U.S. registered or common law trademarks owned by IBM at the time this information was published. Such trademarks may also be registered or common law trademarks in other countries. A current list of IBM trademarks is available on the Web at “Copyright and trademark information” at www.ibm.com/legal/copytrade.shtml

Availability. References in this presentation to IBM products, programs, or services do not imply that they will be available in all countries in which IBM operates.

The workshops, sessions and materials have been prepared by IBM or the session speakers and reflect their own views. They are provided for informational purposes only, and are neither intended to, nor shall have the effect of being, legal or other guidance or advice to any participant. While efforts were made to verify the completeness and accuracy of the information contained in this presentation, it is provided AS-IS without warranty of any kind, express or implied. IBM shall not be responsible for any damages arising out of the use of, or otherwise related to, this presentation or any other materials. Nothing contained in this presentation is intended to, nor shall have the effect of, creating any warranties or representations from IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement governing the use of IBM software.

All customer examples described are presented as illustrations of how those customers have used IBM products and the results they may have achieved. Actual environmental costs and performance characteristics may vary by customer. Nothing contained in these materials is intended to, nor shall have the effect of, stating or implying that any activities undertaken by you will result in any specific sales, revenue growth or other results.