Efficy ServerJS script reference

Efficy reference

API interface class exposing properties and methods allowing to perform operations on the entities and interact with the CRM business logic.

Properties

Name Type Access Description
disableCategorySecurity boolean Read/Write Introduced in Efficy 11.3 Complement to DisableSecurity: If true, the rights and securities on categories are also no longer checked.
disableChangeLog boolean Read/Write Introduced in Efficy 11.2 If true, disables writing the history of changes to the database (SYS_CHANGED table); this can improve performance when needed, e.g. for massive imports.
disableNotifications boolean Read/Write If true, no system notifications get generated by subsequent operations.
Use this method with care.
disableSecurity boolean Read/Write If true, the rights and securities are no longer checked.
disableWebHooks boolean Read/Write Introduced in Efficy 11.2 If true, disables sending notifications configured into SYS_WEBHOOKS table. This can improve performance when needed, e.g. for massive imports.
disableWorkflow boolean Read/Write If true, no workflow scripting events get generated by subsequent operations.
entityCatalog TEntityCatalog Read only The helper object to retrieve metadata.
ignoreRights boolean Read/Write Same as DisableSecurity. (deprecated)
language integer Read/Write The selected language.
logThreadIndex integer Read only Introduced in Efficy 11.2 When running data synchro with multiple threads, contains the index of the current thread.
multiCurrencyMode integer Read only Introduced in Efficy 11.2 The multi-currency mode of the current database. Can be 0 (multi-currency off), 1 (multi-currency on, variable) or 2 (multi-currency on, fixed).
processName string Read only An identifier of the process running the script.
workingPeriodFrom double Read only The low bound of the range shown in agenda.
workingPeriodTo double Read only The high bound of the range shown in agenda.

Methods

Efficy.activateCategory(editHandle, category)

Activates a category in the edit context. If the user does not have the appropriate rights on the category, an exception is thrown.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
category string The name of the category.
Return
boolean
Usage
Efficy.activateCategory(Request.contextHandle, 'DOCU$INVOICING');

Efficy.addLink(entity, detail, key, detailKey, relationId, ignoreExisting)

Adds a database relation without using an edit context. Can be used when multiple relations are available.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
key double The entity key.
detailKey double The detail Key.
relationId integer Specify -1 to generate a new "K_RELATION" value.
ignoreExisting boolean If true, doesn't throw an exception if the relation already exists.
Usage
Efficy.addLink(ntDocu, ntProj, docuKey, projKey, -1, true);

Efficy.addLink2(entity, detail, key, detailKey, ignoreExisting)

Adds a database relation without using an edit context.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
key double The entity key.
detailKey double The detail Key.
ignoreExisting boolean If true, doesn't throw an exception if the relation already exists.
Usage
Efficy.addLink2(ntDocu, ntProj, docuKey, projKey, true);

Efficy.addRecent(entity, key, name, favoriteKey, keyList, gridName)

Adds the record identified by entity and key to the list of recent items.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key double The entity key.
name string The display name.
favoriteKey [Opt] double 0 For recent user lists, the key of corresponding user list favorite.
keyList [Opt] string '' For recent user lists, the list of user keys.
gridName [Opt] string '' For recent user lists, the grid name (e.g. "Agenda").
Usage
Efficy.addRecent(ntCase, caseKey, caseName);

Efficy.aliasList()

Returns the list of aliases.

Return
string
Usage
Create an array of aliases to be inserted into a <select> tag
var options = [], alias; var list = TEnhStringList.create(); try { list.text = Efficy.aliasList(); for (var i = 0; i < list.count; i++) { alias = contextEncodeHtml(list(i)) options.push('<option value="' + alias + '">' + alias + '</option>'); } } finally { list.Free() }

Efficy.applySecurityToContent(editHandle)

Applies the security of a container entity to its linked records.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Usage
if (applyToContent) Efficy.applySecurityToContent(Request.contextHandle);

Efficy.autoMergeDuplicate(entity, key1, key2, alwaysKeepFirst)

Merges duplicates automatically.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key1 double The key of the first record.
key2 double The key of the second record.
alwaysKeepFirst [Opt] boolean False If true, allows to choose which record is kept by ordering the keys.
Usage
var entity = Efficy.entityCatalog.getEntityHandle(Request.argument('entity')), key1 = Request.floatArgument('key1', 0), key2 = Request.floatArgument('key2', 0), Efficy.autoMergeDuplicate(entity, key1, key2, true); // Record with key1 is kept, key2 is deleted after merge

Efficy.callDotNetLibraryFunction(dllName, dllClass, functionName, parameters)

Uses .Net external libraries from within a workflow or a server-side script.

Parameter Type Default value Description
dllName string The name of the external library.
dllClass string The class of the external library.
functionName string The function to be called in the external library.
parameters olevariant The array of variants that contains the parameters to be given to the external library call.
Return
olevariant
Usage
var dllName = 'Path\\to\\TestNetDll.dll', dllClass = 'TestNetDllNamesapce.TestClass', dllFunc = 'TestFunction', params = VarArrayOf(['this is a test string']); res = Efficy.callDotNetLibraryFunction(dllName, dllClass, dllFunc, params);

Efficy.categoryModified(editHandle, category, fieldName)

Tests whether a field value of a category data set has been modified since the beginning of the edit operation.
The value is reset when Efficy.commitChanges() is executed.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
category string The name of the category.
fieldName string The name of the field.
Return
boolean
Usage
if (Efficy.categoryModified(editHandle, 'DOCU$INVOICING', 'EXPENSES')) var oldValue = Efficy.oldCategoryFieldValue(editHandle, 0, 'EXPENSES');

Efficy.clearDetail(editHandle, detail)

Clears all relations for the specified detail.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.

Warning: Do not use this function to clear the "User" detail. The only way of dealing with users is by using the functions Efficy.setUsers() and Efficy.setUserSecurity().

Usage
Efficy.clearDetail(Request.contextHandle, ntCont);

Efficy.closeContext(contextHandle)

