UI Service Methods - imona/tutorial GitHub Wiki

UI Services

Events are mostly vital in a business app and makes users comfortable and eases their job when they are using the business app. In Imona Cloud, we give developers the option to define their own UI services, that these services will turn to an event and run the service when user do a specific action.

Right now, we support four basic actions that can be done on an entity page:

  • On Load Action: is triggered when an entity page is loaded
  • On Edit Action: is triggered when an entity page is in edit mode
  • On Submit Action: is triggered when an entity page form is submitted
  • On Add Action: is triggered when an entity page form is created

The beauty in here is, you can write any service you want into these actions. For example, if you want to send a mail or SMS after a form is submitted, simply you write the service into on Submit Action of that entity and all is set.

Of course, you have to be in Edit Mode in order to change the structure of an entity page. (and yes, you are changing the structure when you add an action to the page) After getting into the edit mode (click edit layout button in Developer Tools tab), right click on an empty area of the entity page will show you couple of options to choose and if you look closely, there is a Services option at there. Thus, you can click one of the onLoad, onEdit, onSubmit, onAdd option and you will be welcomed with a service script editor.

There are various methods available to developer, and you can access those methods by clicking CTRL+SPACE. For example;


Note: Usage examples marked with asteriks,you can find the examples at the end of related code block.


**ACCESSING THE CURRENT PAGE PROPERTIES**
current //can access properties of the current page
user  // you can access the logged in user
organization  // you can access the current organization
getDepartments(); // Returns the list of department names of the organization.
getRoles(); // Returns the list of role names of the organization. 
getUsers(); // Returns the list of usernames of the organization. 
getUserInfo(userId (String)); // Returns information for the user with the given id. 
isPopup(); // Returns true if current window is popup.

**APIs**
asyncCall(backgroundFunction (String), uiFunction (String));
callService(serviceName (String), requestObject (Object)); // Calls the service with given name.
callWebService(wsMessageName (String), vars (Map)); // Calls the defined web service with given service name    and parameter/value set. Service must be defined in "WS Messages" menu and parameters can be accessed in the web service script with a preceding "$" character, eg. $param1. Return value will be the response of the web service.
callRestService("http://sampleurl.com/example?param={urlParameterKey1}", "POST") // Prepares a http (REST)    call to the given url and the HTTP method. HTTP headers, URL parameter encoding, basic authentication and request body (only for PUT and POST) can be set. Additional parameters can be provided with builder methods.Returned object from the REST call, null for PUT and DELETE. If result is JSON, it will be converted to an object. Otherwise result will be a String.
.withBasicAuth("username", "password")
.withHeader("headerKey1", "headerValue1")
.withHeader("headerKey2", "headerValue2")
.withUrlParameter("urlParameterKey1", "urlParameterValue1")
.withRequestBody(someObject)
.perform();  
createVideoSession(apiKey (int), apiSecret (String), timeoutMinutes (int)); // Creates a video session and  returns the session id and authentication tokens. // Returns: HashMap with sessionId, subscriberToken, publisherToken.
parseHtml(html (String), cssQuery (String)); // Parses the html with given css query and returns the output as a list of string array. 
parseResponse(message (String), xpathExpr (String)); // Parses the given response message with the Xpath expression provided. 
parseResponse(message (String), xpathExpr (String), returnAsList (boolean)); // Parses the given response message with the Xpath expression provided.
throwRestServiceError(code (int), message (String)); // Throws a rest service error to user. 
getOrgWebsiteUrl(); // Returns current organization's website URL.
getPlatformBaseUrl(); // Returns the base url for the current platform. 
getPlatformRestUrl(); // Returns the rest url for the current platform. 

**ALGEBRA**
convertToDouble(value (Object));
Converts the given number or string to double.  
formatCurrency(number (BigDecimal)); // Formats the currency value as text.
spellCurrency(number (Number), currency (List), cent (List)); // Returns the spelling of the given currency. 
spellNumber(number (Number)); // Returns the spelling of the given number.

