The examples below will get you started using the JavaScript API to create enhanced HTML pages and visualizations of data.
Note that API calls are case sensitive. Making a call like LabKey.query.selectRows({ ... will not work. You need to capitalize the word LABKEY as in LABKEY.Query.selectRows({ ...

Show a QueryWebPart

Displays a query in the home/ProjectX folder. The containerFilter property being set to "allFolders" broadens the scope of the query to pull data from the entire site.

<div id='queryDiv1'/>
<script type="text/javascript">
var qwp1 = new LABKEY.QueryWebPart({
renderTo: 'queryDiv1',
title: 'Some Query',
schemaName: 'someSchema',
queryName: 'someQuery',
containerPath: 'home/ProjectX',
containerFilter: LABKEY.Query.containerFilter.allFolders,
buttonBar: {
position: 'top',
},
maxRows: 25
});
</script>

Learn more about the available parameters for QueryWebPart in the JavaScript API documentation here. Of note:

  • "buttonBarPosition" has been deprecated in favor of buttonBar with syntax as shown in the above for specifying a button bar position.
  • Additional buttons and actions can be defined in the buttonBar section. Learn more here: Custom Button Bars
  • To hide the button bar completely, you must set buttonBar.position to 'none' and also set showPagination to false.
  • By default, checkboxes will be visible to users who have permission to edit the query itself.
  • To hide the checkboxes entirely, all of the following parameters must be set to false:
    • showRecordSelectors, showDeleteButton, showExportButtons

Files Web Part - Named File Set

Displays the named file set 'store1' as a Files web part.

<div id="fileDiv"></div>

<script type="text/javascript">

// Displays the named file set 'store1'.
var wp1 = new LABKEY.WebPart({
title: 'File Store #1',
partName: 'Files',
partConfig: {fileSet: 'store1'},
renderTo: 'fileDiv'
});
wp1.render();

</script>

Insert a Wiki Web Part

Note that the Web Part Configuration Properties covers the configuration properties that can be set for various types of web parts inserted into a wiki page.

<div id='myDiv'>
<script type="text/javascript">
var webPart = new LABKEY.WebPart({partName: 'Wiki',
renderTo: 'myDiv',
partConfig: {name: 'home'}
});
webPart.render();
</script>

Retrieve the Rows in a List

This script retrieves all the rows in a user-created list named "People." Please see @labkey/api / Query / selectRowsOptions for detailed information on the parameters used in this script.

<script type="text/javascript">
function onFailure(errorInfo, options, responseObj)
{
if(errorInfo && errorInfo.exception)
alert("Failure: " + errorInfo.exception);
else
alert("Failure: " + responseObj.statusText);
}

function onSuccess(data)
{
alert("Success! " + data.rowCount + " rows returned.");
}

LABKEY.Query.selectRows({
schemaName: 'lists',
queryName: 'People',
columns: ['Name', 'Age'],
success: onSuccess,
error: onFailure,
});
</script>

The success and failure callbacks defined in this example illustrate how you might manage the fact that JavaScript requests to LabKey server use AJAX and are asynchronous. You don't get results immediately upon calling a function, but instead at some point in the future, and at that point the success or failure callbacks are run. If you would like to ensure a certain behavior waits for completion, you could place it inside the success callback function as in this example:

var someValue = 'Test value'; 
LABKEY.Query.selectRows({
schemaName: 'lists',
queryName: 'People',
columns: ['Name', 'Age'],
success: function (data)
{
alert("Success! " + data.rowCount + " rows returned and value is " + someValue);
},
failure: onFailure
});

Display a Grid

Use LABKEY.QueryWebPart to customize many aspects of how a grid is displayed.

Update Issues via the API

Insert New Issue

The following Ajax request will insert a new issue in the issue tracker.

  • The action property supports these values: insert, update, resolve, close, and reopen.
  • issueDefId is required when inserting.
  • issueDefName can be used when updating.
var formData = new FormData();
var issues = [];
issues.push({
assignedTo : 1016,
title : 'My New Issue',
comment : 'To repro this bug, do the following...',
notifyList : 'developerx@labkey.com',
priority : 2,
issueDefId : 20,
action : 'insert'
});
formData.append('issues', JSON.stringify(issues));

LABKEY.Ajax.request({
url: LABKEY.ActionURL.buildURL('issues', 'issues.api'),
method: 'POST',
form: formData,
success: LABKEY.Utils.getCallbackWrapper(function(response){
}),
failure: LABKEY.Utils.getCallbackWrapper(function(response){
})
});

Update an Issue

var formData = new FormData();
var issues = [];
issues.push({
assignedTo : 1016,
comment : 'I am not able to repro this bug.',
notifyList : 'developerx@labkey.com',
//issueDefId: 20,
issueDefName: 'mybugs',
issueId : 25,
action : 'update'
});
formData.append('issues', JSON.stringify(issues));

LABKEY.Ajax.request({
url: LABKEY.ActionURL.buildURL('issues', 'issues.api'),
method: 'POST',
form: formData,
success: LABKEY.Utils.getCallbackWrapper(function(response){
}),
failure: LABKEY.Utils.getCallbackWrapper(function(response){
})
});

Add Multiple Users to the Notify List

In the above examples, we add a single user to the notifyList by email address. To add multiple users simultaneously, use their userIDs in a semi-colon delimited string:

notifyList  : '1016;1005;1017',

Submit an Attached File via the Issues API

<script>
function doInsert() {
var file = document.getElementById('attachment-file').files[0];
var file2 = document.getElementById('attachment-file2').files[0];

var issues = [{
action : 'insert',
issueDefName : 'issues',
priority : 3,
title : 'test issue 1',
comment : 'this is a new issue',
attachment : 'attachment.file',
type : 'Todo',
assignedTo : 1011
},{
action : 'insert',
issueDefName : 'issues',
priority : 2,
title : 'test issue 2',
attachment : 'attachment.file2',
assignedTo : 1011
}];

var formData = new FormData();

formData.append("issues", JSON.stringify(issues));
formData.append('attachment.file', file);
formData.append('attachment.file2', file2);

LABKEY.Ajax.request({
method: 'POST',
url: LABKEY.ActionURL.buildURL("issues", "issues.api"),
form: formData
});
}
</script>

<input type="file" id="attachment-file">
<input type="file" id="attachment-file2">
<a href="#" onclick="doInsert()">Insert Issues</a>

Close an Issue via API

var formData = new FormData();
var issues = [];
issues.push({
assignedTo : 0,
comment : 'Looks good, closing.',
issueDefName: 'mybugs',
issueId : 25,
action : 'close'
});
formData.append('issues', JSON.stringify(issues));

LABKEY.Ajax.request({
url: LABKEY.ActionURL.buildURL('issues', 'issues.api'),
method: 'POST',
form: formData,
success: LABKEY.Utils.getCallbackWrapper(function(response){
}),
failure: LABKEY.Utils.getCallbackWrapper(function(response){
})
});

Create a Dataset with a 3rd Key Field

LABKEY.Domain.create({
kind: "StudyDatasetDate",
domainDesign: {
name: "Mood",
description: "Morning and evening mood scores",
fields: [{
name: "moodScore",
rangeURI: "int"
},{
name: "dayOrNight",
rangeURI: "string"
}]
},
options: {
keyPropertyName: "dayOrNight",
isManagedField: false
}
});

Create a Sample Type with Two Parent Alias Fields

// Create a Sample Type with two Parent Aliases
LABKEY.Domain.create({
kind: "SampleType",
domainDesign: {
name: "Vials",
description: "main vial collection",
fields: [{
name: "Name",
rangeURI: "string"
},{
name: "Volume",
rangeURI: "int"
},{
name: "Volume_units",
rangeURI: "string"
}]
},
options: {
name: "test",
nameExpression: "S-${genId}",
importAliases: {parentVial: "materialInputs/Vials", parentVials2: "materialInputs/Vials"}
}
});

Create a List with Indices

Use the LABKEY.Domain.create() API to create a list with the index (or indices) needed. Only a unique field may be used as an index. Shown here, a unique index on the "tubeCode" column that is not the primary key.

LABKEY.Domain.create({
kind: "VarList", //creates a list with the primary key being a text field
domainDesign: {
name: "storageList", //list name
fields: [{
name: "uniqueLocation",
rangeURI: "string"
},{
name: "boxCode",
rangeURI: "string"
},{
name: "column",
rangeURI: "string"
},{
name: "row",
rangeURI: "string"
},{
name: "tubeCode", // this is the other column we want to index; values are unique
rangeURI: "string"
}],
indices: [{
columnNames: [ "tubeCode" ], //put your column with uniqueness constraint here
unique: true
}],
},
options: {
keyName: "uniqueLocation" //put your primary key name here
}

});

Other JavaScript API Resources

Discussion

Was this content helpful?

Log in or register an account to provide feedback


previousnext
 
expand all collapse all