Closes a context. A context remains memory-resident on the web server until it's closed.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
Usage
var editHandle = Efficy.openEditContext(ntTime, key); try { var ds = Efficy.getMasterDataSet(editHandle, 0); // ... } finally { Efficy.closeContext(editHandle); // make sure context is always closed }

Efficy.closingCommit(editHandle)

Commits the changes, releases the record and closes the context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Usage
var contextHandle = Efficy.openEditContext(ntCont, contKey); // ... Efficy.closingCommit(contextHandle);
function addProdPrice(prodName, prodPrice1, prodPrice) { var prodKey, contextHandle = Efficy.openEditContext(ntProd, 0), dsProd = Efficy.getMasterDataSet(contextHandle, 0), dsProdPrce = Efficy.getDetailDataSet(contextHandle, ntProdPrce); dsProd.edit(); dsProd.fieldByName('NAME').asString = prodName; dsProd.fieldByName('PRICE1').asFloat = prodPrice1; Efficy.insertDetail2(contextHandle, ntProdPrce, 1, false); dsProdPrce.fieldByName('PRICE').asFloat = prodPrice; Efficy.setUsers(contextHandle, Efficy.currentUserId(), false, false); prodKey = Efficy.getEditKey(contextHandle); Efficy.closingCommit(contextHandle); return prodKey; }

Efficy.collectGarbage()

Do not use this from within a script unless you know what you're doing.

Efficy.commitChanges(editHandle, refreshAfterCommit)

Commits the changes of the edit context to the database.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
refreshAfterCommit boolean If true, refreshes all the data in the edit context. Use this option if you continue to use the edit context after the commit.

Warning: None of the previous functions has any permanent effect until Efficy.commitChanges() is called.

Usage
var editHandle = Efficy.openEditContext(ntProj, key); try { Efficy.updateCategoryField(editHandle, 'PROJ$WORKLOAD', 'REFIDX_STAGE', 0); Efficy.updateCategoryField(editHandle, 'PROJ$WORKLOAD', 'REFIDX_STEP', 0); Efficy.commitChanges(editHandle, false); } finally { Efficy.closeContext(editHandle); }
var editHandle = Efficy.openEditContext(ntCont, key); try { var ds = Efficy.getMasterDataSet(editHandle, 0); ds.edit(); ds.fieldByName('FIRSTNAME').asString = 'First Name'; ds.fieldByName('MIDDLENAME').asString = 'Middle Name'; Efficy.commitChanges(editHandle, false); } finally { Efficy.closeContext(editHandle); }

Efficy.consult(contextHandle, key, forceRefresh)

Consults a record in the context handle and returns its main data set.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
key double The key of the record.
forceRefresh boolean If true, never uses cached results.
Return
TDataSet
Usage
var contextHandle = Efficy.openConsultContext(ntComp); try { var ds = Efficy.consult(contextHandle, key, true); var name = ds.fieldByName('NAME').asString; } finally { Efficy.closeContext(contextHandle); }

Efficy.consultAgenda(queryHandle, beginDate, endDate, userIDs, activeUser, includeRelations, queryView, planning)

Retrieves the agenda (diary) for the specified period and users.

Parameter Type Default value Description
queryHandle integer Returns the query handle of the database query.
beginDate double The begin date of requested period.
endDate double The end date of requested period.
userIDs olevariant The array of users. Can be filtered according to database security.
activeUser boolean If true, shows data to which the users are actively linked.
includeRelations boolean If true, retrieves the main company, contact and project in the query result.
queryView double The query view to be used on the database query. Use 0 to ignore query views.
planning [Opt] boolean False If true, uses the query of the planning view.
Return
TDataSet
Usage
var handle, beginDate = ISO8601ToDateTime((new Date()).toISOString(), true), days = 7, userIds = VarArrayOf([2, 3]), ds = Efficy.consultAgenda(handle, beginDate, incDay(beginDate, days), userIds, true, true, 0, false);

Efficy.consultDetail(queryHandle, contextHandle, key, detail, forceRefresh, getAllRecords, queryView)

Retrieves the list of linked detail items in a data set.

Parameter Type Default value Description
queryHandle integer Returns the query handle of the database query.
contextHandle TContextHandle The handle of the context (consult or edit).
key double The key of the master record.
detail TEntityHandle The detail handle.
forceRefresh boolean If true, never uses cached results.
getAllRecords boolean If true, retrieves all records in a single call instead of page per page.
queryView double The query view to be used on the database query. Use 0 to ignore query views.
Return
TDataSet
Usage
var contextHandle = Efficy.openConsultContext(ntMail); try { var json, dsComp = Efficy.consultDetail(0, contextHandle, mailKey, ntComp, true, false, 0); if (dsComp) json = JSON.parse(dataSetToJson(dsComp, true, [Efficy.entityCatalog.keyFieldName(ntComp), 'OPENED', 'NAME', 'CITY', 'R_COUNTRY'].join(), '', 10)); } finally { Efficy.closeContext(contextHandle); }

Efficy.consultFavorites(forEntity)

Introduced in Efficy 11.2 Retrieves the list of favorites.

Parameter Type Default value Description
forEntity [Opt] string '' Filters result on a specific entity. If not set, all entities are returned.
Return
TDataSet
Usage
var ds = Efficy.consultFavorites(); return JSON.parse(dataSetToJson(ds, true, ['K_1', 'ENTITY', 'NAME'].join()));
var ds = Efficy.consultFavorites('User'); return JSON.parse(dataSetToJson(ds, true, ['K_FAVORITE', 'NAME', 'K_2'].join()));

Efficy.consultMainCompany(contextHandle, contactKey)

Consults the main company of the specified contact.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
contactKey double The key of the contact.
Return
TDataSet
Usage
var ds = Efficy.consultMainCompany(contextHandle, contKey);

Efficy.consultMany(contextHandle, findFields, orderByFields, findValues, forceRefresh)

Selects records that exactly match certain field values and returns the resulting data set.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
findFields string The fields to match.
orderByFields string The sort order.
findValues olevariant The values to match.
forceRefresh [Opt] boolean True If true, never uses cached results.
Return
TDataSet
Usage
var consultContext = Efficy.openConsultContext(ntSync); try { var ds = Efficy.consultMany(consultContext, 'K_APPLICATION;K_USER', 'K_SYNCHRO', varArrayOf([appKey, userKey]), true), items = []; ds.first(); while (!ds.eof) { items.push({ kSynchro: ds.fieldByName('K_SYNCHRO').asFloat, kRelation: ds.fieldByName('K_RELATION').asFloat, k1: ds.fieldByName('K_1').asFloat }); ds.next(); } } finally { Efficy.closeContext(consultContext); }

Efficy.consultQuery(queryHandle, contextHandle, master, detail, queryParams, forceRefresh, getAllRecords, queryViewText, maxUsedDays, topRows)

Runs a database query and returns the results in a data set.

Parameter Type Default value Description
queryHandle integer Returns the query handle of the database query.
contextHandle TContextHandle The handle of the context (consult or edit).
master integer Identifies the query in the system table "SYS_QUERIES" or "QUERIES".
detail double Identifies the query in the system table "SYS_QUERIES" or "QUERIES" (if master = -1).
queryParams olevariant The query parameters in a variant array.
forceRefresh boolean If true, never uses cached results.
getAllRecords boolean If true, retrieves all records in a single call instead of page per page.
queryViewText string Can be either an empty string "" or a query view text.
maxUsedDays [Opt] integer 0 Filters result on recently used.
topRows [Opt] integer 0 Filters result on a count of leading rows.
Return
TDataSet
Usage
var sqlContext = Efficy.openTemporaryContext(); var ds = Efficy.consultQuery(0, sqlContext, ntAppo, ntTime, varArrayOf([user, date + 1, date]), true, true, '');

Efficy.consultRecent(entity, extraFields, gridName)

Retrieves the recent list.

Parameter Type Default value Description
entity TEntityHandle The entity handle. Pass ntNone to retrieve the list of all entities.
extraFields string When filtered on an entity, retrieves additional fields from the table (comma separated).
gridName [Opt] string '' For recent user lists, the grid name (e.g. Agenda).
Return
TDataSet
Usage
var ds = Efficy.consultRecent(ntCont, ['EMAIL1', 'EMAIL2', 'EMAIL3'].join()); return JSON.parse(dataSetToJson(ds, true, ['K_1', 'ENTITY', 'TEXT', 'OPENED', 'ISDELETED', 'EMAIL1', 'EMAIL2', 'EMAIL3'].join()));

Efficy.consultTaskList(queryHandle, date, userIDs, activeUser, showPast, queryView, showUpcoming)

Retrieves the task list for the specified date and userIDs.

Parameter Type Default value Description
queryHandle integer Returns the query handle of the database query.
date double The requested date for task list.
userIDs olevariant The array of users. Can be filtered according to database security.
activeUser boolean If true, shows data to which the users are actively linked.
showPast boolean If true, includes the past, unfinished tasks.
queryView double The query view to be used on the database query. Use 0 to ignore query views.
showUpcoming [Opt] boolean False If true, includes the future tasks.
Return
TDataSet
Usage
var ds = Efficy.consultTaskList(0, date, user, true, false, 0);

Efficy.contextEncode(s, contexts)

Deprecated since Efficy 11.1 Encodes a string for one or multiple output contexts.
Use the identical contextEncode() instead, which is now available without the Efficy prefix.

Parameter Type Default value Description
s string The string to encode.
contexts string The comma separated list of contexts (ex: "TEXT" or "ATTR,JS"). The available contexts are: TEXT, ATTR, JS, CSS, URL, HTML, or TAG.
Return
string
Usage
var s = Efficy.contextEncode(s, 'TEXT'); // = contextEncode(s, 'TEXT') = contextEncodeText(s)

Efficy.convertAttachmentToPdf(editHandle, fileId, version)

Converts the attachment identified by a fileId and a version into a PDF file and returns the key (K_FILE) to the PDF attachment.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
fileId double The key of the attachment to be converted.
version integer The version of the attachment to be converted.
Return
double
Usage
var fileKey = Efficy.convertAttachmentToPdf(contextHandle, 99999001, 1);

Efficy.copyDetails(editHandle, sourceEditHandle, details, mainRelationOnly, onlyModifiedDetails)

Copies data from another open edit context, not necessarily on the same entity.

Parameter Type Default value Description
editHandle TContextHandle The handle of the destination edit context.
sourceEditHandle TContextHandle The handle of the source edit context.
details array of TEntityHandle The array of details that will be copied.
mainRelationOnly boolean If true, copies only the main relation record.
onlyModifiedDetails boolean If true, copies only the relations that have pending modifications in the source edit context.
Usage
Efficy.copyDetails(projContext, oppoContext, [ntUser, ntComp, ntCont], false, false);

Efficy.copyDetails2(editHandle, sourceEntity, key, details, mainRelationOnly, onlyModifiedDetails)

Copies data from a database record, not necessarily on the same entity.
This is equivalent to opening the source entity and calling Efficy.copyDetails().

Parameter Type Default value Description
editHandle TContextHandle The handle of the destination edit context.
sourceEntity TEntityHandle The entity handle of the source record.
key double The key of the source record.
details array of TEntityHandle The array of details that will be copied.
mainRelationOnly boolean If true, copies only the main relation record.
onlyModifiedDetails boolean If true, copies only the relations that have pending modifications in the source edit context. Should be false (since the source record is taken directly from the database).
Usage
var contextHandle = Efficy.openEditContext(ntDocu, 0); try { Efficy.copyDetails2(contextHandle, ntMail, mailKey, [ntUser, ntComp, ntCont, ntProj, ntCase, ntOppo], true, false); Efficy.commitChanges(contextHandle, false); } finally { Efficy.closeContext(contextHandle); }

Efficy.copyFromExisting(editHandle, key, minIndex, maxIndex)

Copies data from an existing record in the database. The same entity as the current edit context is assumed.
The table views within the index range minIndex to maxIndex are copied. By default, all table views are copied.
To copy a single detail, obtain the table view index using Efficy.indexFromDetail() and use this value as minIndex and maxIndex.

Parameter Type Default value Description
editHandle TContextHandle The handle of the destination edit context.
key double The key of the source record.
minIndex [Opt] integer 0 The index of first table view to be copied.
maxIndex [Opt] integer 999 The index of last table view to be copied.
Usage
var editHandle = Efficy.openEditContext(ntWrkTeam, 0); try { Efficy.copyFromExisting(editHandle, kTeamMember); Efficy.updateField(editHandle, 0, 'K_USER', userKey); Efficy.updateField(editHandle, 0, 'K_PROJECT', projKey); Efficy.commitChanges(editHandle, false); } finally { Efficy.closeContext(editHandle); }

Efficy.createAttachmentRevision(editHandle, fileId, version)

Adds a new version of the attachment identified by a fileId and a version.
The return value is the new version number.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
fileId double The key of the file.
version integer The version of the file.
Return
integer
Usage
var v = Efficy.createAttachmentRevision(contextHandle, 99999001, 1);

Efficy.createSharingToken(entity, key, version, daysValid)

Generates a URL for external document sharing.

Parameter Type Default value Description
entity TEntityHandle Can be ntDocu or ntFile to share either a whole document or a single file.
key double The key of the document or of the file.
version integer The version if a single file is shared. Otherwise value is ignored.
daysValid integer The days from now on the URL can be used.
Return
string
Usage
Retrieve a sharing token for a file or a document, if sharing is allowed
if (fileKey) { entityHandle = ntFile; entityKey = fileKey; } else { entityHandle = ntDocu; entityKey = docuKey; } var contextHandle = Efficy.openConsultContext(ntDocu); try { var dsDocu = Efficy.consult(contextHandle, docuKey, true), sharingToken; if (dsDocu && dsDocu.recordCount > 0 && dsDocu.fieldByName('PREVENTSHARING').asString !== '1') sharingToken = encodeURI(Efficy.createSharingToken(entityHandle, entityKey, version, daysValid)); } finally { Efficy.closeContext(contextHandle); }

Efficy.createTokenUrl(entity, tokenValue)

Introduced in Efficy 11.2 Generates a URL for external document sharing, based on an existing token

Parameter Type Default value Description
entity TEntityHandle Can be ntDocu or ntFile to share either a whole document or a single file. Make sure the entity matches the value used when the token was generated.
tokenValue string Existing token in the SYS_TOKENS table.
Return
string
Usage
var sql ='select <#top count="1"> TVALUE \ from <#table name="SYS_TOKENS"> \ where k_table = 31000 and k_1 = :param1 \ order by d_create desc', ds = Efficy.sqlQueryDataset(sql, req.content.key); if (ds.recordCount > 0) res.token = Efficy.CreateTokenURL(ntDocu, ds.FieldByName('TVALUE').AsString);

Efficy.currentCustomerProfile()

Introduced in Efficy 11.1 Retrieves the current customer profile of the session.

Return
string
Usage
var profile = Efficy.currentCustomerProfile();

Efficy.currentDatabaseAlias()

Retrieves the alias (name) of the currently connected database.

Return
string
Usage
var alias = Efficy.currentDatabaseAlias();

Efficy.currentUserCode()

Retrieves the user code of the current user.

Return
string
Usage
var code = Efficy.currentUserCode(); // "ADMIN"

Efficy.currentUserContactId()

Retrieves the contact key of the current user. This value only makes sense for contact users, for others the value is 0.

Return
double

This method only functions in the context of an extranet (e.g. helpdesk), where a session is created using a Contact License.
Use Efficy.getContactKeyForUser() for a normal User session.

Usage
var id = Efficy.currentUserContactId(); if (id > 0) return 'User is linked to a contact';

Efficy.currentUserFullName()

Retrieves the current user's full name.

Return
string
Usage
var userName = Efficy.currentUserFullName(); // "Administrator"

Efficy.currentUserGroups()

Retrieves the array of groups to which the current user belongs.

Return
olevariant
Usage
var groups = Efficy.currentUserGroups(); if (varIsArray(groups)) { for (var i = varArrayLowBound(groups, 1); i < varArrayHighBound(groups, 1); i++) var groupId = varArrayElement(groups, i); }

Efficy.currentUserId()

Retrieves the ID (key) of the current user.

Return
integer
Usage
Efficy.setUsers(contextHandle, [Efficy.currentUserId()], false, false);

Efficy.currentUserRole(allowForced)

Introduced in Efficy 11.2 Retrieves the current user's role.

Parameter Type Default value Description
allowForced [Opt] boolean True Take into account the forced role set with the forceUserRole method.
Return
integer
Usage
var userRoleSkillId = Efficy.getUserProperty(Efficy.currentUserRole(), 'SKILL');

Efficy.databaseLicenseName()

Retrieves the license name of the currently connected database.

Return
string
Usage
var license = Efficy.Efficy.databaseLicenseName();

Efficy.dbEngine()

Returns the type of the database engine.
Possible values: "OR" (Oracle), "MS" (Microsoft SQL Server) and "FB" (Firebird).

Return
string
Usage
if (Efficy.dbEngine() === 'OR') // specific sql code for Oracle

Efficy.deactivateCategory(editHandle, category)

Introduced in Efficy 11.2 Deactivates a category in the edit context. If the user does not have the appropriate rights on the category, an exception is thrown.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
category string The name of the category.
Return
boolean
Usage
Efficy.deactivateCategory(contextHandle, 'DOCU$INVOICING');

Efficy.deactivateExtranetAccess(contactId)

Introduced in Efficy 11.2 Removes access to the extranet for a given contactId.

Parameter Type Default value Description
contactId double The key of the contact.
Usage
Efficy.deactivateExtranetAccess(2);

Efficy.deleteDetail(editHandle, detail, detailKey, relationId)

Deletes the detail relation identified by a detail, a detailKey and optionally a relationId (if multiple relations are available).

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey double The detail key.
relationId [Opt] integer MULTIRELATION_NONE The ID of the multirelation.
Usage
var contextHandle = Efficy.openEditContext(ntProj, Efficy.getMainDetail(editHandle, ntProj)); try { Efficy.deleteDetail(contextHandle, ntProd, prodDS.fieldByName('K_PRODUCT').asFloat, prodDS.fieldByName('K_RELATION').asFloat); } finally { Efficy.closeContext(contextHandle); }

Efficy.deleteEntity(entity, keyList)

Deletes records.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
keyList olevariant An array of entity keys to be deleted.
Usage
Efficy.deleteEntity(ntTime, key);

Efficy.deleteLink(entity, detail, key, detailKeyList)

Removes database relations without using an edit context.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
key double The entity key.
detailKeyList olevariant An array of detail keys.
Usage
Efficy.deleteLink(ntComp, ntActi, 166, VarArrayOf([5142, 5143]));

Efficy.detailExists(editHandle, detail)

Tests whether the detail entity is available in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
Return
boolean

To check if there are details linked, use recordCount property of the data set:

if (!Efficy.getDetailDataSet(editActi, ntComp).recordCount) {
  // Warn that there are no companies linked
}

Usage
return Efficy.detailExists(editComp, ntActi); // Returns false: in the edit of a Company, Action is not available as detail

Efficy.detailModified(editHandle, detail)

Tests whether the detail data set has been modified since the beginning of the edit operation by inserting or deleting records, or updating field values.
The value is reset when Efficy.commitChanges() is executed.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
Return
boolean
Usage
Prevent modification of Cont-Comp relation
function BeforeCommitCont(editCont, inserted) { if (Efficy.detailModified(editCont, ntComp) && !Efficy.isCurrentUserInGroup(Efficy.getUserId('EFF_ADMINS')) throw Error('You are not allowed to modify the company relation!'); }

Efficy.detectConflictInAgenda(editHandle, checkOldValues)

Returns list of users for which there was a conflicting action.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
checkOldValues [Opt] boolean True If true, does not detect if action range was reduced.
Return
olevariant
Usage
var names = [], contextHandle = Efficy.openEditContext(ntActi, appoId); try { var users = Efficy.detectConflictInAgenda(contextHandle); if (varIsArray(users)) { for (var i = 0; i < varArrayHighBound(users, 1); i++) names.push(Efficy.getUserName(varArrayElement(users, 0, i))); } } finally { Efficy.closeContext(contextHandle); }

Efficy.detectConflictInAgendaAsNames(editHandle, checkOldValues)

Returns list of user names for which there was a conflicting action.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
checkOldValues [Opt] boolean True If true, does not detect if action range was reduced.
Return
string
Usage
Modify the end date of an appointment and check conflicts
var ds, names, ret = '', contextHandle = Efficy.openEditContext(ntActi, appoId); try { if (Efficy.lockedByAccount(contextHandle) !== Efficy.currentUserId()) return Request.translate('This information is read-only!'); ds = Efficy.getMasterDataSet(contextHandle, 0); ds.edit(); ds.fieldByName('D_END').asFloat = ds.fieldByName('D_END').asFloat + delta; names = Efficy.detectConflictInAgendaAsNames(contextHandle); if (names) ret = 'EFFCONFLICT:' + Request.translate('Warning: conflict with existing appointments for the following user(s)') + ': \r\n' + names; Efficy.commitChanges(contextHandle, false); } finally { Efficy.closeContext(contextHandle); }

Efficy.duplicateAttachment(editHandle, fileId, version)

Duplicates the attachment identified by a fileId and a version and returns the key (K_FILE). Attachment revisions are 0-based.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
fileId double The key of the attachment.
version integer The version of the attachment.
Return
double
Usage
var fileKey = Efficy.duplicateAttachment(contextHandle, 99999001, 1);

Efficy.eMailOutFromEditing(mailEditHandle, sourceEditHandle, emailTemplate, mailField, attachmentList, addLinkedDocuments)

Creates an email from a template and send it to the linked contacts or companies.

Parameter Type Default value Description
mailEditHandle TContextHandle The handle of the mail edit context.
sourceEditHandle TContextHandle The handle of the source edit context.
emailTemplate double The key of the mail template.
mailField [Opt] string '' The name of the field containing the email address.
attachmentList [Opt] string '' The list of attachments to send, separated by semicolons.
addLinkedDocuments [Opt] boolean True Introduced in Efficy 11.2 If true, adds the attachments of the linked documents to the email.
Usage
function convertEntityToMail() { var actiHandle = Request.argument('actiHandle'), mailEditHandle = Efficy.openEditContext(ntMail, 0); try { Efficy.eMailOutFromEditing(mailEditHandle, actiHandle, 0); Efficy.commitChanges(mailEditHandle, false); return Efficy.getEditKey(mailEditHandle); } finally { Efficy.closeContext(mailEditHandle) } }

Efficy.entityFromContext(contextHandle)

Returns the entity used in the context handle.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
Return
TEntityHandle
Usage
if (Efficy.entityFromContext(Request.contextHandle) === ntActi) ds.fieldByName('SUBJECT').asString = name; else ds.fieldByName('NAME').asString = name;

Efficy.execSql(sql, queryParams, invalidateConnection)

Executes a SQL command in the database that does not return a data set.
This method is typically used for update or delete SQL.

Parameter Type Default value Description
sql string The SQL statement to be executed.
queryParams string The string list of parameters.
invalidateConnection boolean If true, invalidates the current database connection. Required if the SQL command modifies the system tables.

Warning: By performing rogue update or delete operations, you may invalidate replication, change history or integrity rules. Do not use this instruction unless you are fully aware of the business rules that govern an Efficy database.

Usage
Efficy.execSql('update <#TABLE name="WRK_STEPS"> set REFERENCE = \'\' where K_PROJECT = :param1', projKey, false);

Efficy.executeOdbcQuery(queryHandle, contextHandle, connection, sql, forceRefresh, getAllRecords, storeId)

Runs an ODBC query – a native (SQL) database query – and returns the results in a data set.

Parameter Type Default value Description
queryHandle integer Returns the query handle of the database query.
contextHandle TContextHandle The handle of the context (consult or edit).
connection string The connection string for the ODBC connection.
sql string The SQL select instruction.
forceRefresh boolean If true, never uses cached results.
getAllRecords boolean If true, retrieves all records in a single call instead of page per page.
storeId integer An integer value which identifies the store in which the data set will be kept. Successive calls with an identical storeId reuse the same data set.
Return
TDataSet
Usage
var ds = Efficy.executeOdbcQuery(queryHandle, contextHandle, odbcConnectionString, 'select * from <#TABLE name="CONTACTS">', false, false, storeId);

Efficy.executeQueryWithoutContext(queryHandle, master, detail, queryParams, forceRefresh, getAllRecords)

Equivalent to Efficy.openTemporaryContext() and Efficy.consultQuery().

Parameter Type Default value Description
queryHandle integer Returns the query handle of the database query.
master integer Identifies the query in the system table "SYS_QUERIES" or "QUERIES".
detail double Identifies the query in the system table "SYS_QUERIES" or "QUERIES" (if master = -1).
queryParams olevariant The query parameters in a variant array.
forceRefresh boolean If true, never uses cached results.
getAllRecords boolean If true, retrieves all records in a single call instead of page per page.
Return
TDataSet
Usage
This method can be used in two ways, depending where the query to execute is stored.

• To execute a system query from SYS_QUERIES, specify its master and detail keys:
var ds = Efficy.executeQueryWithoutContext(queryHandle, 32, 5, params, true, true); // Call backs list query from SYS_QUERIES var ds = Efficy.executeQueryWithoutContext(queryHandle, 11, 11010, varArrayOf([contactKey]), true, true);
• To execute a user query from QUERIES, pass the special value "-1" for Master and the query key K_QUERY for detail:
var ds = Efficy.executeQueryWithoutContext(queryHandle, -1, 345, params, true, true); // Query from QUERIES with K_QUERY = 345

Efficy.executeSystemSqlQuery(queryHandle, contextHandle, sql, queryParams, forceRefresh, getAllRecords, storeId)

Runs a native (SQL) database query and return the results in a data set.

Parameter Type Default value Description
queryHandle integer Returns the query handle of the database query.
contextHandle TContextHandle The handle of the context (consult or edit).
sql string The SQL select instruction.
queryParams string The values of the parameters in the SQL select, each parameter on a new line (separated by "\n" in JavaScript).
forceRefresh boolean If true, never uses cached results.
getAllRecords boolean If true, retrieves all records in a single call instead of page per page.
storeId integer An integer value which identifies the store in which the data set will be kept. Successive calls with an identical storeId reuse the same data set.
Return
TDataSet

Warning: Always use bind variables in the SQL command and pass their values in QueryParams. Only fixed values can be part of the SQL command.

Usage
var contextHandle = Efficy.openTemporaryContext(), params = [Efficy.currentUserId()]; var ds = Efficy.executeSystemSqlQuery(0, contextHandle, 'select * from <#TABLE name="ACC_ACCOUNTS" where K_USER = :param1', params.join('\n'), true, true, 0);

Efficy.explodeGroups(users, includeInactive)

Introduced in Efficy 11.3 Explode user groups into the team members, returns the result as a list of users separated by semicolon (;).

Parameter Type Default value Description
users string List of user or group IDs, separated by semicolon (;).
includeInactive [Opt] boolean False Also include inactive users in list (by default only active users are included).
Return
string
Usage
Both these functions explode groups, but the second one will contain duplicates (and is much more complicated):
function explodeGroups(userList) { return Efficy.explodeGroups(userList); }
function explodeGroups(userList) { var userIdList = userList.split(';'); userList = []; for (var i = 0; i < userIdList.length; i++) { var userId = userIdList[i]; if (!userId) continue; userList.push(userId); if (Efficy.isGroup(userId)) { // Add group members var usersInGroupList = TEnhStringList.create(), usersInGroup; try { Efficy.getGroupMemberList(userId, usersInGroupList); usersInGroup = usersInGroupList.commaText.split(','); userList = userList.concat(usersInGroup); // may contain duplicates! } finally { usersInGroupList.free(); } } } return userList.join(';'); }

Efficy.exportReport(editHandle, k_Report, reportFormat, parameters)

Inserts the generated report and returns the key (K_FILE).

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
k_Report double The key of the report.
reportFormat string The output format of the report. Supported values: CrystalReport || PortableDocFormat || WordForWindows || Excel || ExcelRecord || RichText.
parameters string The list of parameters of the report (separated by "\n").
Return
double

Efficy.exportReportToFile(k_Report, reportFormat, parameters)

Same as Efficy.exportReport(), returns the path of the generated report.

Parameter Type Default value Description
k_Report double The key of the report.
reportFormat string The output format of the report. Supported values: CrystalReport || PortableDocFormat || WordForWindows || Excel || ExcelRecord || RichText.
parameters string The list of parameters of the report (separated by "\n").
Return
string

Efficy.extractFile(editHandle, fileId, version, fileName)

Introduced in Efficy 11 Uncompress and saves the content of an attachment to a file. Only inserted files are supported.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
fileId double The key of the file.
version integer The version of the file.
fileName string The path of the file to be saved. Ex: 'C:\\MyFolder\\MyFile.txt'.
Usage
Efficy.extractFile(editHandle, fileId, version, 'c:\\MyFolder\\MyFile.txt'); // is similar to: var ds = Efficy.getDetailDataSet(editHandle, ntFile); ds.locate('K_FILE;VERSION', varArrayOf([fileId, version]), 0); var s = ds.fieldByName('STREAM').asAnsiString; s = smartDecompressEx(s); strSaveBinaryFile('c:\\MyFolder\\MyFile.txt', s);

Efficy.fieldModified(editHandle, tableViewIndex, fieldName)

Tests whether a field value of a master data set has been modified since the beginning of the edit operation.
The value is reset when Efficy.commitChanges() is executed.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
tableViewIndex integer The index of the table view.
fieldName string The name of the field.
Return
boolean
Usage
if (Efficy.fieldModified(editHandle, 0, 'DONE')) // do something

Efficy.findContactsFromEMails(recipients)

Introduced in Efficy 11.2 Returns an array containing all the Contacts having one of the e-mail provided in their e-mail fields (or in the Cont_Comp relation).

Parameter Type Default value Description
recipients string A semicolon separated list of e-mails.
Return
olevariant
Usage
var array = [], contacts = Efficy.findContactsFromEMails(recipients); if (varIsArray(contacts)) { for (var i = varArrayLowBound(contacts, 2); i <= varArrayHighBound(contacts, 2); i++) { array.push({ id: varArrayElement(contacts, 0, i), fullName: varArrayElement(contacts, 1, i), email: varArrayElement(contacts, 4, i), compId: varArrayElement(contacts, 2, i), compName: varArrayElement(contacts, 3, i) }); } }

Efficy.forceUserRole(roleId)

Changes the current user role to set other default securities when inserting records.

Parameter Type Default value Description
roleId integer The key of the group having the default securities configured.
Usage
Efficy.forceUserRole(roleId);

Efficy.generateExtranetPassword(contactId, extCode, requireChangeAtLogin)

Generates a new password for an extranet (Contact) user and insert a corresponding record in ACC_AUTH table the database.

Parameter Type Default value Description
contactId double The key of the Contact.
extCode string The extranet user code (must contain "@" character); usually generated from the e-mail address of the extranet user.
requireChangeAtLogin boolean Specify whether the extranet user must change the password at first login.
Return
string
Usage
var password = Efficy.generateExtranetPassword(contKey, 'NAME@COMPANY.COM', true);

Efficy.generateExtranetPasswordUrl(contactId, extCode, language)

Generates an URL to a password registration page for an extranet (Contact) user.

Parameter Type Default value Description
contactId double The key of the Contact.
extCode string The extranet user code (must contain "@" character); usually generated from the e-mail address of the extranet user.
language [Opt] string '' The language of the page. Default is English.
Return
string
Usage
function createExtranetPasswordUrl(contId, contMail, contLanguage) { var extCode = upperCase(Efficy.getExtranetUserName(contId)); if (!extCode || extCode.indexOf('@') === -1) extCode = upperCase(contMail); return Efficy.generateExtranetPasswordUrl(contId, extCode, contLanguage); }

Efficy.generateProposal(targetContext, sourceContext, mergeArguments, asPdf)

Introduced in Efficy 11 Generates the Spreadsheet Proposal docx based on the current spreadsheet template and linked products.

Parameter Type Default value Description
targetContext TContextHandle The handle of the target context (document). If 0, the docx/pdf will be inserted in the source context.
sourceContext TContextHandle The handle of the source context.
mergeArguments TEnhStringList The list of additional arguments for the merge operation (can be null).
asPdf [Opt] boolean False Introduced in Efficy 11.3 If true, creates the proposal as a PDF file.
Return
double
Usage
function createQuotation() { var contextHandle = Request.contextHandle, oppoHandle = Request.floatArgument('oppoHandle', 0), asPdf = Request.booleanArgument('asPdf'); // ... some code creating quotation Efficy.generateProposal(contextHandle, oppoHandle, null, asPdf); }

Efficy.getAccountKind(userId)

Retrieves the account type of userId.
0 = user, 1 = group, 2 = resource, 3 = team.

Parameter Type Default value Description
userId integer The key of the user.
Return
integer
Usage
switch (Efficy.getAccountKind(user)) { case 0: return 'user', case 1: return 'group', case 2: return 'resource', case 3: return 'team'; }

Efficy.getCategories(contextHandle, selectedCategories, includePanels)

Retrieves activated categories.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
selectedCategories TStrings A string list to be filled.
includePanels boolean If true, lists also the panels.
Usage
var sl = TEnhStringList.create(); try { Efficy.getCategories(Request.contextHandle, sl, false); var i = sl.indexOf(category); if (i >= 0) return 'Category found in context'; } finally { sl.free(); }

Efficy.getCategoryDataSet(contextHandle, categoryName)

Retrieves the data set for category categoryName. Can be null when the category is not available to the current user.
Check TDataSet.isEmpty() to make sure the category is selected for the current record.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
categoryName string The name of the category.
Return
TDataSet
Usage
Switch code based on the active categories, usage example: <%RunScript("ifCategoriesActive", categories="DOCU$INVOICING", then="1", else="0")%>
function ifCategoriesActive() { var editId = Request.contextHandle, categories = Arguments.values('categories').split(';'); var cntActive = 0; categories.forEach(function(category) { var ds = Efficy.getCategoryDataSet(editId, category); if (ds && !ds.isEmpty) cntActive++; }); return (cntActive === categories.length) ? Arguments.values('then') : Arguments.values('else'); }
Return true if category is active
function isCategoryActive(editHandle, category) { var ds = Efficy.getCategoryDataSet(editHandle, category); return ds && !ds.isEmpty(); }

Efficy.getCategoryFieldValue(contextHandle, category, fieldName)

Retrieves the value for field fieldName of the specified category of the consulted entity. Use for non-string fields only.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
category string The name of the category.
fieldName string The name of the field.
Return
olevariant
Usage
var contextHandle = Efficy.openEditContext(ntComp, compKey); try { return Efficy.getCategoryFieldValue(contextHandle, 'COMP$INFO', 'F_FIELD'); finally { Efficy.closeContext(contextHandle); }

Efficy.getCategoryStringFieldValue(contextHandle, category, fieldName)

Retrieves the value for field fieldName of the specified category of the consulted entity. Use for string fields.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
category string The name of the category.
fieldName string The name of the field.
Return
string
Usage
var contextHandle = Efficy.openEditContext(ntComp, compKey); try { return Efficy.getCategoryFieldValue(contextHandle, 'COMP$INFO', 'F_FIELD'); finally { Efficy.closeContext(contextHandle); }

Efficy.getContactKeyForUser(userId)

Retrieves the contact key of the user userId. This value only makes sense for contact users, for others the value is 0.

Parameter Type Default value Description
userId integer The key of the user.
Return
double
Usage
var contactKey = Efficy.getContactKeyForUser(Efficy.currentUserId());

Efficy.getDetailDataSet(editHandle, detail)

Retrieves a relation data set for the specified detail in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
Return
TDataSet
Usage
var contextHandle = Efficy.openEditContext(ntProd, 0), ds = Efficy.getDetailDataSet(contextHandle, ntProdPrce); ds.fieldByName('PRICE').asFloat = 123.45; Efficy.closingCommit(contextHandle);

Efficy.getDetailField(editHandle, detail, detailKey, relationId, fieldName)

Retrieves the value for a relation field of any type but string.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail having the requested field.
detailKey double The key of the detail record.
relationId integer The key of the relation when multi-relations are available.
fieldName string The name of the field.
Return
olevariant
Usage
var value = Efficy.getDetailField(Request.contextHandle, ntComp, 0, -1, 'K_FIELD');
var value = Efficy.getDetailField(Request.contextHandle, ntFile, fileKey, versionId, 'K_FIELD');

Efficy.getDetailStringField(editHandle, detail, detailKey, relationId, fieldName)

Retrieves the value for a relation field of type string.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail having the requested field.
detailKey double The key of the detail record.
relationId integer The key of the relation when multi-relations are available.
fieldName string The name of the field.
Return
string
Usage
var value = Efficy.getDetailStringField(Request.contextHandle, ntComp, 0, -1, 'FIELD');
var value = Efficy.getDetailStringField(Request.contextHandle, ntFile, fileKey, versionId, 'FIELD');

Efficy.getDurationDisplay(duration, activeHours, forcedFormat, dhmsUnits)

Introduced in Efficy 11.2

Parameter Type Default value Description
duration integer Formats an integer duration (in seconds) depending on the user option.
activeHours [Opt] integer 0 Number of working hours in a day. Default is 8.
forcedFormat [Opt] string '' Override the user option. can be D/H/DH/DHM/DHMS.
dhmsUnits [Opt] string '' List of units. Default is "d;h;min;s".
Return
string
Usage
Efficy.getDurationDisplay(43500, 8, 'DHMS'); // 1d 4h 5min

Efficy.getEditEntity(editHandle)

Retrieves the entity handle from an edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
TEntityHandle
Usage
var contextHandle = Efficy.openEditContext(ntComp, 0); var entityHandle = Efficy.getEditEntity(contextHandle); // ntComp (10)

Efficy.getEditKey(editHandle)

Retrieves the main item key of the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
olevariant
Usage
var contextHandle = Efficy.openEditContext(ntProd, 0); var prodKey = Efficy.getEditKey(contextHandle);

Efficy.getExtranetUserName(contactId, createUserNameIfEmpty)

Retrieves the extranet user code for a Contact.

Parameter Type Default value Description
contactId double The key of the Contact.
createUserNameIfEmpty [Opt] boolean False Introduced in Efficy 11.1 If true, creates a new extranet user code if it is currently empty. The new user code will be based on the Contact's EMAIL1 field value.
Return
string
Usage
var extCode = Efficy.getExtranetUserName(contId, true);

Efficy.getFieldDisplayLabel(tableId, fieldId)

Introduced in Efficy 11.2 Retrieves the label for a field fieldId.
It is recommended to use Efficy.getFieldDisplayLabel2() instead to avoid using "magic numbers".

Parameter Type Default value Description
tableId integer The ID of the table.
fieldId integer The ID of the field.
Return
string
Usage
var tableId = Efficy.entityCatalog.tableIdFromEntity(ntCont); var mailFields = { EMAIL1: Efficy.getFieldDisplayLabel(tableId, 32), EMAIL2: Efficy.getFieldDisplayLabel(tableId, 33), EMAIL3: Efficy.getFieldDisplayLabel(tableId, 34) };

Efficy.getFieldDisplayLabel2(tableId, fieldName)

Introduced in Efficy 11.2 Retrieves the label for a field fieldName.

Parameter Type Default value Description
tableId integer The ID of the table.
fieldName string The name of the field.
Return
string
Usage
var tableId = Efficy.entityCatalog.tableIdFromEntity(ntCont); var mailFields = { EMAIL1: Efficy.getFieldDisplayLabel2(tableId, 'EMAIL1'), EMAIL2: Efficy.getFieldDisplayLabel2(tableId, 'EMAIL2'), EMAIL3: Efficy.getFieldDisplayLabel2(tableId, 'EMAIL3') };

Efficy.getFieldStringValue(contextHandle, fieldName, tableViewIndex)

Retrieves the value for a field of type string.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
fieldName string The name of the field.
tableViewIndex [Opt] integer 0 The default TableViewIndex 0 corresponds to the main item.
Return
string
Usage
var name = Efficy.getFieldStringValue(Request.contextHandle, 'NAME');

Efficy.getFieldValue(contextHandle, fieldName, tableViewIndex)

Retrieves the value for a field of any type but string.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
fieldName string The name of the field.
tableViewIndex [Opt] integer 0 The default TableViewIndex 0 corresponds to the main item.
Return
olevariant
Usage
var contextHandle = Efficy.openEditContext(ntProd, 0); var key = Efficy.getFieldValue(contextHandle, 'K_PRODUCT');

Efficy.getFileStream(editHandle, fileDs)

Introduced in Efficy 11.2 Retrieves the binary stream of a file. Depending on the file kind (FILES.KIND field), the function will return the stream stored in FILES.STREAM, load a remote file or download a large file from the Servicy file server.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
fileDs TDataset The data set on the FILES table positioned on the record; Efficy.getFileStream() can use fields KIND, K_FILE, VERSION, PATH and STREAM.
Return
ansistring
Usage
var stream = Efficy.getFileStream(contextHandle, ds);

Efficy.getFlexmailAccountsForCurrentUser()

Retrieves the active Flexmail accounts for the current user.

Return
TDataSet
Usage
function getFlexAccountList() { var list = []; var ds = Efficy.getFlexmailAccountsForCurrentUser(); if (ds && !ds.isEmpty()) { ds.first(); while (!ds.eof) { list.push({ key: ds.fieldByName('K_FLEXMAIL').asFloat, name: ds.fieldByName('NAME').asString }); ds.next(); } } return list; }

Efficy.getFlexmailInfo(k_Flexmail)

Retrieves FlexId, FlexToken, FlexUser and FlexPassword of a Flexmail account.

Parameter Type Default value Description
k_Flexmail integer The key of the Flexmail account.
Return
olevariant
Usage
function getFlexInfo(key) { var v = Efficy.getFlexmailInfo(key); return { key: key, id: varArrayElement(v, 0), token: varArrayElement(v, 1), user: varArrayElement(v, 2), password: varArrayElement(v, 3) }; }

Efficy.getGroupMemberList(groupId, list)

Retrieves the keys of members of a group in a list.

Parameter Type Default value Description
groupId integer The key of the group.
list TEnhStringList The list to be filled.
Usage
if (Efficy.isGroup(userId)) { var usersInGroupList = TEnhStringList.create(), usersInGroup; try { Efficy.getGroupMemberList(userId, usersInGroupList); usersInGroup = usersInGroupList.commaText.split(','); } finally { usersInGroupList.free(); } }

Efficy.getLookupKeyFromValue(tableId, fieldName, value)

Returns the look-up key value for a look-up label.

Parameter Type Default value Description
tableId integer The ID of the table.
fieldName string The field for which the look-up conversion is requested.
value string The text value of look-up field.
Return
integer
Usage
var skillKey = Efficy.getLookupKeyFromValue(Efficy.entityCatalog.tableIDFromName('LK_WRK_SKILL'), 'NAME', fieldValue);

Efficy.getLookupKeyFromValue2(tableName, fieldName, value, searchInTranslations)

Retrieves the key in a lookup table from the value of one field.

Parameter Type Default value Description
tableName string The name of the lookup table.
fieldName string The field that contains the value. If searchInTranslations is true then the value is also searched in translated fields.
value string The value to be searched.
searchInTranslations [Opt] boolean False If true and if the field is the main value field, then the value is also searched into translated fields.
Return
integer

When searching in translated fields, the field corresponding to the current language is checked first, then default (English) and after the trailing fields.

Usage
var skillKey = Efficy.getLookupKeyFromValue2('LK_WRK_SKILL', 'NAME', fieldValue, true);

Efficy.getLookupValueFromKey(tableId, fieldName, key)

Returns the look-up key text for a look-up key.

Parameter Type Default value Description
tableId integer The ID of the table.
fieldName string The field for which the look-up conversion is requested.
key integer The key value of look-up field.
Return
string
Usage
var skillLabel = Efficy.getLookupValueFromKey(Efficy.entityCatalog.tableIDFromName('LK_WRK_SKILL'), 'NAME', fieldKeyValue);

Efficy.getLookupValueFromKey2(tableName, fieldName, key, forcedLanguage)

Retrieves the value in a lookup table from its key.
If the main value field is specified then the translated value for session language is returned. If empty then the default language (English) is returned.

Parameter Type Default value Description
tableName string The name of the lookup table.
fieldName string The field containing the requested value.
key integer The key of the record.
forcedLanguage [Opt] string '' Introduced in Efficy 11.3 The language to use.
Return
string
Usage
var skillLabel = Efficy.getLookupValueFromKey2('LK_WRK_SKILL', 'NAME', fieldKeyValue, userLanguage);

Efficy.getMainDetail(editHandle, detail)

Retrieves the main detail record for the specified detail relation.
Returns 0 if no main detail exists.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
Return
double
Usage
var caseId = Efficy.getMainDetail(Request.contextHandle, ntCase);

Efficy.getMasterDataSet(editHandle, tableViewIndex)

Retrieves a master data set from the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
tableViewIndex integer Specify 0 to retrieve the main entity data.
Return
TDataSet
Usage
var contextHandle = Efficy.openEditContext(ntDocu, 0); var ds = Efficy.getMasterDataSet(contextHandle, 0);

Efficy.getMultiValueLabels(tableId, fieldName, value, separator)

Converts the look-up keys for a multi-value field to labels using the look-up table for the field.

Parameter Type Default value Description
tableId integer The ID of the table.
fieldName string The field for which the look-up conversion is requested.
value string Semicolon separated list of look-up keys (as saved in the database).
separator [Opt] string #13#10 The separator to be used between the labels.
Return
string
Usage
var labels = Efficy.getMultiValueLabels(80026, 'F_MULTIVAL', '1;2', ',');

Efficy.getOwner(editHandle)

Retrieves the key of the owner of the record.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
integer
Usage
Efficy.getOwner(editHandle);

Efficy.getQueryDataSet(queryHandle)

Retrieves the cached data set from a query handle.

Parameter Type Default value Description
queryHandle integer The handle of the query.
Return
TDataSet
Usage
function queryToJson() { var queryHandle = strToIntDef(Arguments.values('queryHandle'), 0), metaData = (Arguments.values('metaData').toUpperCase().charAt(0) === 'F') ? false : true, fields = Arguments.values('fields'), contexts = Arguments.values('contexts'), maxRecords = strToIntDef(Arguments.values('maxRecords'), 0), offSet = strToIntDef(Arguments.values('offSet'), 0), ds = Efficy.getQueryDataSet(queryHandle); return dataSetToJson(ds, metaData, fields, contexts, maxRecords, offSet); }

Efficy.getReferenceToGenerate(editHandle)

In BeforeCommit events, retrieves the key of the reference that will be applied when committing the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
double
Usage
var reference = Efficy.getReferenceToGenerate(editHandle)

Efficy.getSearchFields(entity)

Gets the fields of entity you can search for.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
olevariant
Usage
var searchFields = Efficy.getSearchFields(ntCont); if (varIsArray(searchFields)) { for (var i = varArrayLowBound(searchFields, 1); i <= varArrayHighBound(searchFields, 1); i++) { var fullName = varArrayElement(searchFields, i, 1); // fields are prefixed with table name // ... } }

Efficy.getSetting(module, aName, asString)

Introduced in Efficy 11.2 Retrieves the current value of a given Efficy setting.

Parameter Type Default value Description
module string The name of the module (JSON object) that owns the setting.
aName string The name of the setting.
asString [Opt] boolean False If true, the settings of type TDateTime will be returned as a string formatted with the ShortDateTime format. If false, it will be returned as a float value.
Return
string
Usage
var maxUsedDays = Efficy.getSetting('User', 'MaxUsedDays');

Efficy.getSysSettingsValue(aName)

Introduced in Efficy 11.2 Retrieves a value from the database table "SYS_SETTINGS".

Parameter Type Default value Description
aName string The name of the value.
Return
string
Usage
var settings = Efficy.getSysSettingsValue('ExtranetSettings');

Efficy.getSysStorageValue(aName)

Retrieves a value from the database table "SYS_STORAGE".

Parameter Type Default value Description
aName string The name of the value.
Return
string
Usage
var info = Efficy.getSysStorageValue('CustomInfo');

Efficy.getTranslatedFieldLabel(tableId, fieldName, language)

Introduced in Efficy 11.3 Retrieves the label of a field, translated in a specific language.

Parameter Type Default value Description
tableId integer The ID of the table.
fieldName string The name of the field.
language string The language of the translation.
Return
string
Usage
var tableId = Efficy.entityCatalog.tableIdFromEntityName(ntCont), field = 'NAME', language = Efficy.getUserLanguage(user) || 'EN'); var label = Efficy.getTranslatedFieldLabel(tableId, field, language) || Efficy.getFieldDisplayLabel2(tableId, field);

Efficy.getUserCode(userId)

Retrieves the code of the user userId.

Parameter Type Default value Description
userId integer The key of the user.
Return
string
Usage
var userCode = Efficy.getUserCode(Request.integerArgument('userId', -1));

Efficy.getUserId(userCode)

Retrieves the ID (key) of the user userCode.

Parameter Type Default value Description
userCode string The usercode of the user.
Return
integer
Usage
var userKey = Efficy.getUserId('ADMIN');

Efficy.getUserLanguage(userId)

Introduced in Efficy 11.3 Retrieves the language of the user userId.

Parameter Type Default value Description
userId integer The key of the user.
Return
string
Usage
var userLanguage = Efficy.getUserLanguage(user) || 'EN';

Efficy.getUserName(userId)

Retrieves the full name of the user userId.

Parameter Type Default value Description
userId integer The key of the user.
Return
string
Usage
var userName = Efficy.getUserName(Request.integerArgument('userId', -1));

Efficy.getUserNameFromCode(userCode)

Retrieves the full name of the user userCode.

Parameter Type Default value Description
userCode string The usercode of the user.
Return
string
Usage
var userName = Efficy.getUserNameFromCode('ADMIN');

Efficy.getUserNotification(entity)

Introduced in Efficy 11.3 Retrieves the user's default notifications configuration as a mask (configured in Default Notifications pages).

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
integer
Usage
Default notifications on Contacts
var contMask = Efficy.getUserNotification(ntCont);
Default workload notifications on Steps
var stepMask = Efficy.getUserNotification(ntWrkStep);

Efficy.getUserProperty(userId, propName)

Introduced in Efficy 11.3 Retrieves a property for a user.

Parameter Type Default value Description
userId integer The key of the user.
propName string The name of the property to be retrieved. Possible values are 'skill', 'securityrole'.
Return
olevariant
Usage
var skill = Efficy.getUserProperty(Efficy.currentUserRole(), 'skill');

Efficy.hasRightOnTable(entity, operation)

Tests whether the current user has the right to perform a certain operation on an entity.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
operation TSecurityCode The operation can be scRead (0), scWrite (1), scDelete (2), scInsert (3) or scExecute (4).
Return
boolean
Usage
var entityHandle = Efficy.entityCatalog.getEntityHandle('Acti'); var rights: { create: Efficy.hasRightOnTable(entityHandle, scInsert), read: Efficy.hasRightOnTable(entityHandle, scRead), update: Efficy.hasRightOnTable(entityHandle, scWrite), delete: Efficy.hasRightOnTable(entityHandle, scDelete) };

Efficy.hasSecurity(contextHandle, securityCode)

Introduced in Efficy 11.3 Tests whether the current user has a certain security on an edit/consult context.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
securityCode TSecurityCode The security can be scRead (0), scWrite (1), scDelete (2), scInsert (3), scExecute (4), scNativeSql (5), scSelect (6), scSecurity (7), scFullControl (8), scWriteSome (9).
Return
boolean
Usage
var contextHandle = Efficy.openConsultContext(entity); try { Efficy.consult(contextHandle, key, false); return Efficy.hasSecurity(contextHandle, scWrite) && Efficy.hasRightOnTable(entity, scWrite); } finally { Efficy.closeContext(contextHandle); }

Efficy.hasTeamRole(teamKind, roles, forcePlayer)

Introduced in Efficy 11.3 Tests whether the current user is part of Team with a certain role.

Parameter Type Default value Description
teamKind string Kind of Team (0 = Gamification, 1 = Project)
roles string ANY (Player or Leader), ALL (Player and Leader), PLAYER, LEADER
forcePlayer boolean For roles "PLAYER" and "LEADER": if current user is both Player and Leader, force the Player role.
Return
boolean
Usage
if (!Efficy.hasTeamRole(1, 'LEADER', false)) throw new Error('Security prevents changes to the project, ask your Team Leader to make the modification');

Efficy.indexFromCategory(editHandle, category)

Retrieves the table view index of a category in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
category string The name of the category.
Return
integer
Usage
var index = Efficy.indexFromCategory(Request.contextHandle, 'DOCU$INFO');

Efficy.indexFromDetail(editHandle, detail)

Retrieves the table view index of a detail entity in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
Return
integer
Usage
var index = Efficy.indexFromCategory(Request.contextHandle, ntCont);

Efficy.insertAttachment(editHandle, attachedFileType, path)

Inserts an attached file and returns the key (K_FILE).

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
attachedFileType TAttachedFileType The attachment type: ftInserted (1 = embedded), ftLinked (2 = linked), ftRemote (4 = remote), ftLarge (5 = large).
path string The path of the file that will be saved in the FILES.PATH field.
Return
double

Warning: This method does not actually upload the contents of the file in the database!
Use for instance Efficy.updateDetail2() to do so.

Usage
var contextHandle = Efficy.openEditContext(ntDocu, 0); try { for (var i = 0; i < attachments.length; i++) { var fileName = removeInvalidFileChars(attachments[i].filename); var fileKey = Efficy.insertAttachment(contextHandle, ftInserted, fileName); var fileStr = decodeMime64Utf8(attachments[i].data); Efficy.updateDetail2(contextHandle, ntFile, fileKey, 'STREAM', fileStr); Efficy.updateDetail2(contextHandle, ntFile, fileKey, 'FILESIZE', fileStr.length); Efficy.updateDetail2(contextHandle, ntFile, fileKey, 'PATH', fileName); Efficy.updateDetail2(contextHandle, ntFile, fileKey, 'COMMENT', fileName); } Efficy.commitChanges(contextHandle, false); } finally { Efficy.closeContext(contextHandle); }

Efficy.insertDetail(editHandle, detail, detailKey, relationId, linkMainComp)

Inserts a detail relation in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey double The detail key.
relationId integer Specify -1 to generate a new "K_RELATION" value.
linkMainComp boolean If true, automatically links the contact's main company when linking a contact.

Warning: Use this function when multiple relations are available on this detail relation. (The field "K_RELATION" exists in the database table.)
Use Efficy.setUsers() to link users.

Usage
var contextHandle = Efficy.openEditContext(ntDocu, 0); try { Efficy.copyDetails2(contextHandle, ntMail, mailId, [ntUser, ntComp, ntCont, ntProj, ntCase, ntOppo], true, false); Efficy.insertDetail(contextHandle, ntMail, mailId, 0, true); Efficy.commitChanges(contextHandle, false); } finally { Efficy.closeContext(contextHandle); }

Efficy.insertDetail2(editHandle, detail, detailKey, linkMainComp)

Inserts a detail relation in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey double The detail key.
linkMainComp boolean When linking a contact, automatically links the contact's main company.

Warning: Use this function when multiple relations are available on this detail relation. (The field "K_RELATION" exists in the database table.)
Use Efficy.setUsers() to link users.

Usage
var contextHandle = Efficy.openEditContext(ntDocu, masterKey); try { Efficy.copyDetails2(contextHandle, ntMail, mailId, [ntUser, ntComp, ntCont, ntProj, ntCase, ntOppo], true, false); Efficy.insertDetail2(contextHandle, ntMail, mailId, false); Efficy.commitChanges(contextHandle, false); } finally { Efficy.closeContext(contextHandle); }

Efficy.isConfidential(editHandle)

Tests whether the edited record is confidential (only the owner has visibility on the record).

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
boolean
Usage
var isConfidential = Efficy.isConfidential(editHandle);

Efficy.isCurrentUserInGroup(groupId)

Tests whether the current user belongs to the group groupId.

Parameter Type Default value Description
groupId integer The key of the group.
Return
boolean
Usage
var inSales = Efficy.isCurrentUserInGroup(Efficy.getUserId('EFF_SALES'));

Efficy.isGroup(userId)

Tests whether userId is a group.

Parameter Type Default value Description
userId integer The key of a group/user.
Return
boolean
Usage
var salesIsGroup = Efficy.isGroup(Efficy.getUserId('EFF_SALES'));

Efficy.isGroupMember(userId, groupId)

Tests whether userId belongs to the group groupId.

Parameter Type Default value Description
userId integer The key of the user.
groupId integer The key of the group.
Return
boolean
Usage
var currentUserInSales = Efficy.isGroupMember(Efficy.currentUserId(), Efficy.getUserId('EFF_SALES'));

Efficy.isLookupFieldByReference(tableId, fieldName)

Tests whether the field is a look-up field by reference (using look-up keys instead of labels).

Parameter Type Default value Description
tableId integer The ID of the table.
fieldName string The name of the field.
Return
boolean
Usage
Efficy.isLookupFieldByReference(Efficy.entityCatalog.tableIdFromEntity(ntComp), 'KIND'); // true
Efficy.isLookupFieldByReference(Efficy.entityCatalog.tableIdFromEntity(ntActi), 'MODE'); // false

Efficy.isRecentRecorded(entity)

Tests whether a list of recent items is kept for the specified entity.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
boolean
Usage
if (Efficy.isRecentRecorded(ntCase)) { Efficy.addRecent(ntCase, caseKey, caseName); }
Efficy.isRecentRecorded(Efficy.entityCatalog.getEntityHandle('Time')); // false

Efficy.isUserActive(userId)

Introduced in Efficy 11.3 Returns true if the user is active.

Parameter Type Default value Description
userId integer The key of the user.
Return
boolean
Usage
if (Efficy.isUserActive(Efficy.getUserId('RACHEL')) { ... }

Efficy.languageName(long)

Returns the current user language as text.

Parameter Type Default value Description
long [Opt] boolean False If true, returns the full language name instead of the 2-letters code.
Return
string
Usage
var shortLang = Efficy.languageName(); // "EN", "FR", ... var longLang = Efficy.languageName(true); // "English (EN)", "Français (FR)", ...

Efficy.lockedByAccount(editHandle)

Retrieves the key of the user that have locked the record.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
integer
Usage
var contextHandle = Efficy.openEditContext(ntActi, appoId); try { if (Efficy.lockedByAccount(contextHandle) !== Efficy.currentUserId()) return Request.translate('This information is read-only!'); } finally { Efficy.closeContext(contextHandle); }

Efficy.log(msg)

While executing a scheduled script or a data synchronization script, the log function lets you add a string in the log file of the Data Sync tool or the Efficy service Task Scheduler.

Parameter Type Default value Description
msg string The text to be logged.
Usage
Efficy.log('Initialize...'); Efficy.log('> Retrieve database settings'); Efficy.log('> Retrieve user settings'); Efficy.log('Start...'); Efficy.log('Finished!');

Efficy.mergeEmailTemplate(editHandle, idTemplate, mergeArguments, subject)

Merges a document template (usually in HTML format) and returns the result as a string.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
idTemplate double The document template to merge.
mergeArguments TEnhStringList The list of additional arguments for the merge operation (can be null).
subject string If the template defines a subject text, the merged subject is returned in this variable.
Return
utf8string
Usage
var contextHandle = Request.contextHandle; var templateId = Request.floatArgument('template', 0); var subject; var memo = Efficy.mergeEmailTemplate(docuContext, templateId, null, subject);

Efficy.mergeEmailTemplateVariant(editHandle, idTemplate, mergeArguments)

Merges a document template (usually in HTML format) and returns the result as a varArray of strings with the subject.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
idTemplate double The document template to merge.
mergeArguments TEnhStringList The list of additional arguments for the merge operation (can be null).
Return
olevariant
Usage
var mergeArguments = TEnhStringList.create(); var editHandle = Efficy.openEditContext(ntCont, contId); try { mergeArguments.values('PasswordUrl') = passwordUrl; var mergeResult = Efficy.mergeEmailTemplateVariant(editHandle, templateId, mergeArguments); var body = varArrayElement(mergeResult, 0), subject = varArrayElement(mergeResult, 1); } finally { mergeArguments.free(); Efficy.closeContext(editHandle); }

Efficy.mergeTemplate(editHandle, idTemplate, mergeArguments, pdfWithAttachments)

Merges a document template and inserts the result as a new attachment. The return value is the key of the new attachment.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
idTemplate double The document template to merge.
mergeArguments TEnhStringList The list of additional arguments for the merge operation (can be null).
pdfWithAttachments [Opt] boolean False If true, merges to a .pdf including the attachments.
Return
double
Usage
function addTemplateWithoutReference(docuContext, template, mergeArguments) { if (template) { var contextHandle = Efficy.openConsultContext(ntTmpl); try { var ds = Efficy.consult(contextHandle, template, true); // Copy Comp/Cont/Proj Efficy.copyDetails(docuContext, contextHandle, [ntComp, ntCont, ntProj], false, false); } finally { Efficy.closeContext(contextHandle) } // Run template return Efficy.mergeTemplate(docuContext, template, mergeArguments); } }

Efficy.mobileVersion()

Returns the compatible version of mobile application.

Return
string
Usage
if (Efficy.mobileVersion() === '11.3') { ... }

Efficy.modified(editHandle)

Tests whether any changes have been made in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
boolean
Usage
if (Efficy.modified(editHandle)) var oldValue = Efficy.oldFieldValue(editHandle, 0, fieldName);

Efficy.oldCategoryFieldValue(editHandle, category, fieldName)

Retrieves the initial value of a category data set field of any type but string at the start of the edit operation.
The values are reset when Efficy.commitChanges() is executed.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
category string The name of the category.
fieldName string The name of the field.
Return
olevariant

Warning: Always test whether a field has been modified in the category, using Efficy.categoryModified(), before you try to retrieve an old value.

Usage
if (Efficy.categoryModified(editHandle, 'DOCU$INVOICING', 'EXPENSES')) var oldValue = Efficy.oldCategoryFieldValue(editHandle, 0, 'EXPENSES');

Efficy.oldCategoryStringFieldValue(editHandle, category, fieldName)

Retrieves the initial value of a category data set field of type string at the start of the edit operation.
The values are reset when Efficy.commitChanges() is executed.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
category string The name of the category.
fieldName string The name of the field.
Return
string

Warning: Always test whether a field has been modified in the category, using Efficy.categoryModified(), before you try to retrieve an old value.

Usage
if (Efficy.categoryModified(editHandle, category, fieldName)) var oldValue = Efficy.oldCategoryStringFieldValue(editHandle, 0, fieldName);

Efficy.oldFieldValue(editHandle, tableViewIndex, fieldName)

Retrieves the initial value of a master data set field of any type but string at the start of the edit operation.
The values are reset when Efficy.commitChanges() is executed.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
tableViewIndex integer Specify 0 to retrieve the main item data.
fieldName string The name of the field.
Return
olevariant

Warning: Always test whether a field has been modified, using Efficy.modified(), before you try to retrieve an old value.

Usage
if (Efficy.modified(editHandle)) var oldValue = Efficy.oldFieldValue(editHandle, 0, fieldName);

Efficy.oldStringFieldValue(editHandle, tableViewIndex, fieldName)

Retrieves the initial value of a master data set field of type string at the start of the edit operation.
The values are reset when Efficy.commitChanges() is executed.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
tableViewIndex integer Specify 0 to retrieve the main item data.
fieldName string The name of the field.
Return
string

Warning: Always test whether a field has been modified, using Efficy.modified(), before you try to retrieve an old value.

Usage
if (Efficy.modified(editHandle)) var oldValue = Efficy.oldStringFieldValue(editHandle, 0, fieldName);

Efficy.openConsultContext(entity, forceNewContext, lockContext)

Opens a consult context for the Entity.
A context remains memory-resident (on the web server) until it is closed. Always match an Efficy.openConsultContext() with a Efficy.closeContext() call to avoid memory consumption.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
forceNewContext [Opt] boolean False If true, does not use cached context.
lockContext [Opt] boolean True If true, does not share the context.
Return
TContextHandle
Usage
var contextHandle = Efficy.openConsultContext(ntWrkStage); try { var ds = Efficy.consult(contextHandle, key, true); var status = ds.fieldByName('STATUS').asFloat; } finally { Efficy.closeContext(contextHandle); }

Efficy.openEditContext(entity, key, consultOnly)

Opens an edit context for the record identified by entity and key.
A context remains memory-resident (on the web server) until it's destroyed again. Always match an Efficy.openEditContext() with a Efficy.closeContext() call to avoid memory consumption.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key olevariant The key of the record. Use key = 0 to create a new record.
consultOnly [Opt] boolean False If true, makes the context "read-only" – you won't be able to change any field in it.
Return
TContextHandle
Usage
var contextHandle = Efficy.openEditContext(ntActi, 67); try { var ds = Efficy.getMasterDataSet(contextHandle, 0); var date = ds.fieldByName('D_BEGIN').asFloat; } finally { Efficy.closeContext(contextHandle); }
var contextHandle = Efficy.openEditContext(entityHandle, relKey, true); try { var ds = Efficy.getDetailDataSet(contextHandle, ntUser); ds.first(); while (!ds.eof) { if (ds.fieldByName('ISACTIVE').asString !== '2') // Invisible relations (notifications and/or security) userIdList.push(ds.fieldByName('K_USER').asFloat); ds.next(); } } finally { Efficy.closeContext(contextHandle); }

Efficy.openEditContextRelation(entity, detail, key, detailKey, relationId)

Opens an edit context for a relation. If the relation does not yet exist, it is created.
A context remains memory-resident (on the web server) until it's destroyed again. Always match an Efficy.openEditContextRelation() with a Efficy.closeContext() call to avoid memory consumption.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
key double The key of the entity.
detailKey double The key of the detail.
relationId integer The key of the relation if multi-relation is available.
Return
TContextHandle

Warning: Use Efficy.openEditContextRelation2() when no multiple relations are available on this detail relation. (The field "K_RELATION" doesn't exist in the database table.)

Usage
var contextHandle = Efficy.openEditContextRelation(ntDocu, ntProd, docuKey, prodKey, relationKey); try { var ds = Efficy.getMasterDataSet(contextHandle, 0); ds.edit(); ds.fieldByName('QUANTITY').asInteger = -1; Efficy.commitChanges(contextHandle, false); } finally { Efficy.closeContext(contextHandle); }

Efficy.openEditContextRelation2(entity, detail, key, detailKey)

Opens an edit context for a relation. If the relation does not yet exist, it will be created.
A context remains memory-resident (on the web server) until it's destroyed again. Always match an Efficy.openEditContextRelation2() with a Efficy.closeContext() call to avoid memory consumption.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
key double The key of the entity.
detailKey double The key of the detail.
Return
TContextHandle

Warning: Use Efficy.openEditContextRelation() when multiple relations are available on this detail relation. (The field "K_RELATION" exists in the database table.)

Usage
var contextHandle = Efficy.openEditContextRelation2(ntProf, ntCont, profKey, contKey); try { Efficy.updateField(contextHandle, 0, 'SUBSCRIBED', subscribed ? "1" : "0"); Efficy.updateField(contextHandle, 0, 'EMAILFIELD', emailKey); Efficy.commitChanges(contextHandle, false); } finally { Efficy.closeContext(contextHandle); }

Efficy.openSearchContext(entity)

Opens a consult (search) context for the entity.
A context remains memory-resident (on the web server) until it's destroyed again. Always match an Efficy.openSearchContext() with a Efficy.closeContext() call to avoid memory consumption.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
TContextHandle
Usage
var contextHandle = Efficy.openSearchContext(entityHandle); try { var ds = Efficy.search(contextHandle, 'SEARCHFAST', '', searchValue, false, true, false, '', true, false); } finally { Efficy.closeContext(contextHandle); }

Efficy.openTemporaryContext()

Opens a temporary context without Entity. Typically used to run a Efficy.consultQuery() request.
You don't need to close the temporary context, Efficy handles this automatically!

Return
TContextHandle
Usage
var contextHandle = Efficy.openTemporaryContext(), params = [Efficy.currentUserId()]; var ds = Efficy.executeSystemSqlQuery(0, contextHandle, 'select * from <#TABLE name="ACC_ACCOUNTS" where K_USER = :param1', params.join('\n'), true, true, 0);

Efficy.openUrl(url, request)

Sends a request to an external url and retrieves the response as text (to avoid browser security issues).

Parameter Type Default value Description
url string The external URL to be queried.
request string The request to be sent to the external server as text (can be SOAP).
Return
string
Usage
var response = Efficy.openURL('GET https://jsonplaceholder.typicode.com/posts/1', requestContent);

Efficy.openUrl2(url, request, requestHeader)

Sends a request to an external url and retrieves the response as text (to avoid browser security issues).
Can also return the response code instead of the response text, by adding an additional parameter in the requestHeader: EffHttpStatus:true

Parameter Type Default value Description
url string The external URL to be queried.
request string The request to be sent to the external server as text (can be SOAP).
requestHeader string The request header to be sent to the external server.
Return
string
Usage
var requestHeader = '', headersSL = TEnhStringList.create(); try { headersSL.add('Content-Type: application/json; charset=utf-8'); headersSL.add('EffHttpStatus: true'); requestHeader = headersSL.text; } finally { headersSL.free(); } var response = Efficy.openURL2('GET https://jsonplaceholder.typicode.com/posts/1', requestContent, requestHeader);

Efficy.openUrlSecure(url, postedValues, headers, method, clientCertName, basicLogin, basicPassword)

Sends a request to an external url with optional headers, method, Mutual SSL or Basic HTTP authentication. Both authentication methods are mutually exclusive.
The method returns an object with properties success, statusCode, body and headers.
"success" is true when the HTTP statusCode is in the 200-2xx range.

{ success: true, 
  statusCode: 200, 
  body: "This is the response body contents", 
  headers: "HTTP/1.x 200 OK
    Content-Type: text/html; charset=UTF-8
    Cache-Control: max-age=3600, public ..." }

Parameter Type Default value Description
url string The external URL to be queried.
postedValues string The request to be sent to the external server as text (can be SOAP).
headers [Opt] string '' Extra headers to be sent with the request.
method [Opt] string '' Http method used to send the request: can be empty or one of the following values: POST, GET, HEAD, PUT, DELETE, OPTIONS, PATCH, TRACE. Optional, when empty a standard POST or GET will be used.
clientCertName [Opt] string '' The name of the certificate used for mutual SSL authentication. The certificate is retrieved from the Windows Certificate Store "MY" (Certificates Current User > Personal > Certificates).
basicLogin [Opt] string '' The user name used for Basic HTTP authentication.
basicPassword [Opt] string '' The password used for Basic HTTP authentication.
Return
TOpenURLResult
Usage
Example with custom verb, custom header and JSON data
var data = {firstName: 'John', lastName: 'Doe', age: 37}; var response = Efficy.openUrlSecure('http://httpbin.org/put', JSON.stringify(data), 'X-Custom-Sample: true', 'PUT'); if (response.success) { Efficy.log(response.statusCode + '/' + response.body + '/' + response.headers); }
Example with Basic HTTP authentication
var response = Efficy.openUrlSecure('http://httpbin.org/basic-auth/testuser/testpass', '', '', 'GET', '', 'testuser', 'testpass');
Example with SSL Client Certificate authentication
var response = Efficy.openUrlSecure('https://prod.idrix.eu/secure/', '', '', 'GET', 'TestCertName');

Efficy.parentAlias()

Retrieves the alias of the parent database.
Returns an empty string when the current database is not a child.

Return
string
Usage
var parentAlias = Efficy.parentAlias;

Efficy.parentEntityKey(entity, key)

Retrieves the parent of the entity identified by key.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key double The key of the entity.
Return
double
Usage
var parentEntityKey = Efficy.parentEntityKey(ntProj, 571);

Efficy.parentProductKey(key)

Retrieves the parent of the product identified by key.

Parameter Type Default value Description
key double The key of the product.
Return
double
Usage
var parentProductKey = Efficy.parentProductKey(155);

Efficy.parentProjectKey(key)

Retrieves the parent of the project identified by key.

Parameter Type Default value Description
key double The key of the project.
Return
double
Usage
var parentProjectKey = Efficy.ParentProjectKey(571);

Efficy.pmuActive()

Tests if Peak Me Up is active for the current user.

Return
boolean
Usage
if (Efficy.pmuActive()) { ... }

Efficy.pmuAddItem(entity, key, itemTypeId, quantity, comment)

Creates a Peak Me Up item for the current user on a given entity.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key double The key of the entity.
itemTypeId double The key of the Peak Me Up item type.
quantity double The quantity of the Peak Me Up item.
comment string An optional comment.
Usage
var actionKey = 5273, itemTypeID = 579, quantity = 1, comment = 'Efficy created PMU item'; Efficy.pmuAddItem(ntActi, actionKey, itemTypeID, quantity, comment);

Efficy.pmuCloseOrphan(entity, key, orphanId, pushDelete, k_User)

Removes a Peak Me Up orphan from the table and creates the PMU Item.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key double The key of the entity.
orphanId double The key of the Peak Me Up orphan.
pushDelete boolean Introduced in Efficy 11.1 If true, the item will also be deleted from PMU.
k_User [Opt] integer 0 The key of the user. If not provided, the current user key will be used.

If entity and key are set to 0, no Item is created. In that case, if pushDelete is set to true, the item will also be deleted from PMU.

Usage
Simple delete of the orphan with delete in PMU
Efficy.pmuCloseOrphan(0, 0, orphanID, true);
Close orphan and link it to an efficy element
Efficy.pmuCloseOrphan(ntActi, kAction, kOrphan, false);

Efficy.pmuEntityHasItem(entity, key)

Tests if a Peak Me Up item has already been set to an entity instance.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key double The key of the entity.
Return
boolean
Usage
var hasItem = Efficy.pmuEntityHasItem(ntActi, actionKey);

Efficy.pmuInvolved(entity)

Tests if there are Peak Me Up ItemTypes linked to the entity.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
boolean

Efficy.positionDetail(editHandle, detail, detailKey, relationId)

Positions a detail data set on the record identified by detailKey and optionally relationId.
Returns false if the specified detail record cannot be found.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey double The key of the detail.
relationId [Opt] integer MULTIRELATION_NONE The key of the relation if multi-relation is available.
Return
boolean
Usage
if(Efficy.positionDetail(contextHandle, ntProd, prodDS.FieldByName('K_PRODUCT').asFloat, prodDS.FieldByName('K_RELATION').asFloat)) // Do something on this detail

Efficy.postSecurity(editHandle, securityList)

Posts the security defined in the securityList argument or previously defined with Efficy.setSecurityUsers().
If the securityList argument is provided, it will overwrite any previous user lists or security values set by Efficy.setSecurityUsers() or Efficy.setUserSecurity()!.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
securityList [Opt] string '' Introduced in Efficy 11.2 The array of user ids and security values, separated by a semicolon in the following format: K_USER=SECURITY (ex: 2=271;4=15;5=7).

The security is handled internally into an intermediate object, not directly into the data set.
This function applies the security of this object into the data set. If not called, changes made are lost when closing the context.

The security value is a sum of one or more of the following values: 1 (search), 2 (read), 4 (write), 8 (delete) and 256 (secure)
Useful combinations are 7 (read/write), 15 (read/write/delete) and 271 (full control = read/write/delete/secure).

List of security codes
ACCESSCODE_SEARCH = 1
ACCESSCODE_READ = 2
ACCESSCODE_WRITE = 4
ACCESSCODE_DELETE = 8
ACCESSCODE_SHOWCONTENT = 16
ACCESSCODE_ADDCONTENT = 32
ACCESSCODE_MODIFYCONTENT = 64
ACCESSCODE_DELETECONTENT = 128
ACCESSCODE_SECURE = 256
ACCESSCODE_SECURECONTENT = 512
ACCESSCODE_NOCONTENT = 2048

A few common combinations
ACCESSCODE_READ_WRITE = ACCESSCODE_SEARCH + ACCESSCODE_READ + ACCESSCODE_WRITE;
ACCESSCODE_READ_WRITE_DELETE = ACCESSCODE_READ_WRITE + ACCESSCODE_DELETE;
ACCESSCODE_READ_WRITE_SECURE = ACCESSCODE_READ_WRITE + ACCESSCODE_SECURE;
ACCESSCODE_FULLCONTROL = ACCESSCODE_READ_WRITE_DELETE + ACCESSCODE_SECURE;
ACCESSCODE_CONTENTFULLCONTROL = ACCESSCODE_SEARCH + ACCESSCODE_SHOWCONTENT + ACCESSCODE_MODIFYCONTENT + ACCESSCODE_ADDCONTENT + ACCESSCODE_DELETECONTENT + ACCESSCODE_SECURECONTENT;

Usage
Efficy.postSecurity(editHandle, '2=271;4=15;5=7');

Efficy.readBoolean(section, parameterName, defaultValue)

Reads a boolean value from user options.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
defaultValue boolean The default value if the option is not found.
Return
boolean
Usage
Efficy.readBoolean('DcpSettings', 'MemoFormatted', false);

Efficy.readInteger(section, parameterName, defaultValue)

Reads an integer value from user options.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
defaultValue integer The default value if the option is not found.
Return
integer
Usage
Efficy.readInteger('DcpSettings', 'MaxUsedDays', 90);

Efficy.readSessionBoolean(section, parameterName, defaultValue)

Reads a non-persistent boolean value stored into the user session.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
defaultValue boolean The default if the value is not found.
Return
boolean
Usage
Efficy.readSessionBoolean('custom', 'customInfo', false);

Efficy.readSessionFloat(section, parameterName, defaultValue)

Reads a non-persistent float value stored into the user session.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
defaultValue double The default if the value is not found.
Return
double
Usage
Efficy.readSessionFloat('custom', 'customInfo', 0.5);

Efficy.readSessionInteger(section, parameterName, defaultValue)

Reads a non-persistent integer value stored into the user session.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
defaultValue integer The default if the value is not found.
Return
integer
Usage
Efficy.readSessionInteger('custom', 'customInfo', 1);

Efficy.readSessionString(section, parameterName, defaultValue)

Reads a non-persistent string value stored into the user session.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
defaultValue string The default if the value is not found.
Return
string
Usage
Efficy.readSessionString('custom', 'customInfo', 'abc');

Efficy.readString(section, parameterName, defaultValue)

Reads a string value from user options.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
defaultValue string The default value if the option is not found.
Return
string
Usage
Efficy.readString('DcpSettings', 'DefaultLanguage', 'EN');

Efficy.releaseRecord(editHandle)

Releases the lock on a record and returns the key of the user that locked the record.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
integer
Usage
var contextHandle = Efficy.openEditContext(ntActi, key); try { // ... Efficy.commitChanges(contextHandle false); } finally { Efficy.releaseRecord(contextHandle); Efficy.closeContext(contextHandle); }

Efficy.removeRecent(entity, key, itemName, gridName)

Removes the record identified by entity and key from the list of recent items.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key double The key of the entity.
itemName [Opt] string '' For recent user lists, the name of the userlist to remove.
gridName [Opt] string '' For recent user lists, the grid name (e.g. Agenda)
Usage
if (Efficy.isRecentRecorded(ntCont)) Efficy.removeRecent(ntCont, 5);

Efficy.removeUsers(editHandle, users)

Only removes the user if (s)he is linked visibly.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
users olevariant The user key or an array of users keys.
Return
boolean
Usage
Efficy.removeUsers(editHandle, varArrayOf([2, 5, 6]));

Efficy.revokeSysTokens(entity, key, version)

Introduced in Efficy 11.2 Revoke all the sharing tokens for a specified Document or File

Parameter Type Default value Description
entity TEntityHandle Can be ntDocu or ntFile to share either a whole document or a single file.
key double The key of the document or of the file.
version integer The version if a single file is shared. Otherwise value is ignored.
Return
integer
Usage
Efficy.revokeSysTokens(ntDocu, 9);
Efficy.revokeSysTokens(ntFile, 123, 1);

Efficy.search(contextHandle, searchField, orderByFields, searchValue, ownOnly, contains, openedOnly, category, forceRefresh, getAllRecords, queryViewText)

Performs a search on the database and returns the data set with search results.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (search, consult or edit).
searchField string The field to be searched. Special values SEARCHFAST, SEARCHFULL, SEARCHTEXT, SEARCHFILENAME, SEARCHFILE correspond to the search options in the web application user interface.
orderByFields string The sort order, a semicolon (;) separated list of fields.
searchValue string The value to search.
ownOnly [Opt] boolean False If true, search own records only.
contains [Opt] boolean False If true, allow matches on part of field.
openedOnly [Opt] boolean True If true, search for opened or active records only.
category [Opt] string '' If non-empty, only search for records of the category.
forceRefresh [Opt] boolean True If true, never uses cached results.
getAllRecords [Opt] boolean True If true, retrieves all records in a single call instead of page per page.
queryViewText [Opt] string '' Introduced in Efficy 11.3 The query view text that will be added.
Return
TDataSet
Usage
var ds = Efficy.search(compContext, 'NAME', 'COMPANIES.NAME desc', 'unicef');
var ds = Efficy.search(searchContext, 'SEARCHFAST', '', 'unicef france', false, true);

Efficy.sendExternalMail(sendFrom, sendTo, sendCc, subject, body, entity, idLinked, sendCode)

Sends an e-mail to external recipients (non-Efficy users).

Parameter Type Default value Description
sendFrom string The sender's e-mail address.
sendTo string A semicolon-separated list of "To" recipients (e-mail addresses).
sendCc string A semicolon-separated list of "Cc" recipients (e-mail addresses).
subject string The subject of the e-mail message.
body string The body of the e-mail message.
entity [Opt] TEntityHandle ntNone The entity handle to insert a direct link to a record in the e-mail body.
idLinked [Opt] double 0 The entity key to insert a direct link to a record in the e-mail body.
sendCode [Opt] string '' Can be not specified, empty or a combination of the following values:
'U': Efficy won't add a URL to the mail body.
'S': Efficy won't save the e-mail message in the database.
Return
double

The sendCode parameter is handy for the campaigns, to send external mails that are linked to a contact record without adding a URL to the mail body. (The URL is meaningless for the recipient of the e-mail message.)

Usage
Send an e-mail message without URL that gets saved in the database linked to the contact
Efficy.sendExternalMail(sendFrom, sendTo, sendCc, subject, body, ntCont, contKey, 'U');

Efficy.sendMailToUsers(sendTo, sendCc, subject, body, entity, idLinked, sendCode)

Sends an e-mail message to Efficy users.

Parameter Type Default value Description
sendTo string A semicolon-separated list of "To" recipients (user code or full name).
sendCc string A semicolon-separated list of "Cc" recipients (user code or full name).
subject string The subject of the e-mail message.
body string The body of the e-mail message.
entity [Opt] TEntityHandle ntNone The entity handle to insert a direct link to a record in the e-mail body.
idLinked [Opt] double 0 The entity key to insert a direct link to a record in the e-mail body.
sendCode [Opt] string '' Can be not specified, empty or a combination of the following values:
'U': Efficy won't add a URL to the mail body.
'S': Efficy won't save the e-mail message in the database.
Return
double

The sendCode parameter is handy for the SpyCase script to send internal mails including a URL to the case without saving the mail to the database.

Usage
Efficy.sendMailToUsers(sendTo, sendCc, subject, body, ntCont, contKey, 'U');

Efficy.sendNotification(subject, body, users, customParams, entity, key)

Adds an information to the notification feed of one or several users. Groups are allowed.

Parameter Type Default value Description
subject string The text of the collapsed notification.
body string The content shown when expanding the notification.
users olevariant The list of users to be notified.
customParams [Opt] string '' The extra parameters provided to the notification JSON object
entity [Opt] TEntityHandle ntNone Introduced in Efficy 11.1 Entity to which the notification is linked
key [Opt] double 0 Introduced in Efficy 11.1 Key of the entity to which the notification is linked
Usage
Notify a user that a campaign has been succefully sent
Efficy.sendNotification( 'Campaign successfully sent!', format('<i class="i-info"></i><span>The campaign has been sent to $0 contacts</span>', contextEncodeText(contacts.length)), [userId], '', ntPubl, efficyKey )
Send a timesheet reminder to users
Efficy.sendNotification('Timesheet reminder', 'Hello, please fill in your timesheet for the period from 01/01/2019 to 01/02/2019.', users, '', ntTime);

Efficy.setCategories(editHandle, selectedCategories)

Activates some categories.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
selectedCategories TStrings A string list of category names.
Return
boolean
Usage
The following function is similar to calling Efficy.activateCategory(Request.contextHandle, 'DOCU$INVOICING')
function activateCategory(contextHandle, category) { var isActive = false; var sl = TEnhStringList.create(); try { Efficy.getCategories(contextHandle, sl, false); if (sl.indexOf(category) < 0) { sl.add(category); isActive = Efficy.setCategories(contextHandle, sl); } else { isActive = true; } } finally { sl.free(); } return isActive; } activateCategory(Request.contextHandle, 'DOCU$INVOICING');

Efficy.setChangeLogUserName(logUserName)

Introduced in Efficy 11.2 Sets the user name to be used in SYS_CHANGED when creating the record history.

Parameter Type Default value Description
logUserName string The user name to be used (currently limited to 32 characters).

Typical use case is an import script (run with Administrator user) that imports records, assign them to users and create a record history related to the user.

Usage
var editHandle = Efficy.openEditContext(ntProj, 0); try { //... Efficy.setChangeLogUserName('USERTEST'); Efficy.commitChanges(editHandle, true); } finally { Efficy.CloseContext(editHandle); }

Efficy.setReference(editHandle, referenceId)

Requests that a unique reference number be generated when committing the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
referenceId double The key of the reference.
Usage
function fillInfoFromTemplate(docuContext, templateKey) { var contextHandle = Efficy.openConsultContext(ntTmpl); try { var ds = Efficy.consult(contextHandle, templateKey, true); Efficy.updateField(docuContext, 0, 'NAME', ds.fieldByName('NAME').asString); Efficy.copyDetails(docuContext, contextHandle, [ntComp, ntCont, ntProj], false, false); var reference = ds.fieldByName('K_REFERENCE').asFloat; if (reference) Efficy.setReference(docuContext, reference); } finally { Efficy.closeContext(contextHandle); } Efficy.commitChanges(docuContext, true); }

Efficy.setSecurityUsers(editHandle, users)

Adds each user of the users array in the record's security. These users have the default security.
Users not in the users array are deleted from the record's security.
Call Efficy.postSecurity() after Efficy.setSecurityUsers() to make the changes effective.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
users array of integer The array of users ID.
Usage
Efficy.setSecurityUsers(editHandle, [2, 5]);

Efficy.setSysStorageValue(aName, value)

Saves a value to the database table "SYS_STORAGE".

Parameter Type Default value Description
aName string The name of the value.
value string The value.
Usage
Efficy.setSysStorageValue('customStorageItem', 'customStorageValue');

Efficy.setUsers(editHandle, users, clearUsers, explodeGroups)

Sets the user relations.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
users olevariant The array of user IDs (keys).
clearUsers boolean If true, clears the current user selection.
explodeGroups [Opt] boolean False If true, links all members of the specified groups.
Return
boolean
Usage
Efficy.setUsers(contextHandle, [Efficy.currentUserId()], false, false);

Efficy.setUserSecurity(editHandle, userId, securityValue)

Sets the security for a user or group.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
userId integer The user id or group id for which security is added.
securityValue integer The security value.

The security value is a sum of one or more of the following values: 1 (search), 2 (read), 4 (write), 8 (delete) and 256 (secure)
Useful combinations are 7 (read/write), 15 (read/write/delete) and 271 (full control = read/write/delete/secure).

List of security codes

ACCESSCODE_SEARCH = 1
ACCESSCODE_READ = 2
ACCESSCODE_WRITE = 4
ACCESSCODE_DELETE = 8
ACCESSCODE_SHOWCONTENT = 16
ACCESSCODE_ADDCONTENT = 32
ACCESSCODE_MODIFYCONTENT = 64
ACCESSCODE_DELETECONTENT = 128
ACCESSCODE_SECURE = 256
ACCESSCODE_SECURECONTENT = 512
ACCESSCODE_NOCONTENT = 2048

A few common combinations

ACCESSCODE_READ_WRITE = ACCESSCODE_SEARCH + ACCESSCODE_READ + ACCESSCODE_WRITE;
ACCESSCODE_READ_WRITE_DELETE = ACCESSCODE_READ_WRITE + ACCESSCODE_DELETE;
ACCESSCODE_READ_WRITE_SECURE = ACCESSCODE_READ_WRITE + ACCESSCODE_SECURE;
ACCESSCODE_FULLCONTROL = ACCESSCODE_READ_WRITE_DELETE + ACCESSCODE_SECURE;
ACCESSCODE_CONTENTFULLCONTROL = ACCESSCODE_SEARCH + ACCESSCODE_SHOWCONTENT + ACCESSCODE_MODIFYCONTENT + ACCESSCODE_ADDCONTENT + ACCESSCODE_DELETECONTENT + ACCESSCODE_SECURECONTENT;

The SECURITY field contains a combination of all these values, "normal" record security and security on the contents taken together.

Usage
Efficy.setUserSecurity(editHandle, Efficy.currentUserId(), 32); // add content
Example to check if a user has the permission to add content into a main entity
if ((userDs.fieldByName('SECURITY').asInteger & 32) === 32) { ... }

Efficy.sqlQueryDataset(sql, params, storeId)

Executes a SQL query and returns the resulting data set.

Parameter Type Default value Description
sql string The SQL select instruction.
params string The values of the parameters in the SQL select, each parameter on a new line (separated by "\n" in JavaScript).
storeId [Opt] integer 0 An integer value which identifies the store in which the data set will be kept. Successive calls with an identical storeId reuse the same data set. (optional)
Return
TDataSet
Usage
var ds = Efficy.sqlQueryDataSet('select * from <#TABLE name="LK_WRK_STATUS"> order by K_STATUS', '');
var ds = Efficy.sqlQueryDataSet('select * from <#TABLE name="ACC_ACCOUNTS"> where K_USER = :param1', [Efficy.currentUserId()].join('\n'), 1);

Efficy.sqlQueryValue(sql, params, defaultValue)

Executes a SQL query and returns the value of the first field of the first record. Used to retrieve a single value from the database.

Parameter Type Default value Description
sql string The SQL select instruction.
params string The values of the parameters in the SQL select, each parameter on a new line (separated by "\n" in JavaScript).
defaultValue variant The default value if the query does not return any results.
Return
variant
Usage
var mailKey = Efficy.sqlQueryValue('select <#FIELD name="K_MAIL"> from <#TABLE name="MAILS"> where <#FIELD name="GMAIL_ID"> = :param1', messageId, 0);

Efficy.updateCategory(editHandle, category, fieldNames, fieldValues, ignoreInaccessibleCategory)

Updates field values of a category data set in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
category string The name of category to update.
fieldNames olevariant The array of fields to update.
fieldValues olevariant The array of field values. The number of elements in both arrays must be identical.
ignoreInaccessibleCategory [Opt] boolean False If true, does not throw exception if the category is not active.
Usage
Efficy.activateCategory(editHandle, 'PROF$EMAILING'); Efficy.updateCategory(editHandle, 'PROF$EMAILING', 'FLEXKIND', '2');

Efficy.updateCategoryField(editHandle, category, fieldName, fieldValue, ignoreInaccessibleCategory)

Updates the value of a field of any type but string in a category data set in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
category string The name of category to update.
fieldName string The name of the field.
fieldValue olevariant The new value.
ignoreInaccessibleCategory [Opt] boolean False If true, does not throw exception if the category is not active.
Usage
Efficy.activateCategory(editHandle, 'DOCU$INVOICING'); Efficy.updateCategoryField(editHandle, 'DOCU$INVOICING', 'CURRCY', currency);

Efficy.updateDetail(editHandle, detail, detailKey, relationId, fieldNames, fieldValues)

Updates field values of a detail relation in the edit context.
When the detail relation doesn't exist, an exception is thrown.
If detailKey is 0, the current detail record is used. (relationId is ignored in this case.)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey double The key of detail.
relationId integer The key of the relation if multi-relation is available.
fieldNames olevariant The array of fields to update.
fieldValues olevariant The array of field values. The number of elements in both arrays must be identical.

Warning: Use UpdateDetail2 when no multiple relations are available on this detail relation. (The field "K_RELATION" doesn't exist in the database table.)

Usage
Efficy.updateDetail(contextHandle, ntProd, 0, -1, 'NAME', 'Name value');

Efficy.updateDetail2(editHandle, detail, detailKey, fieldNames, fieldValues)

Updates field values of a detail relation in the edit context.
If the detail relation does not exist, an exception is thrown.
If detailKey is 0, the current detail record is used.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey double The key of detail.
fieldNames olevariant The array of fields to update.
fieldValues olevariant The array of field values. The number of elements in both arrays must be identical.

Warning: Use UpdateDetail when multiple relations are available on this detail relation. (The field "K_RELATION" exists in the database table.)

Usage
var contextHandle = Efficy.openEditContext(ntDocu, 0); var ds = Efficy.getMasterDataSet(contextHandle, 0); try { for (var i = 0; i < attachments.length; i++) { var fileName = removeInvalidFileChars(attachments[i].filename); var fileKey = Efficy.insertAttachment(contextHandle, ftInserted, fileName); var fileStr = decodeMime64Utf8(attachments[i].data); Efficy.updateDetail2(contextHandle, ntFile, fileKey, 'STREAM', fileStr); Efficy.updateDetail2(contextHandle, ntFile, fileKey, 'FILESIZE', fileStr.length); Efficy.updateDetail2(contextHandle, ntFile, fileKey, 'PATH', fileName); Efficy.updateDetail2(contextHandle, ntFile, fileKey, 'COMMENT', fileName); } Efficy.commitChanges(contextHandle, false); } finally { Efficy.closeContext(contextHandle); }

Efficy.updateDetailField(editHandle, detail, detailKey, relationId, fieldName, fieldValue)

Updates the value of a field of any type but string in the relation in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey double The key of detail.
relationId integer The key of the relation if multi-relation is available.
fieldName string The name of the field.
fieldValue olevariant The new value.
Usage
Efficy.updateDetailField(docuContext, ntProd, 0, 0, 'COMMENT', prodDs.fieldByName('COMMENT').asString);

Efficy.updateField(editHandle, tableViewIndex, fieldName, fieldValue)

Updates the value of a field of any type but string of a master data set in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
tableViewIndex integer Specify 0 to update the main entity data.
fieldName string The name of the field.
fieldValue olevariant The new value.
Usage
Efficy.updateField(contextHandle, 0, 'PHONE1', '0123456789');

Efficy.updateFields(editHandle, tableViewIndex, fieldNames, fieldValues)

Updates the field values of a master data set in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
tableViewIndex integer Specify 0 to update the main entity data.
fieldNames olevariant The array of fields to update.
fieldValues olevariant The array of field values. The number of elements in both arrays must be identical.
Usage
Efficy.updateFields(editHandle, 0, 'NAME', 'A name');
Efficy.updateFields(editHandle, 0, varArrayOf(['FIELD1', 'FIELD2']), varArrayOf(['1', '2']));

Efficy.updateFields2(editHandle, tableViewIndex, fieldNames, fieldValues)

Updates the field values of a master data set in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
tableViewIndex integer Specify 0 to update the main entity data.
fieldNames array of string The array of fields to update.
fieldValues array of string The string array of field values. The number of elements in both arrays must be identical.
Usage
Efficy.updateFields2(contextHandle, 0, ['FIELD1', 'FIELD2'], ['1', '2']);

Efficy.userList()

Retrieves the 2-dimensional array of users.

Return
olevariant

List of indexes in the array of users:

USER_ITEM_ID = 0;
USER_ITEM_CODE = 1;
USER_ITEM_KIND = 2;
USER_ITEM_FULLNAME = 3;
USER_ITEM_EMAIL = 4;
USER_ITEM_CONTACT = 5;
USER_ITEM_MAILSERVER = 6;
USER_ITEM_MAILALIAS = 7;
USER_ITEM_NOTIFY = 8;
USER_ITEM_PHONE = 9;
USER_ITEM_ULIST = 10;
USER_ITEM_LANGUAGE = 11;
USER_ITEM_ISCONTACT = 12;
USER_ITEM_TIMEZONE = 13;
USER_ITEM_ROLEID = 14;
USER_ITEM_CAMCARD = 15;
USER_ITEM_SKILL = 16;
USER_ITEM_RECSIZE = 17;

Usage
var userList = Efficy.userList(); for (var i = 0; i < recipients.length; i++) { var email = recipients[i]; var ignoreUser = false; for (var j = varArrayLowBound(userList, 1); j <= varArrayHighBound(userList, 1); j++) { if (varArrayElement(userList, j, 4).toLowerCase() === email.toLowerCase() && !varArrayElement(userList, j, 12)) { Efficy.setUsers(contextHandle, [varArrayElement(userList, j, 0)], false, false); ignoreUser = true; break; } } if (!ignoreUser) filterRecipients.push(email); }

Efficy.usersInGroup(groupId)

Retrieves the array of members of group groupId.

Parameter Type Default value Description
groupId integer The key of the group.
Return
olevariant
Usage
function userInGroup(userId, groupId) { var users = Efficy.usersInGroup(groupId); if (!users) return false; for (var i = varArrayLowBound(users, 1); i <= varArrayHighBound(users, 1); i++) { var userId2 = varArrayElement(users, i); if (userId2 === userId) return true; } return false; }

Efficy.writeInteger(section, parameterName, value)

Writes an integer value into user options.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
value integer The value to be written.
Usage
Efficy.writeInteger('custom', 'customItem', 1);

Efficy.writeSessionBoolean(section, parameterName, value)

Writes a non-persistent boolean value stored into the user session.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
value boolean The value to be written.
Usage
Efficy.writeSessionBoolean('custom', 'customItem', true);

Efficy.writeSessionFloat(section, parameterName, value)

Writes a non-persistent float value stored into the user session.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
value double The value to be written.
Usage
Efficy.writeSessionFloat('custom', 'customItem', 0.5);

Efficy.writeSessionInteger(section, parameterName, value)

Writes a non-persistent integer value stored into the user session.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
value integer The value to be written.
Usage
Efficy.writeSessionInteger('custom', 'customItem', 5);

Efficy.writeSessionString(section, parameterName, value)

Writes a non-persistent string value stored into the user session.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
value string The value to be written.
Usage
Efficy.writeSessionString('custom', 'customItem', 'abc');

Efficy.writeString(section, parameterName, value)

Writes a string value into user options.

Parameter Type Default value Description
section string The name of the section.
parameterName string The name of the value.
value string The value to be written.
Usage
Efficy.writeString('custom', 'customItem', 'abc');

Efficy.zipFiles(editHandle, fileName, files)

Introduced in Efficy 11.2 Generates a Zip archive from a selected list of documents.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
fileName string The file name of the archive.
files string The files to include in the archive.
Return
double
Usage
Example creating a zip archive of several files located in different documents, and creation of shared link for external users
var docuHandle, kFile, ds, docuKey, shareToken, zipfilename, link, timestamp, structure = [ { "path": "Doc1.pdf", "key": "100002512_0" }, { "path": "Logo.jpg", "key": "100004037_0" }, { "path": "Doc2.pdf", "key": "100004041_0" } ]; docuHandle = Efficy.openEditContext(ntDocu, 0); try { timestamp = +(new Date()); ds = Efficy.getMasterDataSet(docuHandle, 0); ds.Edit; ds.FieldByName('NAME').AsString = 'Zip archive - ' + timestamp; zipfilename = "Docs" + timestamp + ".zip"; kFile = Efficy.ZipFiles(docuHandle, zipfilename, JSON.stringify(structure)); //create the zip Efficy.setUsers(docuHandle, 2, false); Efficy.commitChanges(docuHandle, false); docuKey = Efficy.getEditKey(docuHandle); shareToken = Efficy.CreateSharingToken(ntDocu, docuKey, 0, 10); //create share link for 10 days link = '<a href="' + shareToken + '">' + shareToken + '</a>'; } finally { Efficy.closeContext(docuHandle); }

Request reference

API interface class exposing properties and methods allowing to retrieve arguments and other web request parameters. For example:
var dbegin = Request.dateArgument('d_begin', now(), 'dd/MM/yyyy');
var greeting = Request.translate('Hello World');
var price = Request.floatArgument('prodprice', 0);
var ua = Request.getHeader('User-Agent');
var postJson = JSON.parse(Request.rawContent);
var url = Request.url;

Properties

Name Type Access Description
content string Read only Introduced in Efficy 11.2 The contents of the HTTP request. If the "Content-Type" header of the Request contains the mention ";charset=utf-8", then content will be treated as UTF8. This property is empty for GET requests and contains the full contents of the payload in POST requests.
contentLength integer Read only Introduced in Efficy 11.2 The length of the contents of the HTTP request.
contextHandle TContextHandle Read only The context handle of the current request.
cookie string Read only Introduced in Efficy 11.2 The value of the cookie header of the HTTP request.
customBaseUrl string Read/Write The custom base URL of the current session.
fileBaseUrl string Read/Write The file base URL of the current session.
forceRefresh boolean Read/Write If true, disables the use of cached data for the current request.
hideMessages boolean Read/Write If true, disables pop-up alerts in the response page of the current request.
host string Read only Introduced in Efficy 11.2 The value of the Host header of the HTTP request.
messages TEnhStringList Read only The alerts to be inserted into the page.
method string Read only Introduced in Efficy 11.2 The method or verb of the Host header of the HTTP request (GET, POST, ...).
pathInfo string Read only Introduced in Efficy 11.2 The value of the path information (if any) of the URL specified in the HTTP request. (For example: '/dialog')
query string Read only Introduced in Efficy 11.2 The value of the query information (if any) of the URL specified in the HTTP request. (For example: 'page=test&entity=Comp')
rawContent ansistring Read only Introduced in Efficy 11.2 The raw contents of the HTTP request. This property is empty for GET requests and contains the full contents of the payload in POST requests.
remoteAddr string Read only Introduced in Efficy 11.2 The remote IP address of the client associated with the HTTP request.
requestLength integer Read only Deprecated since Efficy 11.2 The length of the request. (Use Request.contentLength instead)
requestUrl string Read only Deprecated since Efficy 11.2 The URL of the request. (Use Request.url instead)
scriptName string Read only Introduced in Efficy 11.2 The value of the script name (if any) of the URL specified in the HTTP request. (For example: '/efficy.dll')
url string Read only Introduced in Efficy 11.2 The full URL of the request (Composed of Protocol, Host, ScriptName, PathInfo and Query components).
utf8Content string Read only Introduced in Efficy 11.2 Identical to the "content" property, except that the content will always be treated as UTF-8, even if the "Content-Type" header of the Request does not the mention ";charset=utf-8".

Methods

Request.argument(name)

Retrieves an argument of the current HTTP request.

Parameter Type Default value Description
name string The name of the argument.
Return
string
Usage
var entity = Request.argument('entity');

Request.booleanArgument(name)

Retrieves an argument of the current HTTP request and convert it to a boolean.

Parameter Type Default value Description
name string The name of the argument.
Return
boolean
Usage
var active = Request.booleanArgument('active');

Request.contentField(name)

Introduced in Efficy 11.2 Retrieves a value from the posted fields of the web request.

Parameter Type Default value Description
name string The name of the field to retrieve.
Return
string

Request.dateArgument(name, default, shortDateFormat)

Introduced in Efficy 11.1 Retrieves an argument of the current HTTP request and convert it to a DateTime. If the conversion fails, returns the default value.

Parameter Type Default value Description
name string The name of the argument.
default TDateTime The default value.
shortDateFormat [Opt] string '' The format in which the date part of the string is provided. Common values are 'dd/MM/yyyy' and 'MM/dd/yyyy'. If omitted, the short date format specified in the Efficy Admin Console settings is used. For more supported tokens, see the method FormatDateTime.
Return
TDateTime

Request.evaluateMacro(macroFile, macroName, context, entity, detail, values)

Introduced in Efficy 11.3 Returns the text content of a macro. The tags contained in the macro text ARE evaluated.

Parameter Type Default value Description
macroFile string The macro definition file to load. Multiple file names are accepted, separated by a ;
macroName string The name of the macro.
context string The security context for the generated result.
entity [Opt] string '' The entity of macro.
detail [Opt] string '' The detail of macro.
values [Opt] string '' The additional arguments for the macro evaluation, in the form $ARG$=VALUE separated by \r\n.
Return
string

To return the content of a macro without evaluating it, use Request.getMacro().
If the macro definition is found in the custom macro file, it gets taken from that source. If not, the standard macro definition is looked for in the standard macro file.
If a macro is used in a context with an entity and a detail, the following search order is used:
 MACRO.ENTITY.DETAIL
 MACRO..DETAIL
 MACRO.ENTITY
 MACRO
When a macro is found, the security descriptor is verified (@USER or @GROUP).
If a macro is not found or the user does not match the security descriptor, an empty result is returned.

Usage
var str = Request.evaluateMacro('MacroConsult', 'FeatureData', 'TEXT');
var str = Request.evaluateMacro('MacroConsult', 'FeatureData', 'Comp', 'Cont', 'JS', '$one$=een\r\n$two$=twee');

Request.evaluateText(text, context)

Introduced in Efficy 11.3 Evaluate a piece of text containing function tags.

Parameter Type Default value Description
text string The source text to evaluate.
context string The security context for the generated result.
Return
string
Usage
var str = Request.evaluateText('Licence: <%GetLicenceInfo()%>', 'JS');

Request.floatArgument(name, default)

Retrieves an argument of the current HTTP request and convert it to float. If the conversion fails, returns the default value.

Parameter Type Default value Description
name string The name of the argument.
default double The default value.
Return
double
Usage
var key = Request.floatArgument('key');

Request.getArgumentNames(names)

Retrieves the names of arguments from the URL.

Parameter Type Default value Description
names TEnhStringList The list to be filled.

Request.getHeader(name)

Introduced in Efficy 11.2 Returns the value of a header of the HTTP request.

Parameter Type Default value Description
name string The name of the header to return.
Return
string
Usage
var accept = Request.getHeader('Accept');

Request.getMacro(name, entity, detail, values)

Returns the text content of a macro. The tags contained in the macro text are NOT evaluated.

Parameter Type Default value Description
name string The name of the macro.
entity [Opt] string '' The entity of macro.
detail [Opt] string '' The detail of macro.
values [Opt] string '' The additional arguments for the macro evaluation, in the form $ARG$=VALUE separated by \r\n.
Return
string

If run in a /node and /rest, the macro file must be loaded first with Request.loadMacros().
To load the macro file and return the evaluated content of a macro, use Request.evaluateMacro().
If the macro definition is found in the custom macro file, it gets taken from that source. If not, the standard macro definition is looked for in the standard macro file.
If a macro is used in a context with an entity and a detail, the following search order is used:
 MACRO.ENTITY.DETAIL
 MACRO..DETAIL
 MACRO.ENTITY
 MACRO
When a macro is found, the security descriptor is verified (@USER or @GROUP).
If a macro is not found or the user does not match the security descriptor, an empty result is returned.

Usage
var str = Request.getMacro('FeatureData');
var str = Request.getMacro('FeatureData', 'Comp', 'Cont', '$one$=een\r\n$two$=twee');

Request.getSessionParameter(name, defaultValue)

Reads a value from user settings.

Parameter Type Default value Description
name string The name a the value.
defaultValue [Opt] string '' The default value.
Return
string

Request.integerArgument(name, default)

Retrieves an argument of the current HTTP request and convert it to integer. If the conversion fails, returns the default value.

Parameter Type Default value Description
name string The name of the argument.
default integer The default value.
Return
integer
Usage
var user = Request.integerArgument('user');

Request.keepContextAlive(handle)

Keeps the context for a next use during 30 seconds.

Parameter Type Default value Description
handle TContextHandle The handle of the context.
Usage
var contextHandle = Efficy.openEditContextRelation2(ntPubl, ntComp, publKey, compKey); try { Efficy.updateField(contextHandle, 0, 'STATUS', 1); Efficy.commitChanges(contextHandle, true); Request.keepContextAlive(contextHandle); } finally { Efficy.closeContext(contextHandle); }

Request.loadMacros(names)

Introduced in Efficy 11.3 Loads a macro file.

Parameter Type Default value Description
names string The macro definition file to load. Multiple file names are accepted, separated by a semicolon (;).
Usage
Request.loadMacros('MacroConsult');

Request.setSessionParameter(name, value)

Writes a value into user settings.

Parameter Type Default value Description
name string The name of the value.
value string The value.

Request.translate(msg, language)

Translates a text label in the current language of the user session.

Parameter Type Default value Description
msg string The label to be translated.
language [Opt] string '' The alternate language.
Return
string
Usage
var label = Request.translate('Subject', 'NL');
var label = Request.translate('Confidential');

Request.translateDate(dateString)

Translates a date text in the current language of the user session.

Parameter Type Default value Description
dateString string The date to be translated.
Return
string
Usage
var dateStr = Request.translateDate('31/12/2000'); // "Sunday 31 December 2000"

Request.translateDateWithFormat(value, format)

Introduced in Efficy 11.3 Translates a date in the current language of the user session, in a requested a datetime format.

Parameter Type Default value Description
value TDateTime The DateTime value.
format string The format to be used. See available format tokens list here.
Return
string
Usage
Request.translateDateWithFormat(Date.now(), 'd mmmm') // "31 December"

Efficy Remote reference

API interface class exposing properties and methods allowing to perform operations on the entities and interact with the CRM business logic from a DataSynchro Remote context. In this case, the instructions are saved to a special queue and are only sent to the web server once a call to the "Efficy.executeBatch();" method is made. At this point, all previously executed instructions are sent at once to the webserver inside a SOAP envelope.
The class prefix to use is still "Efficy.", but some of the methods and properties differ from the Efficy non-remote implementation. For example:
Efficy.activateCategory(editHandle, 'COMP$ADDRESS');
var DS = Efficy.getMasterDataset(editHandle, 0);

Properties

Name Type Access Description
active boolean Read/Write
browserPath string Read only
browserPrefix string Read only
clientVersion string Read only
compression string Read/Write
currentDatabaseAlias string Read only The alias (name) of the currently connected database.
currentDatabaseTimeZone integer Read only The current database time zone.
currentLicenseName string Read only The current license name.
currentUserCode string Read only The current user code.
currentUserContactId double Read only The contact ID of the current user.
currentUserEmail string Read only The current user e-mail.
currentUserFullName string Read only The current user full name.
currentUserGroups string Read only The array of groups to which the current user belongs.
currentUserId integer Read only The current user ID.
currentUserTimeZone integer Read only The current user time zone.
customBase string Read only Introduced in Efficy 11.1
dealerBase string Read only Introduced in Efficy 11.1
disableChangeLog boolean Write only Introduced in Efficy 11.2 If true, disables writing the history of changes to the database (SYS_CHANGED table); this can improve performance when needed, e.g. for massive imports
disableNotifications boolean Write only Introduced in Efficy 11.2 If true, no system notification gets generated by subsequent operations. Use this method with care.
disableWebHooks boolean Write only Introduced in Efficy 11.2 If true, disables sending notifications configured into SYS_WEBHOOKS table. This can improve performance when needed, e.g. for massive imports.
disableWorkflow boolean Write only Introduced in Efficy 11.2 If true, no workflow scripting events get generated by subsequent operations.
fileBase string Read only Introduced in Efficy 11.1
ignoreMessages boolean Read/Write
keepLocalSettings boolean Read/Write
language string Read only The selected language.
loadCookiesFromRegistry boolean Read/Write Introduced in Efficy 11.2
logThreadIndex integer Read/Write Introduced in Efficy 11.2 When running data synchro with multiple threads, contains the index of the current thread.
manualCookies TEnhStringList Read only Introduced in Efficy 11.2
requestLogFileName string Read/Write
responseLogFileName string Read/Write
serverVersion string Read only
sessionHandle string Read only
sessionToken string Read only
soapLogEnabled boolean Read/Write Introduced in Efficy 11.2
soapLogFolder string Read/Write Introduced in Efficy 11.2
userList TDataset Read only The array of users.
webServerUrl string Read/Write

Methods

(Remote) Efficy.accountHasPrivilege(privilege)

Parameter Type Default value Description
privilege integer
Return
TSoapResponseHandle

(Remote) Efficy.activateCategory(editHandle, category)

Activates a category in the edit context. If the user does not have the appropriate rights on the category, an exception is thrown.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
category string The name of the category.
Return
TSoapResponseHandle

(Remote) Efficy.addLink(entity, detail, key, detailKey, ignoreExisting)

Adds a database relation without using an edit context. Can be used when multiple relations are available.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
key double The entity key.
detailKey double The detail Key.
ignoreExisting boolean If true, doesn't throw an exception if the relation already exists.
Return
TSoapResponseHandle

(Remote) Efficy.addLink2(entity, detail, key, detailKey, ignoreExisting)

Adds a database relation without using an edit context.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
key double The entity key.
detailKey double The detail Key.
ignoreExisting boolean If true, doesn't throw an exception if the relation already exists.
Return
TSoapResponseHandle

(Remote) Efficy.addOrModifyFavorite(entity, key, text)

Adds a new favorite or update the text of an existing one.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key double The entity key.
text string The text value.
Return
TSoapResponseHandle

(Remote) Efficy.autoMergeDuplicate(entity, key1, key2, alwaysKeepFirst)

Merges duplicates automatically.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key1 double The key of the first record.
key2 double The key of the second record.
alwaysKeepFirst [Opt] boolean False If true, allows to choose which record is kept by ordering the keys.
Return
TSoapResponseHandle

(Remote) Efficy.clearDetail(editHandle, detail)

Clears all relations for the specified detail.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
Return
TSoapResponseHandle

Warning: Do not use this function to clear the "User" detail. The only way of dealing with users is by using the functions Efficy.setUsers() and Efficy.setUserSecurity().

(Remote) Efficy.clearSessionToken()

Clears the token of the current session.

(Remote) Efficy.closeContext(contextHandle, keepOnServer)

Closes a context. A context remains memory-resident on the web server until it's closed.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
keepOnServer [Opt] boolean False If true, keeps the context opened on the web server.

(Remote) Efficy.closingCommit(editHandle)

Introduced in Efficy 11 Commits the changes, releases the record and closes the context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.

(Remote) Efficy.commitChanges(editHandle, refreshAfterCommit)

Commits the changes of the edit context to the database.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
refreshAfterCommit [Opt] boolean False If true, refreshes all the data in the edit context. Use this option if you continue to use the edit context after the commit.

Warning: None of the previous functions has any permanent effect until Efficy.commitChanges() is called.

(Remote) Efficy.connectToExistingEdit(editHandle)

Parameter Type Default value Description
editHandle integer
Return
TContextHandle

(Remote) Efficy.consult(entity, key)

Consults a record in the context handle and returns its main data set.

Parameter Type Default value Description
entity TEntityHandle The entity of the record.
key string The key of the record.
Return
TSoapResponseHandle

(Remote) Efficy.consult2(entity, key, detail, detailResponseHandle)

Parameter Type Default value Description
entity TEntityHandle
key string
detail TEntityHandle
detailResponseHandle TSoapResponseHandle
Return
TSoapResponseHandle

(Remote) Efficy.consultAgenda(beginDate, endDate, userIDs, activeUser, includeRelations)

Retrieves the agenda (diary) for the specified period and users.

Parameter Type Default value Description
beginDate double The begin date of requested period.
endDate double The end date of requested period.
userIDs string The array of users. Can be filtered according to database security.
activeUser boolean If true, shows data to which the users are actively linked.
includeRelations boolean If true, retrieves the main company, contact and project in the query result.
Return
TSoapResponseHandle

(Remote) Efficy.consultDataSet(contextHandle)

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
Return
TSoapResponseHandle

(Remote) Efficy.consultDetail(contextHandle, detail)

Retrieves the list of linked detail items in a data set.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
detail TEntityHandle The detail handle.
Return
TSoapResponseHandle

(Remote) Efficy.consultEntityList(entity, userIDs, opened, activeUser)

Parameter Type Default value Description
entity TEntityHandle The entity handle.
userIDs string The list of users. Can be filtered according to database security, returns unselected users.
opened boolean If true, only returns opened, active records.
activeUser boolean If true, shows data to which the users are actively linked.
Return
TSoapResponseHandle

(Remote) Efficy.consultFavorites()

Retrieves the list of favorites.

Return
TSoapResponseHandle

(Remote) Efficy.consultMainCompanyEx(contactKey)

Parameter Type Default value Description
contactKey double
Return
TSoapResponseHandle

(Remote) Efficy.consultManyEx(entity, findFields, orderByFields, findValues)

Parameter Type Default value Description
entity TEntityHandle
findFields string The fields to match.
orderByFields string The sort order.
findValues variant The list of values to match.
Return
TSoapResponseHandle

(Remote) Efficy.consultQuery(contextHandle, master, detail, queryParams, forceRefresh, getAllRecords)

Runs a database query and returns the results in a data set.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
master integer Identifies the query in the system table "SYS_QUERIES" or "QUERIES".
detail double Identifies the query in the system table "SYS_QUERIES" or "QUERIES" (if master = -1).
queryParams string The query parameters in a variant array.
forceRefresh boolean If true, never uses cached results.
getAllRecords boolean If true, retrieves all records in a single call instead of page per page.
Return
TSoapResponseHandle

(Remote) Efficy.consultRecent()

Retrieves the recent list.

Return
TSoapResponseHandle

(Remote) Efficy.consultRecentEx(entity, extraFields)

Parameter Type Default value Description
entity TEntityHandle
extraFields string
Return
TSoapResponseHandle

(Remote) Efficy.consultTaskList(date, userIDs, activeUser, showPast, showUpcoming)

Retrieves the task list for the specified date and users.

Parameter Type Default value Description
date double The requested date for task list.
userIDs string The array of users. Can be filtered according to database security.
activeUser boolean If true, shows data to which the users are actively linked.
showPast boolean If true, includes the past, unfinished tasks.
showUpcoming boolean If true, includes the future tasks.
Return
TSoapResponseHandle

(Remote) Efficy.contactIDsFromEMailAddresses(recipients)

Parameter Type Default value Description
recipients string
Return
TSoapResponseHandle

(Remote) Efficy.convertUserCodesToNames(userCodes)

Parameter Type Default value Description
userCodes string
Return
string

(Remote) Efficy.copyDetails(editHandle, sourceEntity, key, details, mainRelationOnly, changedDetailsOnly)

Copies data from another open edit context, not necessarily on the same entity.

Parameter Type Default value Description
editHandle TContextHandle The handle of the destination edit context.
sourceEntity TEntityHandle The entity handle of the source record.
key double The key of the source record.
details string The array of details that will be copied.
mainRelationOnly boolean If true, copies only the main relation record.
changedDetailsOnly boolean If true, copies only the relations that have pending modifications in the source edit context.
Return
TSoapResponseHandle

(Remote) Efficy.copyFromExisting(editHandle, key, minIndex, maxIndex)

Copies data from an existing record in the database. The same entity as the current edit context is assumed.
The table views within the index range MinIndex to MaxIndex are copied. By default, all table views are copied.
To copy a single detail, obtain the table view index using IndexFromDetail and use this value as MinIndex and MaxIndex.

Parameter Type Default value Description
editHandle TContextHandle The handle of the destination edit context.
key double The key of the source record.
minIndex [Opt] integer 0 The index of first table view to be copied.
maxIndex [Opt] integer 999 The index of last table view to be copied.
Return
TSoapResponseHandle

(Remote) Efficy.createDataSet()

Creates a DataSet object to be used in future GetObject calls.
Make sure to destroy the object after usage by calling the Free method, otherwise a memory leak will occur.

Return
TMemoryDataSet
Usage
var dbRequest = Efficy.ExecuteSQLQuery(sqlCommand, sqlParameters); var dsCont = Efficy.CreateDataSet; try Efficy.getObject(dbRequest, dsCont); if (dsCont.RowCount > 1) { … } finally { dsCont.Free; }

(Remote) Efficy.dateToSqlParam(value)

Parameter Type Default value Description
value TDateTime
Return
string

(Remote) Efficy.deactivateCategory(editHandle, category)

Introduced in Efficy 11.2 Deactivates a category in the edit context. If the user does not have the appropriate rights on the category, an exception is thrown.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
category string The name of the category.
Return
TSoapResponseHandle

(Remote) Efficy.deleteDetail(editHandle, detail, detailKey)

Deletes the detail relation identified by detail, detailKey and optionally relationId (if multiple relations are available).

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey double The detail key.
Return
TSoapResponseHandle

(Remote) Efficy.deleteLink(entity, detail, key, detailKey)

Removes database relations without using an edit context.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
key double The entity key.
detailKey double The detail key.
Return
TSoapResponseHandle

(Remote) Efficy.detailExists(editHandle, detail)

Tests whether the detail entity is available in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
Return
TSoapResponseHandle

(Remote) Efficy.downloadRemoteFile(fileName)

Introduced in Efficy 11.2 Hidden

Parameter Type Default value Description
fileName string
Return
string

(Remote) Efficy.editSecurityDataSet(editHandle)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
TSoapResponseHandle

(Remote) Efficy.entityFromContext(contextHandle)

Returns the entity used in the context handle.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
Return
TEntityHandle

(Remote) Efficy.entityFromTableId(tableId)

Retrieves the entity handle from a table ID.

Parameter Type Default value Description
tableId integer The ID of the table.
Return
TEntityHandle

(Remote) Efficy.eventEditInitialized(editHandle)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
TSoapResponseHandle

(Remote) Efficy.executeBatch()

(Remote) Efficy.executeDatabaseQuery(idQuery, queryParameters, loadBlobs)

Parameter Type Default value Description
idQuery double
queryParameters TStrings
loadBlobs [Opt] boolean False
Return
TSoapResponseHandle

(Remote) Efficy.executeEditedQuery(editHandle, loadBlobs)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
loadBlobs [Opt] boolean False
Return
TSoapResponseHandle

(Remote) Efficy.executePendingBatch()

(Remote) Efficy.executeSqlQuery(sql, queryParams, recordCount)

Parameter Type Default value Description
sql string
queryParams string
recordCount [Opt] integer 0
Return
TSoapResponseHandle

(Remote) Efficy.executeSqlQueryEx(accessCode, sql, queryParams, recordCount)

Parameter Type Default value Description
accessCode string
sql string
queryParams string
recordCount integer
Return
TSoapResponseHandle

(Remote) Efficy.flushAndIgnoreErrors()

(Remote) Efficy.getAddinVersion()

Return
TSoapResponseHandle

(Remote) Efficy.getAttachment(editHandle, fileId)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
fileId string
Return
TSoapResponseHandle

(Remote) Efficy.getBinaryData(handle)

Parameter Type Default value Description
handle TSoapResponseHandle
Return
ansistring

(Remote) Efficy.getBooleanData(handle)

Parameter Type Default value Description
handle TSoapResponseHandle
Return
boolean

(Remote) Efficy.getCategories(contextHandle)

Retrieves activated categories.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
Return
TSoapResponseHandle

(Remote) Efficy.getCategoryCollection(entity, detail)

Parameter Type Default value Description
entity TEntityHandle
detail TEntityHandle
Return
TSoapResponseHandle

(Remote) Efficy.getCategoryDataSet(contextHandle, category)

Retrieves the data set for category CategoryName. Can be null when the category is not available to the current user.
Check data set.IsEmpty to make sure the category is selected for the current record.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
category string The name of the category.
Return
TSoapResponseHandle

(Remote) Efficy.getContextParameter(contextHandle, parameter)

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
parameter string
Return
string

(Remote) Efficy.getData(handle)

Parameter Type Default value Description
handle TSoapResponseHandle
Return
string

(Remote) Efficy.getDataset(handle)

Introduced in Efficy 11.1 Create and retrieves a DataSet with data from a previously obtained response handle.
Make sure to destroy the object after usage by calling the Free method, otherwise a memory leak will occur.

Parameter Type Default value Description
handle TSoapResponseHandle The Response handle obtained with a previous command.
Return
TDataset

(Remote) Efficy.getDatasetValue(handle, defaultValue)

Introduced in Efficy 11.1 Retrieve a the value from the first field of the first record of a DataSet with data from a previously obtained response handle.

Parameter Type Default value Description
handle TSoapResponseHandle The Response handle obtained with a previous command.
defaultValue variant The default value to be used if the response Dataset is empty.
Return
variant

(Remote) Efficy.getDefaultRights(entity)

Parameter Type Default value Description
entity TEntityHandle
Return
TSoapResponseHandle

(Remote) Efficy.getDetailDataSet(editHandle, detail)

Retrieves a relation data set for the specified detail in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
Return
TSoapResponseHandle

(Remote) Efficy.getEditKey(editHandle)

Retrieves the main item key of the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
variant

(Remote) Efficy.getEntityHandle(entityName)

Retrieves the entity handle from its string identifier.

Parameter Type Default value Description
entityName string The string identifier of the entity.
Return
TEntityHandle

(Remote) Efficy.getEntityName(entity)

Retrieves the string identifier of an entity from an entity handle.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
string

(Remote) Efficy.getEntityTables()

Return
TSoapResponseHandle

(Remote) Efficy.getFieldMetaData(entity, detail)

Parameter Type Default value Description
entity TEntityHandle
detail TEntityHandle
Return
TSoapResponseHandle

(Remote) Efficy.getInviteData(editHandle)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
TSoapResponseHandle

(Remote) Efficy.getLookupData(entity, detail, fieldName)

Parameter Type Default value Description
entity TEntityHandle
detail TEntityHandle
fieldName string
Return
TSoapResponseHandle

(Remote) Efficy.getLookupDataFromId(tableId, fieldName)

Parameter Type Default value Description
tableId integer
fieldName string
Return
TSoapResponseHandle

(Remote) Efficy.getLookupKeyFromValue(tableId, fieldName, value)

Returns the look-up key value for a look-up label.

Parameter Type Default value Description
tableId integer The ID of the table.
fieldName string The field for which the look-up conversion is requested.
value string The text value of look-up field.
Return
TSoapResponseHandle

(Remote) Efficy.getLookupKeyFromValue2(tableName, fieldName, value, searchInTranslations)

Introduced in Efficy 11 Retrieves the key in a lookup table from the value of one field.

Parameter Type Default value Description
tableName string The name of the lookup table.
fieldName string The field that contains the value. If searchInTranslations is true then the value is also searched in translated fields.
value string The value to be searched.
searchInTranslations [Opt] boolean False If true and if the field is the main value field, then the value is also searched into translated fields.
Return
TSoapResponseHandle

When searching in translated fields, the field corresponding to the current language is checked first, then default (English) and after the trailing fields.

(Remote) Efficy.getLookupList(editHandle, fieldName)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
fieldName string
Return
TSoapResponseHandle

(Remote) Efficy.getLookupValueFromKey(tableId, fieldName, key)

Returns the look-up key text for a look-up key.

Parameter Type Default value Description
tableId integer The ID of the table.
fieldName string The field for which the look-up conversion is requested.
key integer The key value of look-up field.
Return
TSoapResponseHandle

(Remote) Efficy.getLookupValueFromKey2(tableName, fieldName, key)

Retrieves the value in a lookup table from its key. If the main value field is specified then the translated value for session language is returned. If empty then the default language (English) is returned.

Parameter Type Default value Description
tableName string The name of the lookup table.
fieldName string The field containing the requested value.
key integer The key of the record.
Return
TSoapResponseHandle

(Remote) Efficy.getMasterDataSet(editHandle, tableViewIndex)

Retrieves a master data set from the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
tableViewIndex [Opt] integer 0 Specify 0 to retrieve the main entity data.
Return
TSoapResponseHandle

(Remote) Efficy.getObject(handle, component)

Retrieve an object from a previously obtained response handle.

Parameter Type Default value Description
handle TSoapResponseHandle The Response handle obtained with a previous command.
component TPersistent The object to which the response data will be written.
Usage
var dbRequest = Efficy.ExecuteSQLQuery(sqlCommand, sqlParameters); var dsCont = Efficy.CreateDataSet; try Efficy.getObject(dbRequest, dsCont); if (dsCont.RowCount > 1) { … } finally { dsCont.Free; }

(Remote) Efficy.getOwner(editHandle)

Retrieves the key of the owner of the record.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
TSoapResponseHandle

(Remote) Efficy.getQueryDataSet(queryHandle)

Retrieves the cached data set from a query handle.

Parameter Type Default value Description
queryHandle integer The handle of the query.
Return
TSoapResponseHandle

(Remote) Efficy.getReferenceList(editHandle)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
TSoapResponseHandle

(Remote) Efficy.getReferenceListForEntity(entity)

Parameter Type Default value Description
entity TEntityHandle
Return
TSoapResponseHandle

(Remote) Efficy.getRegisteredMails()

Return
TSoapResponseHandle

(Remote) Efficy.getRelationTableId(idTbl1, idTbl2)

Parameter Type Default value Description
idTbl1 integer
idTbl2 integer
Return
TSoapResponseHandle

(Remote) Efficy.getRequiredFields(entity)

Parameter Type Default value Description
entity TEntityHandle
Return
string

(Remote) Efficy.getServerFileSize(serverPathWithoutRootDir)

Parameter Type Default value Description
serverPathWithoutRootDir string
Return
TSoapResponseHandle

(Remote) Efficy.getSessionToken()

(Remote) Efficy.getSetting(module, aName)

Introduced in Efficy 11.2 Retrieves the current value of a given Efficy setting.

Parameter Type Default value Description
module string The name of the module (JSON object) that owns the setting.
aName string The name of the setting.
Return
TSoapResponseHandle

(Remote) Efficy.getSysStorageValue(aName)

Retrieves a value from the database table "SYS_STORAGE".

Parameter Type Default value Description
aName string The name of the value.
Return
TSoapResponseHandle

(Remote) Efficy.getTemplateFields()

Return
TSoapResponseHandle

(Remote) Efficy.getTranslatedTableName(entity)

Parameter Type Default value Description
entity TEntityHandle
Return
TSoapResponseHandle

(Remote) Efficy.getUserId(userName)

Retrieves the ID (key) of the user UserCode.

Parameter Type Default value Description
userName string The username of the user.
Return
integer

(Remote) Efficy.getUserName(userId)

Retrieves the full name of the user UserID.

Parameter Type Default value Description
userId integer The key of the user.
Return
string

(Remote) Efficy.hasRightOnTable(entity, accesOperation)

Tests whether the current user has the right to perform a certain operation on an entity.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
accesOperation TSecurityCode The operation can be 0 (read), 1 (write), 2 (delete), 3 (add) or 4 (execute).
Return
TSoapResponseHandle

(Remote) Efficy.impersonateUser(impersonateAccount, forceUserRole)

Impersonate a different user, for example this can be useful to import data using a specific owner.
You require the "impersonate" privilege to execute this instruction.

Parameter Type Default value Description
impersonateAccount string The account code to impersonate.
forceUserRole [Opt] integer 0 Introduced in Efficy 11.2 The role ID (integer value) that will be used instead of the default role of the user.
Return
TSoapResponseHandle

(Remote) Efficy.initializeSecurityList(editHandle)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
TSoapResponseHandle

(Remote) Efficy.insertAttachment(editHandle, attachedFileType, path)

Inserts an attached file and returns the key (K_FILE).

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
attachedFileType TAttachedFileType The attachment type (1 = embedded, 2 = linked, 4 = remote, 5 = large).
path string The path of the file that will be saved in the FILES.PATH field.
Return
TSoapResponseHandle

Warning: This method does not actually upload the contents of the file in the database!
Use for instance Efficy.updateDetail2() to do so.

(Remote) Efficy.insertDetail(editHandle, detail, detailKey, linkMainCompany, retrieveName)

Inserts a detail relation in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey string The detail key.
linkMainCompany boolean
retrieveName [Opt] boolean False
Return
TSoapResponseHandle

Warning: Use InsertDetail when multiple relations are available on this detail relation. (The field "K_RELATION" exists in the database table.)
Use the Efficy.setUsers() function to link users.

(Remote) Efficy.insertDetail2(editHandle, detail, detailKey, linkMainCompany)

Inserts a detail relation in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey double The detail key.
linkMainCompany boolean If true, automatically link the contact's main company when linking a contact.
Return
TSoapResponseHandle

Warning: Use InsertDetail when multiple relations are available on this detail relation. (The field "K_RELATION" exists in the database table.)
Use the Efficy.setUsers() function to link users.

(Remote) Efficy.insertDetailEx(editHandle, detail, detailKey, k_Relation, linkMainCompany)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle
detailKey double
k_Relation integer
linkMainCompany boolean
Return
TSoapResponseHandle

(Remote) Efficy.isSessionOpened()

Return
boolean

(Remote) Efficy.keyFieldName(entity)

Retrieves the key field of an entity.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
string

(Remote) Efficy.log(value)

While executing a scheduled script or a data synchronization script, the log function lets you add a string in the log file of the Data Sync tool or the Efficy service Task Scheduler.

Parameter Type Default value Description
value string The text to be logged.

(Remote) Efficy.logMessage(value)

Parameter Type Default value Description
value string

(Remote) Efficy.makeConfidential(editHandle)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
TSoapResponseHandle

(Remote) Efficy.openConsultContext(entity, key)

Opens a consult context for the Entity.
A context remains memory-resident (on the web server) until it is closed. To avoid memory consumption, always match an OpenConsultContext with a Efficy.closeContext() call.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key variant The entity key.
Return
TContextHandle

(Remote) Efficy.openEditContext(entity, key)

Opens an edit context for the record identified by entity and key.
A context remains memory-resident (on the web server) until it's destroyed again. Always match an OpenEditContext with a Efficy.closeContext() call to avoid memory consumption.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
key variant The key of the record. Use key = 0 to create a new record.
Return
TContextHandle

(Remote) Efficy.openEditContextForced(entity, forceKey)

Parameter Type Default value Description
entity TEntityHandle
forceKey variant
Return
TContextHandle

(Remote) Efficy.openEditContextRelation(entity, detail, key, detailKey, k_Relation)

Opens an edit context for a relation. If the relation does not yet exist, it is created.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
key variant The key of the entity.
detailKey variant The key of the detail.
k_Relation [Opt] integer MULTIRELATION_NONE The key of the relation if multi-relation is available.
Return
TContextHandle

Warning: Use OpenEditContextRelation2 when no multiple relations are available on this detail relation. (The field "K_RELATION" doesn't exist in the database table.)

(Remote) Efficy.openEditContextRelation2(entity, detail, key, detailKey)

Opens an edit context for a relation. If the relation does not yet exist, it will be created.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
key variant The key of the entity.
detailKey variant The key of the detail.
Return
TContextHandle

Warning: Use OpenEditContextRelation when multiple relations are available on this detail relation. (The field "K_RELATION" exists in the database table.)

(Remote) Efficy.openSearchContext(entity)

Opens a consult (search) context for the entity.
A context remains memory-resident (on the web server) until it's destroyed again. To avoid memory leaks, always match an OpenSearchContext with a Efficy.closeContext() call.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
TContextHandle

(Remote) Efficy.openTemporaryContext()

Opens a temporary context without Entity. Typically used to run a Efficy.consultQuery() request.
You don't need to close the temporary context, Efficy handles this automatically.

Return
TContextHandle

(Remote) Efficy.planAction(editHandle)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
TSoapResponseHandle

(Remote) Efficy.postSecurity(editHandle, securityList)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
securityList [Opt] string '' Introduced in Efficy 11.2
Return
TSoapResponseHandle

(Remote) Efficy.prepareExchangeSync(accessCode)

Parameter Type Default value Description
accessCode string
Return
TSoapResponseHandle

(Remote) Efficy.readAccountOption(fieldName)

Read user options.

Parameter Type Default value Description
fieldName string The field name.
Return
TSoapResponseHandle

(Remote) Efficy.readBoolean(section, ident, defaultValue)

Reads a boolean value from user options.

Parameter Type Default value Description
section string The name of the section.
ident string The name of the value.
defaultValue boolean The default value if the option is not found.
Return
boolean

(Remote) Efficy.readDateTime(section, ident, defaultValue)

Reads a DateTime value from user options.

Parameter Type Default value Description
section string The name of the section.
ident string The name of the value.
defaultValue TDateTime The default value if the option is not found.
Return
TDateTime

(Remote) Efficy.readInteger(section, ident, defaultValue)

Reads an integer value from user options.

Parameter Type Default value Description
section string The name of the section.
ident string The name of the value.
defaultValue integer The default value if the option is not found.
Return
integer

(Remote) Efficy.readQueryDefinitionFromString(editHandle)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
TSoapResponseHandle

(Remote) Efficy.readString(section, ident, defaultValue)

Reads a string value from user options.

Parameter Type Default value Description
section string The name of the section.
ident string The name of the value.
defaultValue string The default value if the option is not found.
Return
string

(Remote) Efficy.refreshAccountData()

(Remote) Efficy.refreshSessionHandle()

(Remote) Efficy.registerMailToUpload(eMail, password)

Parameter Type Default value Description
eMail string
password string
Return
TSoapResponseHandle

(Remote) Efficy.reloadDbSettings()

(Remote) Efficy.reloadManualCookies()

Introduced in Efficy 11.2

(Remote) Efficy.retrieveAllSyncRelations(applicId)

Parameter Type Default value Description
applicId integer
Return
TSoapResponseHandle

(Remote) Efficy.retrieveEntityFields(entity, forStateEditor)

Parameter Type Default value Description
entity string
forStateEditor [Opt] boolean False
Return
TSoapResponseHandle

(Remote) Efficy.saveParameters()

Return
TSoapResponseHandle

(Remote) Efficy.search(entity, searchField, value, own, contains, opened)

Performs a search on the database and returns the data set with search results.

Parameter Type Default value Description
entity TEntityHandle
searchField string The field to be searched.
value string The value to search.
own boolean If true, searches own records only.
contains boolean If true, allows matches on part of field.
opened boolean If true, searches for open, active records only.
Return
TSoapResponseHandle

(Remote) Efficy.searchContactsByPhone(phoneNumber)

Parameter Type Default value Description
phoneNumber string
Return
TSoapResponseHandle

(Remote) Efficy.searchDataSet(contextHandle, searchMethod, value, own, contains, opened)

Performs a search on the database and returns the data set with search results.

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
searchMethod string The search method to use.
value string The value to search.
own boolean If true, searches own records only.
contains boolean If true, allows matches on part of field.
opened boolean If true, searches for open, active records only.
Return
TSoapResponseHandle

(Remote) Efficy.searchDetail(contextHandle, key, detail)

Parameter Type Default value Description
contextHandle TContextHandle The handle of the context (consult or edit).
key double
detail TEntityHandle
Return
TSoapResponseHandle

(Remote) Efficy.searchLdap(host, userName, password, baseName, filter, scope, encrypt)

Parameter Type Default value Description
host string
userName string
password string
baseName string
filter string
scope integer
encrypt boolean
Return
TSoapResponseHandle

(Remote) Efficy.sendExternalMail(sendFrom, sendTo, sendCc, subject, body, entity, idLinked, sendCode)

Sends an e-mail to external recipients (non-Efficy users).

Parameter Type Default value Description
sendFrom string The sender's e-mail address.
sendTo string A semicolon-separated list of "To" recipients (e-mail addresses).
sendCc string A semicolon-separated list of "Cc" recipients (e-mail addresses).
subject string The subject of the e-mail message.
body string The body of the e-mail message.
entity [Opt] TEntityHandle ntNone The entity handle to insert a direct link to a record in the e-mail body.
idLinked [Opt] double 0 The entity key to insert a direct link to a record in the e-mail body.
sendCode [Opt] string '' Can be not specified, empty or a combination of the following values:
'U': Efficy won't add a URL to the mail body.
'S': Efficy won't save the e-mail message in the database.

Usage: The SendCode parameter is handy for the campaigns, to send external mails that are linked to a contact record without adding a URL to the mail body. (The URL is meaningless for the recipient of the e-mail message.)

Example: Send an e-mail message without URL that gets saved in the database linked to the contact:
Efficy.sendExternalMail(SendFrom, SendTo, SendCc, Subject, Body, ntCont, K_Contact, 'U');

(Remote) Efficy.sendMailToUsers(sendTo, sendCc, subject, body, entity, idLinked, sendCode)

Sends an e-mail message to Efficy users.

Parameter Type Default value Description
sendTo string A semicolon-separated list of "To" recipients (user code or full name).
sendCc string A semicolon-separated list of "Cc" recipients (user code or full name).
subject string The subject of the e-mail message.
body string The body of the e-mail message.
entity [Opt] TEntityHandle ntNone The entity handle to insert a direct link to a record in the e-mail body.
idLinked [Opt] double 0 The entity key to insert a direct link to a record in the e-mail body.
sendCode [Opt] string '' Can be not specified, empty or a combination of the following values:
'U': Efficy won't add a URL to the mail body.
'S': Efficy won't save the e-mail message in the database.

Usage: The SendCode parameter is handy for the SpyCase script to send internal mails including a URL to the case without saving the mail to the database.

(Remote) Efficy.sendNotification(subject, body, users, customParams, entity, key)

Introduced in Efficy 11 Adds an information to the notification feed of one or several users. Groups are allowed.

Parameter Type Default value Description
subject string The text of the collapsed notification.
body string The content shown when expanding the notification.
users olevariant The list of users to be notified.
customParams [Opt] string '' The extra parameters provided to the notification JSON object
entity [Opt] TEntityHandle ntNone Introduced in Efficy 11.1 Entity to which the notification is linked
key [Opt] double 0 Introduced in Efficy 11.1 Key of the entity to which the notification is linked

(Remote) Efficy.setCategories(editHandle, categoryList)

Activates some categories

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
categoryList string A string list of category names.
Return
TSoapResponseHandle

(Remote) Efficy.setChangeLogUserName(logUserName)

Introduced in Efficy 11.2 Sets the user name to be used in SYS_CHANGED when creating the record history.

Parameter Type Default value Description
logUserName string The user name to be used (currently limited to 32 characters).

Typical use case is an import script (run with Administrator user) that imports records, assign them to users and create a record history related to the user.

(Remote) Efficy.setOwner(editHandle, ownerId)

Changes the user of an element in a specified context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
ownerId integer The key of the new owner user.
Return
TSoapResponseHandle

(Remote) Efficy.setReference(editHandle, referenceId)

Requests that a unique reference number be generated when committing the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
referenceId double The key of the reference.
Return
TSoapResponseHandle

(Remote) Efficy.setSecurityUsers(editHandle, users)

Adds each user of the Users array in the record's security. These users have the default security.
Users not in the Users array are deleted from the record's security.
Call postSecurity after Efficy.setSecurityUsers() to make the changes effective.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
users string The array of users ID.
Return
TSoapResponseHandle

(Remote) Efficy.setSoapLogFileNames(requestFile, responseFile)

Introduced in Efficy 11.1

Parameter Type Default value Description
requestFile string
responseFile string

(Remote) Efficy.setUsers(editHandle, users, clearUsers)

Sets the user relations.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
users string The array of user IDs (keys).
clearUsers boolean If true, clears the current user selection.
Return
TSoapResponseHandle

(Remote) Efficy.setUserSecurity(editHandle, account, securityValue)

Sets the security for a user or group.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
account integer The user or group for which security is added.
securityValue integer A sum of one or more of the following values: 1 (search), 2 (read), 4 (write), 8 (delete) and 256 (secure)
Useful combinations are 7 (read/write), 15 (read/write/delete) and 271 (full control = read/write/delete/secure).
Return
TSoapResponseHandle

List of security codes

ACCESSCODE_SEARCH = 1
ACCESSCODE_READ = 2
ACCESSCODE_WRITE = 4
ACCESSCODE_DELETE = 8
ACCESSCODE_SHOWCONTENT = 16
ACCESSCODE_ADDCONTENT = 32
ACCESSCODE_MODIFYCONTENT = 64
ACCESSCODE_DELETECONTENT = 128
ACCESSCODE_SECURE = 256
ACCESSCODE_SECURECONTENT = 512
ACCESSCODE_NOCONTENT = 2048

A few common combinations

ACCESSCODE_READ_WRITE = ACCESSCODE_SEARCH + ACCESSCODE_READ + ACCESSCODE_WRITE;
ACCESSCODE_READ_WRITE_DELETE = ACCESSCODE_READ_WRITE + ACCESSCODE_DELETE;
ACCESSCODE_READ_WRITE_SECURE = ACCESSCODE_READ_WRITE + ACCESSCODE_SECURE;
ACCESSCODE_FULLCONTROL = ACCESSCODE_READ_WRITE_DELETE + ACCESSCODE_SECURE;
ACCESSCODE_CONTENTFULLCONTROL = ACCESSCODE_SEARCH + ACCESSCODE_SHOWCONTENT + ACCESSCODE_MODIFYCONTENT + ACCESSCODE_ADDCONTENT + ACCESSCODE_DELETECONTENT + ACCESSCODE_SECURECONTENT;

Field security contains a combination of all these values, "normal" record security and security on the contents taken together.
Example to check if a user has the permission to add content into a main entity
if ((UserDataSet.fieldByName('SECURITY').asInteger & 32) == 32)

(Remote) Efficy.tableIdFromEntity(entity)

Retrieves a table ID from an entity.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
integer

(Remote) Efficy.tableIdFromEntityName(entityName)

Retrieves a table ID from an entity string identifier.

Parameter Type Default value Description
entityName string The string identifier.
Return
integer

(Remote) Efficy.unplanAction(editHandle)

Converts a meeting to a task

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
Return
TSoapResponseHandle

(Remote) Efficy.updateAttachment(editHandle, idBlob, attachmentAsString, compress)

Updates an attached file and returns the key (K_FILE).

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
idBlob string
attachmentAsString ansistring The string content of the source file.
compress [Opt] boolean True If true, compresses the file.
Return
TSoapResponseHandle

(Remote) Efficy.updateAttachmentFromFile(editHandle, idBlob, attachmentPath, compress)

Updates an attached file from a file and returns the key (K_FILE).

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
idBlob string
attachmentPath string The path of the source file.
compress [Opt] boolean True If true, compresses the file.
Return
TSoapResponseHandle

(Remote) Efficy.updateBinaryField(editHandle, tableViewIndex, fieldName, value)

Updates the binary field values of a master data set in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
tableViewIndex integer Specify 0 to update the main entity data.
fieldName string The field to update.
value ansistring The field value
Return
TSoapResponseHandle

(Remote) Efficy.updateCategory(editHandle, category, fldNames, fldValues)

Updates field values of a category data set in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
category string The name of category to update.
fldNames variant The array of fields to update.
fldValues variant The array of field values. The number of elements in both arrays must be identical.
Return
TSoapResponseHandle

(Remote) Efficy.updateDetail(editHandle, detail, detailKey, fldNames, fldValues)

Updates field values of a detail relation in the edit context.
When the detail relation doesn't exist, an exception is thrown.
If detailKey is 0, the current detail record is used. (relationId is ignored in this case.)

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey string The key of the detail.
fldNames variant The array of fields to update.
fldValues variant The array of field values. The number of elements in both arrays must be identical.
Return
TSoapResponseHandle

Warning: Use UpdateDetail2 when no multiple relations are available on this detail relation. (The field "K_RELATION" doesn't exist in the database table.)

(Remote) Efficy.updateDetail2(editHandle, detail, detailKey, fldNames, fldValues)

Updates field values of a detail relation in the edit context.
If the detail relation does not exist, an exception is thrown.
If detailKey is 0, the current detail record is used.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey double The key of the detail.
fldNames variant The array of fields to update.
fldValues variant The array of field values. The number of elements in both arrays must be identical.
Return
TSoapResponseHandle

Warning: Use UpdateDetail when multiple relations are available on this detail relation. (The field "K_RELATION" exists in the database table.)

(Remote) Efficy.updateDetailEx(editHandle, detail, detailKey, k_Relation, fldNames, fldValues)

Updates field values of a detail relation in the edit context.
If the detail relation does not exist, an exception is thrown.
If detailKey is 0, the current detail record is used.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
detail TEntityHandle The detail handle.
detailKey double The key of the detail.
k_Relation integer The key of the relation.
fldNames variant The array of fields to update.
fldValues variant The array of field values. The number of elements in both arrays must be identical.
Return
TSoapResponseHandle

(Remote) Efficy.updateFields(editHandle, tableViewIndex, fldNames, fldValues)

Updates the field values of a master data set in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
tableViewIndex integer Specify 0 to update the main entity data.
fldNames variant The array of fields to update.
fldValues variant The array of field values. The number of elements in both arrays must be identical.
Return
TSoapResponseHandle

(Remote) Efficy.updateFields2(editHandle, tableViewIndex, fldNames, fldValues)

Updates the field values of a master data set in the edit context.

Parameter Type Default value Description
editHandle TContextHandle The handle of the edit context.
tableViewIndex integer Specify 0 to update the main entity data.
fldNames array of string The array of fields to update.
fldValues array of string The string array of field values. The number of elements in both arrays must be identical.
Return
TSoapResponseHandle

(Remote) Efficy.usersInGroup(groupId)

Retrieves the array of members of group GroupID.

Parameter Type Default value Description
groupId integer The key of the group.
Return
TSoapResponseHandle

(Remote) Efficy.writeAccountOption(fieldName, value)

Writes user options.

Parameter Type Default value Description
fieldName string The field name.
value variant The value to be written.
Return
TSoapResponseHandle

(Remote) Efficy.writeBoolean(section, ident, value)

Writes an boolean value into user options.

Parameter Type Default value Description
section string The name of the section.
ident string The name of the value.
value boolean The value to be written.

(Remote) Efficy.writeDateTime(section, ident, value)

Writes an DateTime value into user options.

Parameter Type Default value Description
section string The name of the section.
ident string The name of the value.
value TDateTime The value to be written.

(Remote) Efficy.writeInteger(section, ident, value)

Writes an integer value into user options.

Parameter Type Default value Description
section string The name of the section.
ident string The name of the value.
value integer The value to be written.

(Remote) Efficy.writeQueryToString(editHandle, queryDefinition)

Introduced in Efficy 11.3

Parameter Type Default value Description
editHandle TContextHandle
queryDefinition TPersistent
Return
TSoapResponseHandle

(Remote) Efficy.writeString(section, ident, value)

Writes a string value into user options.

Parameter Type Default value Description
section string The name of the section.
ident string The name of the value.
value string The value to be written.

Response reference

Methods

Response.setContent(content)

Introduced in Efficy 11.2 Sets the information sent to the web client in response to an HTTP request.
Only available in the context of a /node request.

Parameter Type Default value Description
content string The content to send.
Usage
Response.setContent(JSON.stringify(obj));

Response.setContentEncoding(contentEncoding)

Introduced in Efficy 11.2 Specifies the compression algorithm applied to the Content of the HTTP response.
Only available in the context of a /node request.

Parameter Type Default value Description
contentEncoding ansistring The content encoding (deflate, gzip, ...).

Response.setContentLength(contentLength)

Introduced in Efficy 11.2 Sets the size of the Content of the HTTP response, in decimal number of octets.
Only available in the context of a /node request.

Parameter Type Default value Description
contentLength integer The content size.

Response.setContentType(contentType)

Introduced in Efficy 11.2 Sets the media type of the Content of the HTTP response.
Only available in the context of a /node request.

Parameter Type Default value Description
contentType ansistring The media type. Default value: 'text/html; charset=UTF-8'
Usage
Response.setContentType('application/json; charset=UTF-8');

Response.setCookie(values, domain, path, expires, secure)

Introduced in Efficy 11.2 Sets a cookie in the HTTP response.
Only available in the context of a /node request.

Parameter Type Default value Description
values string The cookie values, in the format =.
domain ansistring The hosts to which the cookie will be sent.
path ansistring The URL path.
expires TDateTime The maximum lifetime of the cookie.
secure boolean A secure cookie will only be sent to the server when a request is made using SSL and the HTTPS protocol.
Usage
Response.setCookie('CustomSession=ABCD-1234\nCustomValue=56', 'localhost', '', incMonth(now(), 1), false);

Response.setHeader(name, value)

Introduced in Efficy 11.2 Sets a header item of the HTTP response.
Only available in the context of a /node request.

Parameter Type Default value Description
name string The name of the header item.
value string The value to set.
Usage
Response.setHeader('X-FromScript', 'Hello Efficy');
Response.setHeader('X-Efficy-Status', 'error'); Response.setHeader('X-Efficy-Error', (error && error.message) ? error.message : error);

Response.setRawContent(rawContent)

Introduced in Efficy 11.2 Sets the information sent to the web client in response to an HTTP request.
Only available in the context of a /node request.

Parameter Type Default value Description
rawContent ansistring The content to send.

Response.setStatusCode(statusCode)

Introduced in Efficy 11.2 Sets the status code of the Response.
Only available in the context of a /node request.

Parameter Type Default value Description
statusCode integer The status code (HTTP_OK: 200, HTTP_CREATED: 201, HTTP_ACCEPTED: 202, HTTP_NOCONTENT: 204, HTTP_BADREQUEST: 400, HTTP_NOTFOUND: 404, HTTP_NOTALLOWED: 405, ...).
Usage
Response.setStatusCode(202); // accepted

TDataSet reference

API interface class exposing properties and methods allowing read and write data from a database collection of records and fields.

Properties

Name Type Access Description
canModify boolean Read only Tests whether the data set can be modified by the current user.
eof boolean Read only Tests for the end of the data set (“end-of-file”).
fieldCount integer Read only The number of fields in the data set.
filter string Read/Write The text of the current SQL filter for the data set. Needs Filter property to be true.
filtered boolean Read/Write If true, the filtering is active for a data set. Set to "true" to activate the Filter property.
recordCount integer Read only The total number of records in the data set.

Methods

TDataSet.append()

Appends a new record after the last record of the data set.

Usage
ds.append();

TDataSet.delete()

Deletes the current record.

Warning: You may have to use the uppercase "Delete" form to avoid calling the native JavaScript delete() function.

Usage
ds.Delete(); // see warning

TDataSet.edit()

Puts the data set in the edit mode.

Note: this step is required before any update is made on an existing record.

Usage
ds.edit();

TDataSet.fieldByName(fieldName)

Returns a field whose value can be accessed or modified using the asString, asInteger, asFloat or value properties.
If the field does not exist, an exception is thrown.

Parameter Type Default value Description
fieldName string The name of the field.
Return
TField
Usage
ds.fieldByName('LAYOUT').asString = layout.join('\r\n');
var layout = ds.fieldByName('LAYOUT').asString;

TDataSet.findField(fieldName)

Returns a field whose value can be accessed or modified using the asString, asInteger, asFloat or value properties.
If the field doesn't exist, the function returns null.

Parameter Type Default value Description
fieldName string The name of the field.
Return
TField
Usage
if (ds.findField('D_BEGIN') && ds.findField('D_END')) { // Agenda type action
var field = ds.findField('D_BEGIN'); if (field) var value = field.asFloat;

TDataSet.first()

Positions the data set on the first record.

Usage
ds.first();

TDataSet.insert()

Inserts a new record in the data set at the current position.

Usage
ds.insert();

TDataSet.isEmpty()

Tests whether the data set contains any record.

Return
boolean
Usage
if (ds.isEmpty()) throw new Error('dataset is empty');

TDataSet.locate(fields, values, options)

Locate a record in the data set. The function returns true if a matching record is found, and will position the data set on the first record that matches the criteria.

Parameter Type Default value Description
fields string Semicolon (;) separated list of fields.
values array Array of values to be found.
options integer Options, 0 is recommended.
Return
boolean
Usage
if (dsMembers.locate('K_USER;K_SKILL', varArrayOf([user, skill]), 0)) { dsMembers.edit(); dsMembers.fieldByName('FIELD').asString = '0'; }

TDataSet.next()

Positions the data set on the next record.

Usage
var ds = Efficy.getDetailDataSet(editHandle, ntWidg); ds.first(); while (!ds.eof) { if (keys.indexOf(ds.fieldByName('K_WIDGET').asFloat) === -1) ds.Delete(); else ds.next(); }

TDataSet.post()

Posts the changes made to the current record in the data set.

Usage
if (!ds.locate('K_WIDGET', kWidget, 0)) { ds.insert(); ds.fieldByName('K_WIDGET').asFloat = kWidget; ds.fieldByName('K_DASHBOARD').asFloat = newKey; ds.post(); }

TEnhStringList reference

API interface class exposing properties and methods allowing to manipulate a list of text strings. The string index is 0-based: the first string has index 0, last string has index (count - 1).
Instances of this class must be explicitly freed with free() when created with create().

Properties

Name Type Access Description
allowEmptyValues boolean Read/Write Introduced in Efficy 11.2 If true, allows names with empty values to exist in the list. By default names with empty values are removed from the list.
commaText string Read/Write The full content of the list with individual strings separated by a comma.
count integer Read only The count of elements into the list.
names(integer) string Read only The name at a specified index, when the list contains strings with format "Name=Value" is used.
var name = sl.names(3).
sorted boolean Read/Write If true, the list is automatically sorted.
strings(Integer) string Read/Write An element of the list. The first string has index 0, last string has index (count - 1).
text string Read/Write The full text content of the list, with strings separated by new line separators (CR+LF).
values(string) string Read/Write The value associated with a name. var value = sl.values('Name').
valuesFromIndex(integer) string Read only A value by index. var value = sl.valuesFromIndex(4).

Methods

TEnhStringList.add()

Add a string to the list.

Usage
var ResultList = TEnhStringList.create(); try { ds.first(); while (! ds.eof) { var EMail = Trim(ds.fieldByName('EMAIL1').asString); if (EMail) ResultList.add(ds.fieldByName('NAME').asString + ' ' + ds.fieldByName('FIRSTNAME').asString + ' <' + EMail + '>') ds.next(); } Emails = ResultList.getText(',', true); } finally { ResultList.free(); }

TEnhStringList.append()

Add a string to the list, same as add().

TEnhStringList.clear()

Empties the list.

Usage
sl.clear();

TEnhStringList.create()

Creates an instance of TEnhStringList.

Instances of this class must be explicitly freed with free() when created with create().

Usage
var sl = TEnhStringList.create(); try { ... } finally { sl.free(); }

TEnhStringList.delete(index)

Removes a string from the list.

Parameter Type Default value Description
index integer The index of the item in the list.
Usage
sl.delete(sl.count - 1);

TEnhStringList.exchange(index1, index2)

Exchanges two strings in the list.

Parameter Type Default value Description
index1 integer The first index of the item in to exchange.
index2 integer The second index of the item in to exchange.
Usage
sl.exchange(0, sl.count - 1);

TEnhStringList.free()

Frees the instance of TEnhStringList. See create().

TEnhStringList.getString(index)

Retrieves a string for a given index.

Parameter Type Default value Description
index integer The index of the string.
Return
string
Usage
var firstString = sl.getString(0);
var lastString = sl.getString(sl.count - 1);

TEnhStringList.getText(separator, removeLastSeparator)

Retrieve the full text of the list, with strings separated by a separator string.

Parameter Type Default value Description
separator string Separator string that will be inserted after each element of the list.
removeLastSeparator [Opt] boolean False Remove separator after the final element of the list.
Return
string
Usage
var mails = sl.getText(';', true);

TEnhStringList.indexOf(s)

Retrieves the index of the string in the list. Returns -1 if the string was not found.

Parameter Type Default value Description
s string The string to retrieve.
Return
integer
Usage
var n = sl.indexOf('myvalue');

TEnhStringList.indexOfName(name)

Retrieves the index of the name in a list formatted as Name=Value. Returns -1 if the string was not found.

Parameter Type Default value Description
name string The name to retrieve index for.
Return
integer
Usage
var n = sl.indexOfName('MyName'); if (n >= 0) { var myName = sl.valuesFromIndex(n); }

TEnhStringList.insert(index, s)

Inserts a string at a defined index in the list.

Parameter Type Default value Description
index integer The index where to place the item in the list.
s string The string to be inserted.
Usage
sl.insert(0, 'myvalue'); // insert at the start of the list

TEnhStringList.loadFromFile(fileName)

Loads the content of a text file in the list.

Parameter Type Default value Description
fileName string The full path of the file to be loaded.
Usage
sl.loadFromFile('C:\\temp\\import.txt');

TEnhStringList.saveToFile(fileName)

Saves the content of the list to a text file.

Parameter Type Default value Description
fileName string The full path of the file to be saved.
Usage
sl.saveToFile('C:\\temp\\output.txt');

TEntityCatalog reference

API interface class exposing properties and methods allowing to convert between entities related system names and IDs. It can be referenced directly through the "Efficy.entityCatalog" property of the API interface "Efficy".

Methods

Efficy.entityCatalog.detailFromTableId(tableId)

Retrieves the detail entity handle from a relation table ID.

Parameter Type Default value Description
tableId integer The ID of the table.
Return
TEntityHandle
Usage
var detail = Efficy.entityCatalog.detailFromTableID(11010); // ntContComp (11010)

Efficy.entityCatalog.entityFromTableId(tableId)

Retrieves the entity handle from a table ID.

Parameter Type Default value Description
tableId integer The ID of the table.
Return
TEntityHandle
Usage
var entity = Efficy.entityCatalog.entityFromTableID(10000); // ntComp (10)

Efficy.entityCatalog.entityNameFromTableId(tableId)

Retrieves the string identifier of an entity from a table ID.

Parameter Type Default value Description
tableId integer The ID of the table.
Return
string
Usage
var name = Efficy.entityCatalog.entityNameFromTableID(10000); // "Comp"
var favorites = [], ds = Efficy.consultFavorites(); ds.first(); while (!ds.eof) { favorites.push(Efficy.entityCatalog.entityNameFromTableId(ds.fieldByName('K_TABLE').asInteger)); ds.next(); }

Efficy.entityCatalog.getEntityHandle(entityName)

Retrieves the entity handle from its string identifier.

Parameter Type Default value Description
entityName string The string identifier of the entity.
Return
TEntityHandle
Usage
var entity = Efficy.entityCatalog.GetEntityHandle('Comp'); // ntComp (10)

Efficy.entityCatalog.getEntityLabel(entity)

Returns the translated label of an entity from an entity handle.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
string
Usage
var label = Efficy.entityCatalog.getEntityLabel(ntComp); // "Company"

Efficy.entityCatalog.getEntityName(entity)

Retrieves the string identifier of an entity from an entity handle.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
string
Usage
var name = Efficy.entityCatalog.getEntityName(ntComp); // "Comp"

Efficy.entityCatalog.getRelationEntityTableName(entity, detail)

Retrieves a relation table name from entity and detail handles.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
Return
string
Usage
var tableName = Efficy.entityCatalog.getRelationEntityTableName(ntComp, ntCont); // "CONT_COMP"

Efficy.entityCatalog.keyFieldName(entity)

Retrieves the key field of an entity from an entity handle.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
string
Usage
var keyField = Efficy.entityCatalog.keyFieldName(ntComp); // "K_COMPANY"

Efficy.entityCatalog.tableIdFromEntity(entity)

Retrieves a table ID from an entity from an entity handle.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
integer
Usage
var compTableId = Efficy.entityCatalog.tableIdFromEntity(ntComp); // 10000

Efficy.entityCatalog.tableIdFromEntityDetail(entity, detail)

Retrieves a relation table ID from entity and detail handles.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
detail TEntityHandle The detail handle.
Return
integer
Usage
var compContTableId = Efficy.entityCatalog.tableIDFromEntityDetail(ntComp, ntCont); // 11010

Efficy.entityCatalog.tableIdFromEntityName(entityName)

Retrieves a table ID from an entity string identifier.

Parameter Type Default value Description
entityName string The string identifier.
Return
integer
Usage
var compTableId = Efficy.entityCatalog.tableIdFromEntityName('Comp'); // 10000
var tableName = Efficy.entityCatalog.getRelationEntityTableName(Efficy.entityCatalog.tableIdFromEntityName(entity) / 1000, ntUser);

Efficy.entityCatalog.tableIdFromName(tableName)

Retrieves a table ID from a table name.

Parameter Type Default value Description
tableName string The table name.
Return
integer
Usage
var tableID = Efficy.entityCatalog.tableIDFromName('COMPANIES'); // 10000

Efficy.entityCatalog.tableName(entity)

Retrieves a table name from an entity handle.

Parameter Type Default value Description
entity TEntityHandle The entity handle.
Return
string
Usage
var name = Efficy.entityCatalog.tableName(ntComp); // "COMPANIES"

TFormatSettings reference

Defines a data structure containing locale information (date, time and numeric format) used by some string formatting routines.
Any usage must start by the creation of an instance of the structure by calling the create() method.

Properties

Name Type Access Description
currencyDecimals integer Read/Write The maximum number of digits, after decimal point, for a currency value.
currencyString string Read/Write The local currency symbol.
dateSeparator char Read/Write The character used as date separator.
decimalSeparator char Read/Write The character used to separate the integer part from the fractional part of a number.
listSeparator char Read/Write The character used to separate items in a list.
longDateFormat string Read/Write The long format string used to represent a date value as a string.
longTimeFormat string Read/Write The long format string used to represent a time value as a string.
shortDateFormat string Read/Write The short format string used to represent a date value as a string.
shortTimeFormat string Read/Write The short format string used to represent a time value as a string.
thousandSeparator char Read/Write The character used to separate thousands in numbers with more than three digits to the left of the decimal separator.
timeAmString string Read/Write The suffix string used for time values in the first 12 hours of the day.
timePmString string Read/Write The suffix string used for time values in the last 12 hours of the day.
timeSeparator char Read/Write The character used to separate the hour, minute, and second parts of a time value.

Methods

TFormatSettings.create()

Creates an instance of the record. TFormatSettings is a record, not a class, and therefore does not need to be destroyed/freed explicitly.

Return
TFormatSettings
Usage
var fs = TFormatSettings.create(); fs.decimalSeparator = ','; fs.shortDateFormat = 'dd/MM/yyyy'; var dateText = dateTimeToStr2(dateValue, fs); var numericText = formatFloat2('#.##', amount, fs);

TMagickWand reference

API interface class exposing properties and methods allowing to perform operations on image binary data using the ImageMagick library.
Instances of this class must be explicitly freed with free() when created with create().
MW.loadFromFile('C:\picture.png');
MW.thumbnailImage(50, 50);
var MW = TMagickWand.create();

Properties

Name Type Access Description
imageHeight nativeint Read only The height of the image.
imageWidth nativeint Read only The width of the image.

Methods

TMagickWand.create()

Creates an instance of TMagickWand.

TMagickWand.free()

Frees the instance of TMagickWand.

TMagickWand.loadFromFile(fileName)

Loads the file specified in the parameter fileName into the TMagickWand object.

Parameter Type Default value Description
fileName ansistring The full path of the file.
Return
boolean

TMagickWand.resizeImage(columns, rows, filter, blur)

Resizes the image to the desired Width and Height.

Parameter Type Default value Description
columns nativeint The width to be set.
rows nativeint The height to be set.
filter [Opt] imfiltertype ftLanczos Do not specify.
blur [Opt] double 1 Do not specify.
Return
boolean

TMagickWand.sampleImage(columns, rows)

Scales an image to the desired Width and Height with pixel sampling.

Parameter Type Default value Description
columns nativeint The width to be set.
rows nativeint The height to be set.
Return
boolean

TMagickWand.saveImageToFile(fileName)

Saves the image in the file specified in the parameter fileName .

Parameter Type Default value Description
fileName ansistring The full path of the file.
Return
boolean

TMagickWand.saveToFile(fileName, multiImageFile)

Saves the image in the file specified in the parameter fileName .

Parameter Type Default value Description
fileName ansistring The full path of the file.
multiImageFile boolean If true, joins several images into a single multi-image file.
Return
boolean

TMagickWand.thumbnailImage(columns, rows)

Changes the size of an image to the given dimensions and removes any associated profiles. The objective is to produce small thumbnail images suited for display on the web.

Parameter Type Default value Description
columns nativeint The width to be set.
rows nativeint The height to be set.
Return
boolean

Library reference

Collection of utility methods available in the global scripting context as-is, without the "Efficy." prefix.

Methods

computeSoundex(s)

Introduced in Efficy 11.1 Converts a string value to the corresponding Soundex code.

Parameter Type Default value Description
s string The value to convert.
Return
string
Usage
var soundsLikeName = computeSoundex(name);

contextEncode(s, contexts)

Introduced in Efficy 11.1 Encodes a string for one or multiple output contexts.
This method is identical to the deprecated Efficy.contextEncode() function and available without the Efficy prefix.

Parameter Type Default value Description
s string The string to encode.
contexts string Comma separated list of contexts (ex: "TEXT" or "ATTR,JS").
The available contexts are: TEXT, ATTR, JS, CSS, URL, HTML, or TAG.
Return
string
Usage
return contextEncode(name, 'TEXT');

contextEncodeHtml(s)

Introduced in Efficy 11.1 Encodes a string for the HTML output context: raw data that must be rendered as HTML (e.g. WYSIWYG editors, formatted memos).
This method is a shortcut to contextEncode(s, 'HTML').

Parameter Type Default value Description
s string The string to encode.
Return
string

Warning: This Context method is particularly time consuming and should be avoided unless totally necessary. It will remove all inline events (onclick…), scripts tags, and so on.

Usage
return contextEncodeHtml(body);

contextEncodeJs(s)

Introduced in Efficy 11.1 Encodes a string for the JavaScript output context.
This method is a shortcut to contextEncode(s, 'JS') and replaces the method EscapeJavascriptText() deprecated in Efficy 11.1.

Parameter Type Default value Description
s string The string to encode.
Return
string
Usage
return contextEncodeJs(name);

contextEncodeText(s)

Introduced in Efficy 11.1 Encodes a string for the Text output context: text data inside HTML, which must be encoded to avoid rendering HTML elements.
This method is a shortcut to contextEncode(s, 'TEXT') and replaces method escapeHTML() deprecated in Efficy 11.1.

Parameter Type Default value Description
s string The string to encode.
Return
string
Usage
return contextEncodeText(name);

copyFile(existingFileName, newFileName, failIfExists)

Introduced in Efficy 11.2 Copies a file in the file system. Returns true if operation is successful.

Parameter Type Default value Description
existingFileName string The current file path.
newFileName string The new file path.
failIfExists boolean If true, aborts copy if destination file already exists.
Return
boolean
Usage
if (copyFile(sourceDir + fileName, destinationDir + fileName, true)) { ... };

currencyString()

Specifies the currency symbol.

Return
ansistring
Usage
var currency = currencyString;

currentRecordToJson(dataSet, metadata, fields, contexts, datesAsIso8601)

Introduced in Efficy 11.2 Serializes the current record of a data set to JSON string.

Parameter Type Default value Description
dataSet TDataSet The source data set.
metadata [Opt] boolean False If true, includes metadata information, data contains no field names.
fields [Opt] string '' The list of fields to include. If empty, all data set fields are included.
contexts [Opt] string '' The list of security contexts to use to encode the output data for.
datesAsIso8601 [Opt] boolean True If true, returns date and time fields as an ISO-8601 date-and-time value (ex: 2008-09-15T15:53:00+05:00), if false returns them in Delphi date float format.
Return
string
Usage
var consultHandle = Efficy.openConsultContext(ntDocu), fields = Request.argument('fields'), meta = Request.booleanArgument('meta'), ds = Efficy.consult(consultHandle, parseFloat(key), true), obj = JSON.parse(currentRecordToJson(ds, meta, fields, 'JS', true));

dataSetToJson(dataSet, metadata, fields, contexts, maxRecords, top, datesAsIso8601)

Serializes a data set to JSON string.

Parameter Type Default value Description
dataSet TDataSet The source data set.
metadata [Opt] boolean False If true, includes metadata information, data contains no field names.
fields [Opt] string '' The list of fields to include. If empty, all data set fields are included.
contexts [Opt] string '' The list of security contexts to use to encode the output data for.
maxRecords [Opt] integer 0 The maximum number of records to include. If empty, all data set records are included.
top [Opt] integer 0 The record number at which to start the serialization. If empty, serialization starts from the first record.
datesAsIso8601 [Opt] boolean True Introduced in Efficy 11.2 If true, returns date and time fields as an ISO-8601 date-and-time value (ex: 2008-09-15T15:53:00+05:00), if false returns them in Delphi date float format.
Return
string

The data type constants are:

DATATYPE_STRING = 1
DATATYPE_INTEGER = 2
DATATYPE_FLOAT = 3
DATATYPE_DATE = 4

Usage
var ds = Efficy.consultFavorites(), favorites = JSON.parse(dataSetToJson(ds, true, ['K_1', 'ENTITY', 'NAME'].join()));

dateSeparator()

Specifies the character used to separate the year, month, and day parts of a date value.

Return
ansistring
Usage
var separator = dateSeparator;

decimalSeparator()

Specifies the character used to separate the integer part from the fractional part of a floating-point value.

Return
ansistring
Usage
var separator = decimalSeparator;

decodeMime64Utf8(s)

Introduced in Efficy 11.2 Decodes a Mime64 (Base64) UTF8 string.

Parameter Type Default value Description
s string The source string to decode.
Return
string
Usage
var fileStr = decodeMime64Utf8(attachments[i].data);

decryptAes(s, passPhrase, prefix)

Introduced in Efficy 11.1 Decrypts a data string with the AES (Rijndael) algorithm, using a specified passphrase.

Parameter Type Default value Description
s string The data string to decrypt.
passPhrase string The passphrase that will be used as the decryption key.
prefix [Opt] string '' If specified, the presence of this prefix will be tested before decrypting the data string to verify if the string is encrypted. The prefix will be removed before decryption.
Return
string
Usage
var password = decryptAes(encryptedPassword, secretKey, '$AES$');

deleteFile(fileName)

Introduced in Efficy 11.2 Deletes a file in the file system. Returns true if operation is successful.

Parameter Type Default value Description
fileName string The file path
Return
boolean
Usage
if (deleteFile(fileName)) { ... }

directoryExists(name)

Introduced in Efficy 11.2 Tests whether a directory (folder) exists in the file system.

Parameter Type Default value Description
name string The directory path
Return
boolean
Usage
if (directoryExists(path)) { ... }

encodeMime64Utf8(s)

Introduced in Efficy 11.2 Encodes a UTF8 string to Mime64 (Base64).

Parameter Type Default value Description
s string The source string to encode.
Return
string
Usage
var encodedText = encodeMime64Utf8(myString);

encryptAes(s, passPhrase, prefix)

Introduced in Efficy 11.1 Encrypts a data string with the AES (Rijndael) algorithm, using a specified passphrase.

Parameter Type Default value Description
s string The data string to encrypt.
passPhrase string The passphrase that will be used as the encryption key.
prefix [Opt] string '' If specified, this prefix will be added to the result of the encryption to help identify a string as encrypted. The prefix itself is not encrypted.
Return
string
Usage
var encryptedPassword = encryptAes(password, secretKey, '$AES$');

escapeHtml(s)

Deprecated, please use contextEncodeText.

Parameter Type Default value Description
s string The string to encode.
Return
string

escapeRtf(s)

Escapes text to make it safe to insert into an RTF document. To be used only in a template merge script generating an RTF file.

Parameter Type Default value Description
s string The text to escape.
Return
string
Usage
return escapeRtf(mergedData);

escapeXml(s)

Escapes text to make it safe to insert into an XML document. To be used only in a template merge script generating a DOCX, XLSX or PPTX file.

Parameter Type Default value Description
s string The text to escape.
Return
string
Usage
return escapeXml(mergedData);

extractHtmlBody(html)

Introduced in Efficy 11.2 Returns all the contents of an HTML document contained inside the <body></body> tag.

Parameter Type Default value Description
html string The HTML source text.
Return
string
Usage
var bodyText = extractHtmlBody(fileData);

extractHtmlText(html, maxLength)

Introduced in Efficy 11.2 Returns the text contents of an HTML document (strips all the tags).

Parameter Type Default value Description
html string The HTML source text.
maxLength [Opt] integer 0 The maximum number of characters to return.
Return
string
Usage
var bodyText = extractHtmlText(body, 1024);

floatToStr(value)

Converts a floating-point value into a string.

Parameter Type Default value Description
value extended The value to be converted.
Return
string
Usage
var text = floatToStr(x);

format(format, args)

Returns a formatted string assembled from a format string and a series of untyped arguments array.

Parameter Type Default value Description
format string The output format string (see below).
args array of const The array of arguments to apply to the format specifiers in the format string.
Return
string

The format string specifies required formats to general-purpose formatting routines. It contains two types of objects-literal characters and format specifiers. Literal characters are copied word for word to the resulting string. Format specifiers fetch arguments from the argument list and apply the formatting to them.
Format specifiers have the following form: "%" [index ":"] ["-"] [width] ["." prec] type
A format specifier begins with a % character. After the percent sign come the following elements, in this order:
1 - An optional argument zero-offset index specifier (that is, the first item has index 0), [index ":"].
2 - An optional left justification indicator, ["-"].
3 - An optional width specifier, [width].
4 - An optional precision specifier, ["." prec].
5 - The conversion type character, type.

The following table summarizes the possible values for type:
d: Decimal. The argument must be an integer value. The value is converted to a string of decimal digits. If the format string contains a precision specifier, it indicates that the resulting string must contain at least the specified number of digits; if the value has less digits, the resulting string is left-padded with zeros.
u: Unsigned decimal. Similar to d, but no sign is output.
e: Scientific. The argument must be a floating-point value. The value is converted to a string of the form "-d.ddd...E+ddd". The resulting string starts with a minus sign if the number is negative. One digit always precedes the decimal point. The total number of digits in the resulting string (including the one before the decimal point) is given by the precision specifier in the format string; a default precision of 15 is assumed if no precision specifier is present. The "E" exponent character in the resulting string is always followed by a plus or minus sign and at least three digits.
f: Fixed. The argument must be a floating-point value. The value is converted to a string of the form "-ddd.ddd...". The resulting string starts with a minus sign if the number is negative. The number of digits after the decimal point is given by the precision specifier in the format string—a default of 2 decimal digits is assumed if no precision specifier is present.
g: General. The argument must be a floating-point value. The value is converted to the shortest possible decimal string using fixed or scientific format. The number of significant digits in the resulting string is given by the precision specifier in the format string; a default precision of 15 is assumed if no precision specifier is present. Trailing zeros are removed from the resulting string, and a decimal point appears only if necessary. The resulting string uses the fixed-point format if the number of digits to the left of the decimal point in the value is less than or equal to the specified precision, and if the value is greater than or equal to 0.00001. Otherwise the resulting string uses scientific format.
n: Number. The argument must be a floating-point value. The value is converted to a string of the form "-d,ddd,ddd.ddd...". The n format corresponds to the f format, except that the resulting string contains thousand separators.
m: Money. The argument must be a floating-point value. The value is converted to a string that represents a currency amount. The conversion is controlled by the CurrencyString, CurrencyFormat, NegCurrFormat, ThousandSeparator, DecimalSeparator, and CurrencyDecimals global variables or their equivalent in a TFormatSettings data structure. If the format string contains a precision specifier, it overrides the value given by the CurrencyDecimals global variable or its TFormatSettings equivalent.
p: Pointer. The argument must be a pointer value. The value is converted to an 8-character string that represents the pointer's value in hexadecimal.
s: String. The argument must be a character, a string value. The string or character is inserted in place of the format specifier. The precision specifier, if present in the format string, specifies the maximum length of the resulting string. If the argument is a string that is longer than this maximum, the string is truncated.
x: Hexadecimal. The argument must be an integer value. The value is converted to a string of hexadecimal digits. If the format string contains a precision specifier, it indicates that the resulting string must contain at least the specified number of digits; if the value has fewer digits, the resulting string is left-padded with zeros.

Usage
var s = format('%d %%', [100]); // displays '100 %'
var s = format('<%.6d>', [1234]) // displays <001234>
var s = format('Hello %s!', ['Efficy']); // displays 'Hello Efficy!'

format2(format, args, settings)

Introduced in Efficy 11.1 Returns a formatted string assembled from a format string and a series of untyped arguments array using a set of custom regional format settings.

Parameter Type Default value Description
format string The output format string (see above).
args array of const The array of arguments to apply to the format specifiers in the format string.
settings TFormatSettings The FormatSettings record specifying the regional settings.
Return
string
Usage
var fs = TFormatSettings.create(); fs.decimalSeparator = ','; var numericText = format2('%.1f', amount, fs);

formatFloat(format, value)

Converts a Float into a string according to the given format.

Parameter Type Default value Description
format string The format to be used.
value extended The float to be converted.
Return
string

The following table summarizes the possible format specifiers:
"0": Digit placeholder. If the value being formatted has a digit in the position where '0' appears in the format string, then that digit is copied to the output string. Otherwise, a '0' is stored in that position in the output string.
"#": Digit placeholder. If the value being formatted has a digit in the position where '#' appears in the format string, then that digit is copied to the output string. Otherwise, nothing is stored in that position in the output string.
".": Decimal point. The first '.' character in the format string determines the location of the decimal separator in the formatted value; any additional '.' characters are ignored. The actual character used as a decimal separator in the output string is determined by the DecimalSeparator global variable or its TFormatSettings equivalent.
",": Thousand separator. If the format string contains one or more ',' characters, the output will have thousand separators inserted between each group of three digits to the left of the decimal point. The placement and number of ',' characters in the format string does not affect the output, except to indicate that thousand separators are wanted. The actual character used as a thousand separator in the output is determined by the ThousandSeparator global variable or its TFormatSettings equivalent.
E+: Scientific notation. If any of the strings 'E+', 'E-', 'e+', or 'e-' are contained in the format string, the number is formatted using scientific notation. A group of up to four '0' characters can immediately follow the 'E+', 'E-', 'e+', or 'e-' to determine the minimum number of digits in the exponent. The 'E+' and 'e+' formats cause a plus sign to be output for positive exponents and a minus sign to be output for negative exponents. The 'E-' and 'e-' formats output a sign character only for negative exponents.
'xx'/"xx": Characters enclosed in single or double quotation marks are output as such and do not affect formatting.
";": Separates sections for positive, negative, and zero numbers in the format string.

Usage
var s = formatfloat('#####', float); // displays '1235'
var s = formatfloat('#,##0', 1234.567); // displays '1,235'
var s = formatfloat('0.0000', 1234.567); // displays '1234.5670'

formatFloat2(format, value, settings)

Introduced in Efficy 11.1 Converts a Float into a string according to the given format using a set of custom regional format settings.

Parameter Type Default value Description
format string The format to be used.
value extended The float to be converted.
settings TFormatSettings The FormatSettings record specifying the regional settings.
Return
string
Usage
var fs = TFormatSettings.create(); fs.decimalSeparator = ','; var numericText = formatFloat2('#.##', amount, fs);

hashMd5(s)

Introduced in Efficy 11.1 Returns the MD5 hash of the specified data string.
Warning! Provided for legacy purposes only. The MD5 algorithm has been broken and is not safe to use for storing passwords or sensitive data. For that purpose, use SHA256.

Parameter Type Default value Description
s string The data string to hash.
Return
string

hashSha1(s)

Introduced in Efficy 11.1 Returns the SHA1 hash of the specified data string.
Warning ! Provided for legacy purposes only. The SHA1 algorithm has been broken and is not safe to use for storing passwords or sensitive data. For that purpose, use SHA256.

Parameter Type Default value Description
s string The data string to hash.
Return
string

hashSha256(s)

Introduced in Efficy 11.1 Returns the SHA256 hash of the specified data string.
This algorithm is safe to use for storing passwords or sensitive data.

Parameter Type Default value Description
s string The data string to hash.
Return
string
Usage
var hash = hashSha256(password);

intToStr(value)

Converts an integer into a string.

Parameter Type Default value Description
value integer The value to be converted.
Return
string
Usage
var n = intToStr(text);

lineDiff(newFile, oldFile, diffFile, headerLines)

Introduced in Efficy 11.2 Writes to DiffFile the lines in NewFile that are not found in OldFile. Returns the number of lines written in DiffFile.

Parameter Type Default value Description
newFile string The new file path.
oldFile string The old file path.
diffFile string The result file path.
headerLines [Opt] integer 0 The number of header lines that will be copied from newFile.
Return
integer
Usage
var dir = 'C:\\temp\\'; var n = lineDiff(dir + 'import1.txt', dir + 'import0.txt', dir + 'importdelta.txt');

listFileNames(folder, list)

Introduced in Efficy 11.2 Lists all the files in a directory (folder) in the file system.

Parameter Type Default value Description
folder string The folder path.
list TStrings Returns the files found in the folder in this StringList (create the object first with TEnhStringList.create()
Usage
var fileList = TEnhStringList.create(); try { listFileNames('C:\\temp', fileList); ... } finally { fileList.free(); }

locateByKey(dataSet, fieldName, key)

Searches a data set for a single key. Position on the record and returns true if the record was found.
Internally this uses TDataset.locate().

Parameter Type Default value Description
dataSet TDataSet The data set.
fieldName string The key field name.
key double The key of the record.
Return
boolean
Usage
var srcMemberExists = locateByKey(dsSrcMembers, 'K_TEAMMEMBER', kTeamMember);

locateByKeys(dataSet, fieldNames, keys)

Searches a data set for a multiple key. Position on the record and returns true if the record was found.
Internally this uses TDataset.locate().

Parameter Type Default value Description
dataSet TDataSet The data set.
fieldNames string The key field name, dot-coma separated.
keys variant The list of values of the multiple key.
Return
boolean
Usage
var dstMemberExists = locateByKeys(dsDstMembers, 'K_USER;K_SKILL', varArrayOf([kUser, kSkill]));

longDateFormat()

Specifies the format string used to convert a date value to a user-friendly string, in long format.

Return
ansistring
Usage
var f = longDateFormat;

longTimeFormat()

Specifies the format string used to convert a date value to a user-friendly string, in long format.

Return
ansistring
Usage
var f = longTimeFormat;

lowerCase(s)

Converts a string to lower case.

Parameter Type Default value Description
s string The string to be converted.
Return
string
Usage
var searchString = lowerCase(name);

removeInvalidFileChars(fileName)

Introduced in Efficy 11.2 Removes invalid file chars of a file name, such as '\', '/', ':', '*', '?', '"', '<', '>' and '|'.

Parameter Type Default value Description
fileName string The file name.
Return
string
Usage
fileName = removeInvalidFileChars(fileName);

renameFile(oldName, newName)

Introduced in Efficy 11.2 Renames a file in the file system. Returns true if operation is successful.

Parameter Type Default value Description
oldName string The current file path.
newName string The new file path.
Return
boolean
Usage
if (renameFile('C:\\temp\\' + fileName, 'C:\\prod\\' + fileName)) { ... }

sameText(s1, s2)

Compares the strings S1 and S2 without case sensitivity and returns true when they are equal.

Parameter Type Default value Description
s1 string The first string.
s2 string The second string.
Return
boolean

Warning: This function is not case-sensitive. The strings ABC, abc, Abc and aBC are all equal.

Usage
if (sameText(name, 'Efficy')) { ... }

shortDateFormat()

Specifies the short format string used to represent a date value as a string.

Return
ansistring
Usage
var f = shortDateFormat;

shortTimeFormat()

Specifies the short format string used to represent a time value as a string.

Return
ansistring
Usage
var f = shortTimeFormat;

smartCompressEx(stream, fileName)

Compresses the stream and returns it.
If a Filename is specified, SmartCompressEx checks if it is necessary to compress it (depending on the file extension).

Parameter Type Default value Description
stream ansistring The content to be compressed.
fileName [Opt] string '' The full path to the file.
Return
ansistring
Usage
var compressedStream = smartCompressEx(stream, 'myDoc.docx');

smartCompressFromFile(fileName)

Introduced in Efficy 11.1 Compresses the stream of a file and returns it.

Parameter Type Default value Description
fileName string The full path to the source file.
Return
ansistring
Usage
var compressedStream = smartCompressFromFile('C:\\temp\\myDoc.docx');

smartDecompressEx(stream)

Decompresses the stream and returns it.

Parameter Type Default value Description
stream ansistring The content to be decompressed.
Return
ansistring
Usage
var stream = smartDecompressEx(compressedStream);

smartDecompressToFile(stream, fileName)

Introduced in Efficy 11.1 Decompresses the stream and saves it in a file.

Parameter Type Default value Description
stream ansistring The content to be decompressed.
fileName string The full path to the destination file.
Usage
smartDecompressToFile(compressedStream, 'C:\\temp\\myDoc.docx');

standardFloatToStr(value)

Introduced in Efficy 11.2 Converts a floating-point value to a string in standard format, using a point as decimal separator.

Parameter Type Default value Description
value extended The value to be converted.
Return
string
Usage
var numericText = standardFloatToStr(x);

standardStrToFloat(value)

Introduced in Efficy 11.2 Converts a string in standard format to a floating-point value, using a point as decimal separator.

Parameter Type Default value Description
value string The value to be converted.
Return
extended
Usage
var x = standardStrToFloat(numericText);

strAssemble(s1, s2, separator)

Concatenates two strings and adds the separator if both strings are not empty.

Parameter Type Default value Description
s1 string The first string.
s2 string The second string.
separator string The separator.
Return
string
Usage
var text = strAssemble(text, item, ';');

strLoadBinaryFile(fileName)

Loads a binary file from the hard disk.

Parameter Type Default value Description
fileName string The full path to the file.
Return
ansistring
Usage
var stream = strLoadBinaryFile('C:\\temp\\myDoc.docx');

strLoadTextFile(fileName)

Loads a text file from the hard disk.

Parameter Type Default value Description
fileName string The full path to the file.
Return
utf8string
Usage
var text = strLoadTextFile('C:\\temp\\report.csv');

strSaveBinaryFile(fileName, source, append)

Saves a binary file to the hard disk.

Parameter Type Default value Description
fileName string The full path to the file.
source rawbytestring The content to be saved.
append [Opt] boolean False If true, appends the content if the file already exists.
Usage
strSaveBinaryFile('C:\\temp\\myDoc.docx', stream);

strSaveTextFile(fileName, source, append)

Saves a text file to the hard disk.

Parameter Type Default value Description
fileName string The full path to the file.
source utf8string The content to be saved.
append [Opt] boolean False If true, appends the content if the file already exists.
Usage
strSaveTextFile('C:\\temp\\report.csv', text);

strToBool(s)

Converts a string into a boolean value.

Parameter Type Default value Description
s string The string to be converted. It can be "0", "1", "False", "True".
Return
boolean
Usage
var refreshNeeded = strToBool(Request.argument('refresh'));

strToBoolDef(s, default)

Tries to convert a string into a boolean value.
If the conversion fails, the default value is returned.

Parameter Type Default value Description
s string The string to be converted.
default boolean The default value.
Return
boolean
Usage
var refreshNeeded = strToBool(Request.argument('refresh'), false);

strToFloat(s)

Converts a string into a floating-point value.

Parameter Type Default value Description
s string The string to be converted.
Return
extended
Usage
var x = strToFloat(Request.argument('key'));

strToFloatDef(s, default)

Tries to convert a string into a floating-point value.
If the conversion fails, the default value is returned.

Parameter Type Default value Description
s string The string to be converted.
default extended The default value.
Return
extended
Usage
var x = strToFloatDef(Request.argument('key'), -1);

strToInt(s)

Converts a string into an integer value.

Parameter Type Default value Description
s string The string to be converted.
Return
integer
Usage
var n = strToInt(Request.argument('user'));

strToIntDef(s, default)

Tries to convert a string into an integer value.
If the conversion fails, the default value is returned.

Parameter Type Default value Description
s string The string to be converted.
default integer The default value.
Return
integer
Usage
var n = strToIntDef(Request.argument('user'), 0);

thousandSeparator()

Specifies the short format string used to represent a time value as a string.

Return
ansistring
Usage
var separator = thousandSeparator;

timeSeparator()

Specifies the character used to separate the hour, minute, and second parts of a time value.

Return
ansistring
Usage
var separator = timeSeparator;

trim(s)

Trims a string on left and right.

Parameter Type Default value Description
s string The string to be trimmed.
Return
string
Usage
var name = trim(ds.fieldByName('NAME').asString);

trimLeft(s)

Trims a string on the left.

Parameter Type Default value Description
s string The string to be trimmed.
Return
string
Usage
var name = trimLeft(ds.fieldByName('NAME').asString);

trimRight(s)

Trims a string on the right.

Parameter Type Default value Description
s string The string to be trimmed.
Return
string
Usage
var name = trimRight(ds.fieldByName('NAME').asString);

upperCase(s)

Converts a string to upper case.

Parameter Type Default value Description
s string The string to be converted.
Return
string
Usage
var searchString = upperCase(name);

varArrayElement(v, index1, index2)

Retrieves an element into a variant array.

Parameter Type Default value Description
v olevariant The variant array.
index1 integer The index of the element.
index2 [Opt] integer -1 The second index of the element if the array has two dimensions.
Return
olevariant
Usage
var mergeArguments = TEnhStringList.create(); var editHandle = Efficy.openEditContext(ntCont, contID); try { mergeArguments.values('PasswordUrl') = passwordUrl; var mergeResult = Efficy.mergeEmailTemplateVariant(editHandle, templateId, mergeArguments); var body = VarArrayElement(mergeResult, 0), subject = VarArrayElement(mergeResult, 1); } finally { mergeArguments.free(); Efficy.closeContext(editHandle); }

varArrayOf(values)

Constructs a variant array of values.

Parameter Type Default value Description
values array of variant The values.
Return
variant
Usage
var varArray = varArrayOf(['one', 'two']);
var dstMemberExists = locateByKeys(dsDstMembers, 'K_USER;K_SKILL', varArrayOf([kUser, kSkill]));

varIsArray(a)

Tests if a variant contains an array.

Parameter Type Default value Description
a variant The variant value.
Return
boolean
Usage
if (varIsArray(v)) { ... }

DateUtils reference

Collection of methods allowing to perform conversions and other operation on date and time values. Those methods are available in the global scripting context as-is, without the "Efficy." prefix.

Methods

businessDaysBetween(date1, date2)

Introduced in Efficy 11.1 Returns the number of week days (Monday to Friday) between two dates.

Parameter Type Default value Description
date1 TDateTime The first date.
date2 TDateTime The second date.
Return
integer
Usage
var slaDays = businessDaysBetween(startDateTime, endDateTime);

convertDateTimeTzFromTo(value, fromTimeZone, toTimeZone)

Introduced in Efficy 11.1 Converts the provided DateTime from one to another time zone.

Parameter Type Default value Description
value TDateTime The DateTime to convert.
fromTimeZone integer The origin time zone.
toTimeZone integer The destination time zone.
Return
TDateTime

convertLocalDateTimeToUtc(value)

Introduced in Efficy 11.1 Converts the provided DateTime from a local value to Coordinated Universal Time.

Parameter Type Default value Description
value TDateTime The DateTime to convert.
Return
TDateTime

convertUtcToLocalDateTime(value)

Introduced in Efficy 11.1 Converts the provided DateTime from Coordinated Universal Time to a local value.

Parameter Type Default value Description
value TDateTime The DateTime to convert.
Return
TDateTime

dateTimeInRange(value, startDateTime, endDateTime, inclusive)

Introduced in Efficy 11.1 Checks if the provided DateTime is in the range between two dates. startDateTime must be before endDateTime.

Parameter Type Default value Description
value TDateTime The DateTime to check.
startDateTime TDateTime The start DateTime of the range.
endDateTime TDateTime The end DateTime of the range.
inclusive [Opt] boolean True If true, the limit dates are included in the check, otherwise they are excluded.
Return
boolean

dateTimeToIso8601(value, inputIsUtc)

Introduced in Efficy 11.2 Converts a specified TDateTime value into an ISO-8601 date-and-time value (ex: 2019-02-23 or 2008-09-15T15:53:00+05:00)
If the TDateTime is a date only (time is 00:00:00), the output will be omitting the time portion.

Parameter Type Default value Description
value TDateTime The DateTime value.
inputIsUtc [Opt] boolean True Specify if the source DateTime is in UTC. If not, it will first be converted to UTC, then to ISO-8601 format.
Return
string

dateTimeToIso8601Full(value, inputIsUtc)

Introduced in Efficy 11.2 Converts a specified TDateTime value into an ISO-8601 date-and-time value (ex: 2008-09-15T15:53:00+05:00)
The output will always use the full format, even if the TDateTime is a date only (time is 00:00:00)

Parameter Type Default value Description
value TDateTime The DateTime value.
inputIsUtc [Opt] boolean True Specify if the source DateTime is in UTC. If not, it will first be converted to UTC, then to ISO-8601 format.
Return
string

dateTimeToStr(dateTime)

Converts a DateTime into a string.

Parameter Type Default value Description
dateTime TDateTime The date to be converted.
Return
string

dateTimeToStr2(dateTime, settings)

Introduced in Efficy 11.1 Converts a DateTime into a string using a set of custom regional format settings.

Parameter Type Default value Description
dateTime TDateTime The date to be converted.
settings TFormatSettings The FormatSettings record specifying the regional settings.
Return
string

dateTimeToUnix(value, inputIsUtc)

Introduced in Efficy 11.1 Converts a specified TDateTime value into a Unix/Linux-style date-and-time value.

Parameter Type Default value Description
value TDateTime The DateTime value.
inputIsUtc [Opt] boolean True Specify if the source DateTime is in UTC. If not, it will first be converted to UTC, then to Unix format.
Return
integer

dateToStr(dateTime)

Converts the date part of a DateTime into a string.

Parameter Type Default value Description
dateTime TDateTime The date to be converted.
Return
string

dayOfTheMonth(value)

Introduced in Efficy 11.1 Returns the day of the month represented by a TDateTime value.
The return value range is 1 to 31.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
word

dayOfTheWeek(value)

Introduced in Efficy 11.1 Returns the day of the week represented by a TDateTime value in an ISO8601 compliant manner (Monday is the first day of the week).
The return value range is 1 (Monday) to 7 (Sunday).

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
word

daysBetween(date1, date2)

Introduced in Efficy 11.1 Returns the number of whole days between two specified TDateTime values.

Parameter Type Default value Description
date1 TDateTime The first date.
date2 TDateTime The second date.
Return
integer

daysInMonth(value)

Introduced in Efficy 11.1 Returns the number of days in the month of a specified TDateTime value.
The return value range is 1 to 31.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
word

daysInYear(value)

Introduced in Efficy 11.1 Returns the number of days in the year of a specified TDateTime value.
The return value range is 365 to 366.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
word

endOfTheDay(value)

Introduced in Efficy 11.1 Returns a TDateTime that represents the last millisecond of the day identified by a specified TDateTime (23:59:59.999 the same day).

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
TDateTime

endOfTheMonth(value)

Introduced in Efficy 11.1 Returns a TDateTime that represents the last millisecond of the last day of the month identified by a specified TDateTime.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
TDateTime

endOfTheWeek(value)

Introduced in Efficy 11.1 Returns a TDateTime that represents the last millisecond of the last day of the week identified by a specified TDateTime in an ISO8601 compliant manner (Monday is the first day of the week).

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
TDateTime

formatDateTime(format, dateTime)

Converts a DateTime into a string according to the given format.

Parameter Type Default value Description
format string The format to be used.
dateTime TDateTime The date to be converted.
Return
string

Available Format tokens are:

d : Displays the day as a number without a leading zero (1-31).
dd : Displays the day as a number with a leading zero (01-31).
ddd : Displays the day as an abbreviation (Sun-Sat) using the strings given by ShortDayNames
dddd : Displays the day as a full name (Sunday-Saturday) using the strings given by LongDayNames.
ddddd : Displays the date using the format given by ShortDateFormat.
dddddd : Displays the date using the format given by LongDateFormat.
m : Displays the month as a number without a leading zero (1-12). If the m specifier immediately follows an h or hh specifier, the minute rather than the month is displayed.
mm : Displays the month as a number with a leading zero (01-12). If the mm specifier immediately follows an h or hh specifier, the minute rather than the month is displayed.
mmm : Displays the month as an abbreviation (Jan-Dec) using the strings given by the ShortMonthNames global variable.
mmmm : Displays the month as a full name (January-December) using the strings given by LongMonthNames.
yy : Displays the year as a two-digit number (00-99).
yyyy : Displays the year as a four-digit number (0000-9999).
h : Displays the hour without a leading zero (0-23).
hh : Displays the hour with a leading zero (00-23).
n : Displays the minute without a leading zero (0-59).
nn : Displays the minute with a leading zero (00-59).
s : Displays the second without a leading zero (0-59).
ss : Displays the second with a leading zero (00-59).
z : Displays the millisecond without a leading zero (0-999).
zzz : Displays the millisecond with a leading zero (000-999).
t : Displays the time using the format given by the ShortTimeFormat global variable.
tt : Displays the time using the format given by the LongTimeFormat global variable.
"/" : Displays the date separator character given by the DateSeparator global variable.
":" : Displays the time separator character given by the TimeSeparator global variable.
'xx'/"xx" : Characters enclosed in single or double quotation marks are displayed as such, and do not affect formatting.

formatDateTime2(format, dateTime, settings)

Introduced in Efficy 11.1 Converts a DateTime into a string according to the given format using a set of custom regional format settings.

Parameter Type Default value Description
format string The format to be used.
dateTime TDateTime The date to be converted.
settings TFormatSettings The FormatSettings record specifying the regional settings.
Return
string

hourOfTheDay(value)

Introduced in Efficy 11.1 Returns the hour of the day represented by a TDateTime value.
The return value range is 0 to 23.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
word

hoursBetween(date1, date2)

Introduced in Efficy 11.1 Returns the number of whole hours between two specified TDateTime values. This method only counts entire hours.
The return value is always positive.

Parameter Type Default value Description
date1 TDateTime The first date.
date2 TDateTime The second date.
Return
integer

incBusinessDay(value, numberOfDays)

Introduced in Efficy 11.1 Adds a number of days to a specified TDateTime value, skipping Saturdays and Sundays and keeping the time part intact.
The return value is always a week day.

Parameter Type Default value Description
value TDateTime The DateTime value.
numberOfDays [Opt] cardinal 1 The number of days to add.
Return
TDateTime

incDay(value, numberOfDays)

Introduced in Efficy 11.1 Returns a date shifted by a specified number of days. The time of day is copied to the result.

Parameter Type Default value Description
value TDateTime The DateTime value.
numberOfDays [Opt] integer 1 The number of days to shift by. This number can be negative, to return a date N days prior.
Return
TDateTime

incHour(value, numberOfHours)

Introduced in Efficy 11.1 Returns a DateTime value shifted by a specified number of hours.

Parameter Type Default value Description
value TDateTime The DateTime value.
numberOfHours [Opt] integer 1 The number of hours to shift by. This number can be negative, to return a date N hours prior.
Return
TDateTime

incMilliSecond(value, numberOfMilliSeconds)

Introduced in Efficy 11.1 Returns a DateTime value shifted by a specified number of milliseconds.

Parameter Type Default value Description
value TDateTime The DateTime value.
numberOfMilliSeconds [Opt] integer 1 The number of milliseconds to shift by. This number can be negative, to return a date N milliseconds prior.
Return
TDateTime

incMinute(value, numberOfMinutes)

Introduced in Efficy 11.1 Returns a DateTime value shifted by a specified number of minutes.

Parameter Type Default value Description
value TDateTime The DateTime value.
numberOfMinutes [Opt] integer 1 The number of minutes to shift by. This number can be negative, to return a date N minutes prior.
Return
TDateTime

incMonth(dateTime, numberOfMonths)

Introduced in Efficy 11.1 Returns a DateTime value shifted by a specified number of months.

Parameter Type Default value Description
dateTime TDateTime The DateTime value.
numberOfMonths [Opt] integer 1 The number of months to shift by. This number can be negative, to return a date N months prior.
Return
TDateTime

incSecond(value, numberOfSeconds)

Introduced in Efficy 11.1 Returns a DateTime value shifted by a specified number of seconds.

Parameter Type Default value Description
value TDateTime The DateTime value.
numberOfSeconds [Opt] integer 1 The number of seconds to shift by. This number can be negative, to return a date N seconds prior.
Return
TDateTime

incWeek(value, numberOfWeeks)

Introduced in Efficy 11.1 Returns a DateTime value shifted by a specified number of weeks. The time of day is copied to the result.

Parameter Type Default value Description
value TDateTime The DateTime value.
numberOfWeeks [Opt] integer 1 The number of weeks to shift by. This number can be negative, to return a date N weeks prior.
Return
TDateTime

incYear(value, numberOfYears)

Introduced in Efficy 11.1 Returns a DateTime value shifted by a specified number of years. The time of day is copied to the result.

Parameter Type Default value Description
value TDateTime The DateTime value.
numberOfYears [Opt] integer 1 The number of years to shift by. This number can be negative, to return a date N years prior.
Return
TDateTime

isBusinessDay(value)

Introduced in Efficy 11.1 Indicates whether the specified DateTime value occurs on a business day (week day).
Returns false if it occurs on a Saturday or Sundays.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
boolean

isEmptyDate(value, checkAll)

Introduced in Efficy 11.2 Indicates whether the specified DateTime represents an empty date value (represented by the Delphi zero date 30 December 1899).

Parameter Type Default value Description
value string The DateTime value.
checkAll [Opt] boolean False If true, will also check if the provided value equals the SQL zero date (1st January 1900) or the Unix Epoch zero date (1st January 1970).
Return
boolean

iso8601ToDateTime(value, returnUtc)

Introduced in Efficy 11.2 Converts an ISO-8601 date-and-time value (ex: 2008-09-15T15:53:00+05:00) to a TDateTime value.

Parameter Type Default value Description
value string The DateTime value.
returnUtc [Opt] boolean True If true, the returned DateTime will be converted to UTC.
Return
TDateTime

isSameDay(date1, date2)

Introduced in Efficy 11.1 Indicates whether a specified TDateTime value occurs on the same day as a criterion date. The time portions of the two values can differ.

Parameter Type Default value Description
date1 TDateTime The specified DateTime.
date2 TDateTime The criterion DateTime.
Return
boolean

isToday(value)

Introduced in Efficy 11.1 Indicates whether a specified TDateTime value occurs on the current date.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
boolean

isWeekendDay(value)

Introduced in Efficy 11.1 Indicates whether a specified TDateTime value occurs on a Saturday or Sunday.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
boolean

milliSecondsBetween(date1, date2)

Introduced in Efficy 11.1 Returns the number of milliseconds between two specified TDateTime values.

Parameter Type Default value Description
date1 TDateTime The first date.
date2 TDateTime The second date.
Return
integer

minuteOfTheHour(value)

Introduced in Efficy 11.1 Returns the number of minutes between a specified TDateTime value and the beginning of the same hour.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
word

minutesBetween(date1, date2)

Introduced in Efficy 11.1 Returns the number of minutes between two specified TDateTime values.

Parameter Type Default value Description
date1 TDateTime The first date.
date2 TDateTime The second date.
Return
integer

monthOfTheYear(value)

Introduced in Efficy 11.1 Returns the month of the year represented by a TDateTime value.
The return value range is 1 to 12.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
word

monthsBetween(date1, date2)

Introduced in Efficy 11.1 Returns the approximate number of months between two specified TDateTime values.
Because months are not all the same length, the returned value is an approximation based on an assumption of 30.4375 days per month. Fractional months are not counted.

Parameter Type Default value Description
date1 TDateTime The first date.
date2 TDateTime The second date.
Return
integer

now()

Introduced in Efficy 11.1 Returns the current date and time, accurate to the nearest second.

Return
TDateTime

secondsBetween(date1, date2)

Introduced in Efficy 11.1 Returns the number of seconds between two specified TDateTime values.

Parameter Type Default value Description
date1 TDateTime The first date.
date2 TDateTime The second date.
Return
integer

standardDateTimeToStr(value)

Introduced in Efficy 11.1 Converts a DateTime into a string containing the DateTime in the standard database format "YYYY/MM/DD hh:nn:ss".

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
string

standardStrToDateTime(value)

Introduced in Efficy 11.1 Converts a string containing a DateTime in the standard database format "YYYY/MM/DD hh:nn:ss" into a DateTime.

Parameter Type Default value Description
value string The string value.
Return
TDateTime

startOfTheDay(value)

Introduced in Efficy 11.1 Returns a TDateTime that represents 00:00:00 on the day identified by a specified TDateTime.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
TDateTime

startOfTheMonth(value)

Introduced in Efficy 11.1 Returns a TDateTime that represents 00:00:00 on the first day of the month identified by a specified TDateTime.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
TDateTime

startOfTheWeek(value)

Introduced in Efficy 11.1 Returns a TDateTime that represents 00:00:00 on the first day of the week identified by a specified TDateTime in an ISO8601 compliant manner (Monday is the first day of the week).

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
TDateTime

strToDateTime(s)

Converts a string into a DateTime.

Parameter Type Default value Description
s string The string to be converted.
Return
TDateTime

strToDateTime2(s, settings)

Introduced in Efficy 11.1 Converts a string into a DateTime using a set of custom regional format settings.

Parameter Type Default value Description
s string The string to be converted.
settings TFormatSettings The FormatSettings record specifying the regional settings.
Return
TDateTime

strToDateTimeDef(s, default)

Tries to convert a string into a DateTime value.
If the conversion fails, the default value is returned.

Parameter Type Default value Description
s string The string to be converted.
default TDateTime The default value.
Return
TDateTime

strToDateTimeDef2(s, default, settings)

Introduced in Efficy 11.1 Tries to convert a string into a DateTime value using a set of custom regional format settings.
If the conversion fails, the default value is returned.

Parameter Type Default value Description
s string The string to be converted.
default TDateTime The default value.
settings TFormatSettings The FormatSettings record specifying the regional settings.
Return
TDateTime

timeToStr(dateTime)

Converts the time part of a DateTime into a string.

Parameter Type Default value Description
dateTime TDateTime The time to be converted.
Return
string

toBusinessDay(value)

Introduced in Efficy 11.1 Returns the specified DateTime value converted to a business day.
When the specified DateTime occurs on a Saturday or Sunday, returns the following Monday. When it occurs on a week day, return the DateTime unchanged.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
TDateTime

today()

♫ is gonna be the day that they're gonna throw it back to you ♫
Introduced in Efficy 11.1
Returns a TDateTime value that represents the current date.

Return
TDateTime

tomorrow()

♫ and tonight, we can rock all day, we can roll all night ♫
Introduced in Efficy 11.1
Returns a TDateTime value that represents the following day.

Return
TDateTime

unixToDateTime(value, returnUtc)

Introduced in Efficy 11.1 Converts a Unix/Linux style date-and-time value to a TDateTime value.

Parameter Type Default value Description
value integer The DateTime value.
returnUtc [Opt] boolean True If true, the returned DateTime will be converted to UTC.
Return
TDateTime

utcNow()

Introduced in Efficy 11.1 Returns the current date and time in Coordinated Universal Time, accurate to the nearest second.

Return
TDateTime

weekOfTheYear(value)

Introduced in Efficy 11.1 Returns the week of the year represented by a TDateTime value in an ISO8601 compliant manner (Monday is the first day of the week).
The return value range is 1 to 53.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
word

The first week of a year is defined as the first week with four or more days in that year. This means that, if the first calendar day of the year is a Friday, Saturday, or Sunday, then for the first three, two, or one days of the calendar year, WeekOfTheYear returns the last week of the previous year. Similarly, if the last calendar day of the year is a Monday, Tuesday, or Wednesday, then for the last one, two, or three days of the calendar year, WeekOfTheYear returns 1 (the first week of the next calendar year).

weeksBetween(date1, date2)

Introduced in Efficy 11.1 Returns the number of whole weeks between two specified TDateTime values.

Parameter Type Default value Description
date1 TDateTime The first date.
date2 TDateTime The second date.
Return
integer

weeksInYear(value)

Introduced in Efficy 11.1 Returns the number of weeks in the year of a specified TDateTime value in an ISO8601 compliant manner (The first week that has four or more days in the year).
The return value range is 52 to 53.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
word

yearOf(value)

Introduced in Efficy 11.1 Returns the year of the specified TDateTime value.
The return value range is 1 to 9999.

Parameter Type Default value Description
value TDateTime The DateTime value.
Return
word

yearsBetween(date1, date2)

Introduced in Efficy 11.1 Returns the approximate number of years between two specified TDateTime values.

Parameter Type Default value Description
date1 TDateTime The first date.
date2 TDateTime The second date.
Return
integer

Because years are not all the same length (leap years), YearsBetween returns an approximation based on an assumption of 365.25 days per year. Fractional years are not counted. Thus, for example, it returns the difference between January 1 and December 31 as 0 on non-leap years and 1 on leap years.

yesterday()

♫ All my troubles seemed so far away ♫
Introduced in Efficy 11.1
Returns a TDateTime value that represents the preceding day.

Return
TDateTime
Top ▲