**CONFIRMATION DIALOG**
confirm(onAcceptServiceName (String), onRejectServiceName (String), languages (String[])); // Pops up a confirmation dialog to the user, proceeds with given confirm or reject service according to user's choice.

***DATE OPERATIONS***  
addDay(date (Date), amount (Integer)); // Adds the given amount of days to the given date and returns the new  date.
addMonth(date (Date), amount (Integer)); // Adds the given amount of months to the given date and returns the new date.
addYear(date (Date), amount (Integer)); // Adds the given amount of years to the given date and returns the new date.
daysBetween2Dates(date1 (Date), date2 (Date)); // Calculates the day number between two given dates.
daysInMonth(month (Integer), year (Integer)); // Returns the day number in a given month and year.
findMaxDate(dates (Date[])); // Returns the latest date of given two dates.
*formatDate(datePattern, date); // Adds the given amount of days to the given date and returns the new date.
getDay(date (Date)); // Returns the day value of the month in the given date.
getMonth(date (Date)); // Returns the month value of the year in the given date.
getYear(date (Date)); // Returns the year value in the given date.
time(); // Returns the current time.
toDate(date (String)); // Returns a new date from the given string which is formatted as "dd.MM.yyyy".
toDate(date (String), datePattern (String)); //Returns a new date from the given string which is formatted as the given pattern.
toDateFromEpoch(epoch (long)); // Returns a new date from the given epoch date which is a number.
toDateFromTimestamp(timestamp (long)); // Returns a new date from the given timestamp (milliseconds since epoch) which is a number.
today(); // Returns the current date.
validateAGivenDate(dateString (String)); // Validates a given string as a date.

Examples:

var zk = today();
formatDate("dd.MM.yyyy", zk);**
In order to receive required values from this format, we can use simple method;
formatDate("dd.MM.yyyy", date);** where "date" is the Date Object.

**DATABASE OPERATIONS**
find(key (String), entityName (String)); // Finds and returns the given bean with the key on the given entity.
deleteItem(item (Object)); // Deletes the given item(s) or record(s) from database. Note that in entity list  tables, deleted record remains on table unless table is refreshed.
deleteSelectedItem(fieldName (String)); // Deletes the selected item in the given field. Field must be embeeded table. Note that deleteSelectedItem is a database operation and does not work for entity list tables.
deleteViaQuery("from Customer where name = 'emre'") // Executes the given delete query with parameters.
query(hql (String)); // Executes the given query for entity objects.
query(hql (String), args (Object[])); // Executes the given query, substituting ?'s with actual parameters.
query(hql (String), firstResult (Integer), maxResults (Integer), args (Object[])); // Executes the given query for entity objects.

**EMAIL OPERATIONS**
getImapEmails(username (String), password (String), imapHost (String), markAsRead (boolean)); // Retrieves   unread emails from an inbox using given parameters.
getImapEmails(username (String), password (String), imapHost (String), markAsRead (boolean), useSsl (boolean),  includeFile (boolean)); // Retrieves unread emails from an inbox using given parameters.
getImapEmails(username (String), password (String), imapHost (String), markAsRead (boolean), useSsl   (boolean)); // Retrieves unread emails from an inbox using given parameters.
getPop3Emails(username (String), password (String), host (String), port (int)); // Retrieves emails from an  inbox using given parameters.
sendEmail(to (String), subject (String), content (Object)); // Sends an e-mail to a recipient with specified subject and content text. Content type is HTML. Note that organization email settings must be defined to use this function. 
sendEmailFrom(userName (String), password (String), smtp (String), port (int), useSsl (boolean), to (String), subject (String), content (Object)); // Sends an e-mail from a specified smtp host to a recipient with given subject and content text. Content type is HTML. SMTP host, userName, password and port must be provided. 
sendEmailWithImage(tos (List), subject (String), body (Object), imgs (List)); // Sends and e-mail to a recipient with specified subject and body text, adds an image in the attachments. Image type parameter must be passed to this method or images can be embedded into body message by putting <img src="cid:image{#no}"> into any place of body. Image no begins from 0 index.
sendEmailWithReportExcel(entityName (String), data (List), visibleColumns (List), fileName (String), to (String), subject (String), body (String)); // Sends an e-mail to a recipient with specified subject and body text, adding an Excel spreadsheet file with the given name to the attachments which is created using the given data under specified columns. 
sendEmailWithReportPDF(entityName (String), template (Object), data (List), fileName (String), to (String), subject (String), body (Object)); // Sends an e-mail to a recipient with specified subject and body text, adding a PDF file with the given name to the attachments which is created from the specified report template and using the given data 
sendEmailWithReportPDF(templateName (String), data (List), fileName (String), to (String), subject (String), body (Object)); // Sends an e-mail to a recipient with specified subject and body text, adding a PDF file with the given name to the attachments which is created from the specified report template and using the given data. Note that report template must be uploaded to use this method 
sendEmailWithReportPDF(templateName (String), data (List), params (Map), fileName (String), to (String), subject (String), body (Object)); // Sends an e-mail to a recipient with specified subject and body text, adding a PDF file with the given name to the attachments which is created from the specified report template and using the given data. Note that report template must be uploaded to use this method. 
validateEmail(email (String)); // validateEmail(email (String)); // Validates a given string as a date.

**FIELD OPERATIONS**
getComponent(id (String)); // Returns component with given id / name. Various operations can be made on/for component after calling this method. Functions that are valid for the component can be displayed on suggestions      after calling the method.
isVisible(fieldName (String)); // Returns true if given field is visible.
setFocus(fieldName (String)); // Sets the focus on the target field. 
setReadOnly(fieldName (String), readOnly (Boolean)); // Sets the target field as read-only or editable.
getLatitude(); // Returns the current latitude. If the latitude cannot be accessed, returns null.
getLongitude(); // Returns the current longitude. If the longitude cannot be accessed, returns null.

**FORM OPERATIONS**
create(entityName (String)); // Creates a new object for the specified entity type. Object can be stored in a  variable. 
configureForm(footerButtonsVisible (boolean), menubarVisible (boolean), breadCrumbVisible (boolean),     childrenVisible (boolean)); // Configure the visibility of certain form sections. All sections are visible as default.
save(bean (Object)); // Saves the given entity.
goBackToPreviousPage(); // Goes back to previous page.
logout(); // Logs off the user.
exportExcelReport(entityName (String), data (List), visibleColumns (List)); // Generates and downloads Excel  report filled with provided data, showing specified columns.

**PAGE OPERATIONS**
openExternalPage(url (String)); // Opens the external page with the given URL in a new tab. 
openExternalPage(url (String), width (int), height (int)); // Opens the external page with the given URL in a new tab with given size. 
openForm(pageName (String)); // Opens form 
openForm(pageName (String), bean (Object)); // Opens form and fills it with the given bean. 
openFormReadOnly(pageName (String)); // Opens form as read-only. No modifications can be made on form.
openFormReadOnly(pageName (String), bean (Object)); // Opens form as read-only and fills it with the given bean. No modifications can be made on form.
openPopup(pageName (String)); // Opens the given entity in a Popup Screen.
openPopup(pageName (String), obj (Object)); // Opens the given entity using given bean as input in a Popup Screen.
openPopup(pageName (String), obj (Object), width (Integer), height (Integer)); // Opens the given entity using given bean as input in a Popup Screen with desired dimensions.
openPopup(pageName (String), width (Integer), height (Integer)); // Opens the given entity in a Popup Screen with desired dimensions.
openReportPage(tabTitle (String), entityName (String), template (Object), data (List)); // Opens the specified report template filled with the data provided. Report template must be created and uploaded to use this method.
openReportPage(tabTitle (String), entityName (String), template (Object), data (List), parameters (Map)); // Opens the specified report template filled with the data provided. Report template must be created and uploaded to use this method.
openReportPage(templateName (String), data (List)); // Opens the specified report template filled with the data provided. Report template must be created and uploaded to use this method.
openReportPage(templateName (String), data (List), parameters (Map)); // Opens the specified report template filled with the data provided. Report template must be created and uploaded to use this method.
openTable(pageName (String)); // Opens the given entity in a Popup Screen.
openTable(pageName (String), constraints (String)); // Opens the given entity in a Popup Screen. 
closePage(); // Closes current entity page.
closePage(entityName (String)); // Closes given entity page.

**PROMPTING A MESSAGE TO SCREEN**
tray(languages (String[])); // Displays a message in the system tray. 
info("This is an info message" (String[])); // Displays an info message. 
warn("This is warn message" (String[])); // Creates a warning message popup. 
warnXml(msg (String)); Creates a warning message popup.
error("This is an error message" (String[])); // Displays an error message. 
log(message (String)); // Logs a message to developer logs
debug(message (String)); // Prints the value of a given variable in a popup window.

**SCHEDULING OPERATIONS**
startScheduling(serviceName (String), input (Object), interval (String), startDate (Date), endDate (Date)); //     Starts scheduling for the given service. Note that service must be defined first. 
stopScheduling(serviceName (String)); // Stops scheduling for the given service. 
isScheduling(serviceName (String)); // Returns true if given service has a scheduled job.

**TABLE OPERATIONS**
addItem(comboName (String), key (Object), languages (List)); // Adds the given item (key) to the target ComboBox or Radio Button. Note that this method only works for transient components.
addTableItem(tableName (String), item (Object)); // Adds the given item to the target table.
addListItem(constantGroupName (String), key (String), languages (List)); // Adds the given item (key) to the  target ComboBox or Radio Button. Note that this method only works for transient components.
selectItem(twincolName (String), item (Object)); // Selects the given item from given twinColSelect table.
refreshCurrentTable(); // Refreshes the current entity list table. After a database operation is made, this method must be used to update table. 
removeItem(fieldName (String), item (Object)); // Removes the item(s) with the given id from the field with the given name. Field can be permanent or transient. Remove operation works on UI level for embedded  tables,doesn't effect database record. 
removeSelectedItem(fieldName (String)); // Removes selected item(s) from the field with the given name. Field can be permanent or transient. Remove operation works on UI level for embedded tables, doesn't effect database record.
removeAllItems(fieldName (String)); // Removes all items(s) from the field with the given name. Field can be permanent or transient. Remove operation works on UI level for embedded tables, doesn't effect database record.

**RICH TABLE OPERATIONS**

Check: Rich Table API & Examples


**TASK MANAGEMENT**
task(name (String), description (String), assigneeId (String), dueDate (Date), priority (int)); // Creates a new task with given parameters. Returns the task id 
taskForGroup(name (String), description (String), dueDate (Date), priority (Integer), assigneeGroup (String)); // Creates a new task with given parameters assigned to a group. Returns the task id. 
taskForGroupWithAttachment(name (String), description (String), dueDate (Date), priority (Integer), assigneeGroup (String), bean (Object)); // .Creates a new task with given parameters assigned to a group. Given bean is added to the task as attachment. Returns the task id. 
getTask(taskId (String)); // Returns the task with the given id. 
completeTask(taskId (String)); // Completes the task with the given task id which can be received from task,  taskForGroup or taskForGroupWithAttachment methods.

and you can play & learn with those methods to see how powerful they are. There is also a description for each method about how to use them.

Not only pages can run services, but also buttons and comboboxes in a page can run a service. Simply right clicking on a button, you can define what action will be triggered when the button is clicked. Same as button, you can also right click on a combobox and define what action will be triggered when the combobox value is changed.

Opening a Report Page

openReportPage(tabTitle (String), entityName (String), template (Object), data (List));  

This method is used for opening a report page for a report template you have defined. The first parameter to this method takes the entity name. The second takes the name of the report template. The third parameter takes the data to be viewed by using the template. You can use the query method for retrieving data to be used for the report.

Example:

openReportPage('Leads', 'LeadsInIstanbul', ('Leads', "from Leads where city = 'Istanbul'"));  

This code snippet queries for the leads who live in Istanbul, and uses the report template named 'LeadsInIstanbul' to view this data.