Skip to Main Content

Interface: model

QuickNav

model

A model holds data in memory for use by the UI layer. It corresponds to the view-model in the Model-View-ViewModel (MVVM) pattern. The UI can both read and write the data. A model can notify interested parties (subscribers) when the data changes. The data comes (is fetched) from the server and updates can be written back (saved) to the server.

Models are created and managed with functions of the apex.model namespace. A model is uniquely identified by a model.ModelId, which is a string name and optional string instance id.

A model can hold data of different shapes. They are:

  • table: The data is an ordered collection of records. In database or UI terms the record might be called a row. See model.Record.
  • tree: The data is a single root record and each record including the root can have an ordered collection of any number of child records. When dealing with trees it is common to call the records nodes. See model.Node.
  • record: The data is a single record. In some cases this is treated as a collection of one.

Each record can have any number of named fields. See model.Record. All records in the collection must have the same set of fields although the value of some fields may be null. In database or UI terms the fields might be called columns. The actual storage of a record could be an object or an array. If records are objects then the fields of the record are the properties of the object. If the records are arrays the fields of the record are elements of the array and the model.FieldMeta index property is used to map from the field name to the record array index.

The model has very few restrictions on the values of fields. However typically when the model data is backing APEX items or HTML form controls the values will all be strings. The model optionally uses the following fields for specific purposes:

  • identity: A string value that uniquely identifies the record. There can be multiple identity fields. Required for editable models. See apex.model.create option identityField.
  • meta: An object with additional metadata about the record. See apex.model.create option metaField.
  • children: (tree shape only) An array of the child records (nodes). See apex.model.create option childrenField.
  • parent identity: (tree shape only) A string value that identifies the parent record (node) of this record (node). Required for editable tree shaped models. See apex.model.create option parentIdentityField.

Another special case is for field values that have a display value in addition to their intrinsic value. These composite values have the form: { d: "display value", v: value } When comparing values during model#setValue only the value is considered not the display value. Also when the changes are saved to the server just the value is included without being wrapped in an object. Other special fields such as identity or parent etc. cannot have this structure.

Aggregations:

Aggregations are just records that the server includes in order among all the other records marked with meta data property agg: true. The aggregate record has most fields empty except for the aggregate fields that contain the aggregate value.

Ajax Messages:

This section defines the JSON content of the Ajax requests the model sends to the server and the responses it expects back. This information is useful when creating a plug-in that uses the model.

All the requests and responses use the regions array structure shown in apex.server.plugin. The top level object contains a property called "regions" which is an array of region objects. Each region object, in both the request and response, contains the "id" (region id) and "ajaxIdentifier" associated with the region plug-in. The rest of the region object content depends on the type of request.

{
    "regions": [ {
       "id": region-id-or-static-id,
       "ajaxIdentifier": ajaxIdentifier,
       // model create option regionData is merged here
       // method specific properties go here
    }, ...]
}

Method model#fetch request:

Model shape table:

"fetchData": {
    "firstRow": n, // one based
    "maxRows": n,
    "version": version // model create option version
    // model create option fetchData is merged here
}

Model shape tree or record:

"fetchData": {
    "version": version // model create option version
    // model create option fetchData is merged here
}

Method model#fetch response:

Model shape table:

"fetchedData": {
    "values": [record, ...],
    "firstRow": n, // one based
    "moreData": true/false, // true if there are more records on the server and false otherwise
    "totalRows": n // only required when option hasTotalRecords is true
}

Model shape tree:

"fetchedData": {
    "root": node
}

Model shape record:

"fetchedData": {
    "value": record
}

Method model#fetchRecords request:

"fetchData": {
    "primaryKeys": [key, ...] // a key is { "recordId": stringId, "pk": [identityValue, ...] }
    "version": version // model create option version
    // model create option fetchData is merged here
}

Method model#fetchRecords response:

"fetchedData": {
    "values": [record, ...]
}

Method model#save request:

"saveData": {
    "models": [
        {
            "version": version // model create option version
            "instance": modelInstance, // model instance or null
            "values": [record, ...] // meta column contains "op": i|u|d for operation insert, update, delete
                // Note additional properties in the meta column are not yet formally defined
                // inserted records have identityField values set to "".
            // model create option saveData is merged here
        }, ... // when saving a master model there can be additional detail models
    ]
}

Method model#save response:

"fetchedData": {
    models: [
        {
            "values": [record, ...], // records updated or inserted are returned
        }, ... // when saving a master model there can be additional detail models
    ]
}

Method model#fetchChildNodes request:

"fetchData": {
    "parentId": [identityValue, ...], // an array of identity field values or null
    "version": version // model create option version
    // model create option fetchData is merged here
}

Method model#fetchChildNodes response:

When parentId in the request is null the response contains the whole tree:
"fetchedData": {
    "root": node
}
When parentId is given in the request the response contains an array of child nodes:
"fetchedData": {
    childrenField: [node, ...]
}
Since:
  • 5.1

Example

Models are typically used by advanced UI controls (views) to display, interact with, and edit data. The following is a high level sketch of how a UI control might use a table shape model.

// The widget can create the model during widget initialization
this.model = apex.model.create( modelName, options, initialData, ... );

// Or it can be configured with the name of a model that already exists and get a reference to it
this.model = apex.model.get( modelName );

// In either case subscribe to model notifications
this.modelViewId = this.model.subscribe( {
    onChange: modelNotificationFunction,
} );

// During create or when the widget is refreshed it should render data from the model
// this.pageOffset starts at 0. When the user changes pages or additional page data is needed run this code again
// the model fetches more data from the server as needed.
var count = 0;
this.model.forEachInPage( this.pageOffset, pageSize, function( record, index, id ) {
    if ( record ) {
        // render the row record
        count += 1;
    }
    if ( count === pageSize || !record ) {
        // done rendering this page of records
    }
} );

// When settings change that affect the data such as changing the sort order or applying a filter
// the new sort order or filter information can be communicated to the server in the model fetchData or
// regionData option or it can be sent in a separate Ajax request.
this.model.clearData();

// Clearing the data will result in a refresh notification. The modelNotificationFunction should
this.pageOffset = 0;
// call the above forEachInPage code to fetch and render the new data.

// When the widget is destroyed it needs to release the model
this.model.unSubscribe( this.modelViewId );
this.model.release( modelName );

Notifications

addData

Sent when data has been added to the model from the server.
Properties:
Name Type Description
changeType string "addData"
change object
Properties
Name Type Description
parentNode model.Node Only for tree shape models. This is the parent node the data was added to or null if root.
offset number Index into the client model data. 0 for tree or record shape models
count number Number of records added to the model. For a tree shape model this is the number of nodes added to the parent or 1 if root. For table shape models the count could be less than the number of records returned by the server if some records were merged (replaced) existing record with same identity.
replacedIds array Only for table shape models. Array of record ids that were replaced. This happens when a record returned by the server is already in the model. In this case the existing record is replaced and the record id is added to this list.

clearChanges

Sent when the model has been saved (or model#clearChanges called) after all metadata related to changes has been cleared.
Properties:
Name Type Description
changeType string "clearChanges"
change object
Properties
Name Type Description
deletedIds array Record ids for deleted records.
changedIds array Record ids for records that had been updated or inserted.

copy

Sent when one or more records are copied.
Properties:
Name Type Description
changeType string "copy"
change object
Properties
Name Type Description
records array The records that were copied.
recordIds array The ids of the records that were copied. The ith item in this array corresponds to the ith item in the records array.
insertAfterId string The id of the record that these new records were inserted after or null if inserted at the beginning.

delete

Sent when one or more records are deleted.
Properties:
Name Type Description
changeType string "delete"
change object
Properties
Name Type Description
records array The records that were deleted.
recordIds array The ids of the records that were deleted. The ith item in this array corresponds to the ith item in the records array.

insert

Sent when a record is inserted into the model.
Properties:
Name Type Description
changeType string "insert"
change object
Properties
Name Type Description
record model.Record The inserted record.
recordId string The id of the inserted record.
insertAfterId string The id of the record that this new record was inserted after or null if inserted at the beginning.

metaChange

Sent when metadata has changed. The record field values have not changed but the record or field metadata has changed. Typically this is the result of validation errors. If external code changes the metadata it must call model#metadataChanged (which sends this notification) to let other views know about the change.
Properties:
Name Type Description
changeType string "metaChange"
change object
Properties
Name Type Description
record model.Record The record that changed.
field string The name of the field that changed or null if field metadata didn't change.
property string The name of the metadata property that changed or null if not specified. If multiple properties changed this can be a comma separated list.

move

Sent when one or more records are moved.
Properties:
Name Type Description
changeType string "move"
change object
Properties
Name Type Description
records array The records that were moved.
recordIds array The ids of the records that were moved. The ith item in this array corresponds to the ith item in the records array.
insertAfterId: object The id of the record that these new records were inserted after or null if inserted at the beginning.

refresh

Sent when the model has been given new data or there is a change in data on the server that the model should now go get. In either case the previous data in the model is gone/changed so any views showing the model data should re-render their views.
Properties:
Name Type Description
changeType string "refresh"
change object Empty object

refreshRecords

Sent when specific records in the model have changed. This happens when the model is saved if the server returns updated records or when model#fetchRecords is called. Both the record field values and metadata may have changed. The view layer should render the new record including taking into consideration any metadata and replace the existing view of the record.
Properties:
Name Type Description
changeType string "refreshRecords"
change object
Properties
Name Type Description
records array Records that have been updated. Note for inserted items this includes the new id
recordIds array Record ids that have been changed. Note for inserted items the previous (old) id is given. The ith item in this array corresponds to the ith item in the records array.
newIds object For inserted records this is a map from the previous (old) id to the new id.

revert

Sent when record changes are reverted.
Properties:
Name Type Description
changeType string "revert"
change object
Properties
Name Type Description
records array The records that were reverted.
recordIds array The ids of the records that were reverted. The ith item in this array corresponds to the ith item in the records array.
newIds object For records where the identity was changed and is now reverted this is a map from the previous (old) id to the new (reverted) id.

set

Sent when a field value of a record is changed.
Properties:
Name Type Description
changeType string "set"
change object
Properties
Name Type Description
oldValue * The previous value of the field.
oldIdentity string If the identity changed this is the previous identity value.
recordId string The id of the record that changed.
record model.Record The record that changed.
field string The name of the field that changed.

Methods

addChangesToSaveRequest(pRequestData)

Rarely needed. Only useful if making your own call to the server. See model#save, apex.model.addChangesToSaveRequest, and apex.model.save.
Parameters:
Name Type Description
pRequestData object An empty or partially filled in object to which changes for this model will be added.

allowAdd(pParentRecordopt, pAddActionopt, pRecordsToAddopt) → {boolean}

Determine if any record or one or more specific records can be added to the table collection or, for trees, the parent record's children collection.

For any record or one or more specific records to be addable:

  • the shape must not be record and
  • if the shape is a tree the parent record is required and must have a children collection
  • the model must have the editable option set to true and
  • if the shape is tree the type of the parent record must allow add or
  • if the shape is table or the parent record has no type or doesn't specify if it allows add the default type must allow add
  • and if the model specifies an additional check callback function it must allow or deny the add
  • then, for tree shape only, if adding is allowed and pRecordsToAdd is given then check if the type of each record to add is a valid child type for the parent using validChildren type property.
Parameters:
Name Type Attributes Description
pParentRecord model.Record <optional>
The parent record to add children to if the shape is tree, null if the shape is table.
pAddAction string <optional>
Specifies how/why the records are to be added. Standard values are "new", "move", or "copy".
pRecordsToAdd Array.<model.Record> <optional>
An array of the records to be added. Only used for tree shape models.
Returns:
true if add is allowed.
Type
boolean
Example

This example checks if adding is allowed before inserting a record.

if ( myModel.allowAdd() ) {
    myModel.insertNewRecord();
}

allowDelete(pRecord) → {boolean}

Determine if the given record can be deleted.

For a record to be deletable:

  • the shape must not be record and
  • if the shape is a tree the record must not be the root record
  • the model must have the editable option set to true and
  • the type of the record must allow delete or
  • if the record has no type or doesn't specify if it can be deleted the default type must allow delete
  • and if the model specifies an additional check callback function it must allow or deny the delete
Parameters:
Name Type Description
pRecord model.Record The record to check if deleting is allowed.
Returns:
true if the record can be deleted.
Type
boolean
Example

This example checks if deleting is allowed before deleting a record.

if ( myModel.allowDelete( record ) ) {
    myModel.deleteRecords( [record] );
}

allowDrag(pRecord) → {boolean}

Determine if an record can be dragged. Note this is just a check to see if the dragging can start. What is allowed on drop (move, copy etc.) is a separate check.

For a record to be draggable:

  • the shape must not be record and
  • the model must have the editable option set to true and
  • the type of the record must allow drag or
  • if the record has no type or doesn't specify if it can be dragged the default type must allow drag
  • and if the model specifies an additional check callback function it must allow or deny the drag
Parameters:
Name Type Description
pRecord model.Record The record to check if it can be dragged.
Returns:
true if the record can be dragged.
Type
boolean

allowEdit(pRecord) → {boolean}

Determine if the given record can be edited.

For a record to be editable:

  • the model must have the editable option set to true and
  • the type of the record must allow edit or
  • if the record has no type or doesn't specify if it can be edited the default type must allow edit
  • and if the model specifies an additional check callback function it must allow or deny the edit
Parameters:
Name Type Description
pRecord model.Record The record to check if editing is allowed.
Returns:
true if the record can be edited.
Type
boolean
Example

This example checks if editing is allowed before setting a value.

if ( myModel.allowEdit( record ) ) {
    myModel.setValue( record, "NAME", newName );
}

canRevertRecord(pRecord) → {boolean}

Return true if the record exists in the model and has a change that can be reverted (is updated or is deleted). See also model#revertRecords.

Parameters:
Name Type Description
pRecord model.Record The record to check if it can be reverted.
Returns:
true if record has change that can be reverted.
Type
boolean
Example

This example checks if a record can be reverted before reverting it.

if ( myModel.canRevertRecord( record ) ) {
    myModel.revertRecords( [record] );
}

check(pOperation, pRecordopt, pAddActionopt, pRecordsToAddopt) → {boolean}

Low level operation permission checking. Better to use model#allowEdit, model#allowDelete, model#allowAdd, model#allowDrag. The purpose is to determine what kinds of edits are allowed.

If the model is not editable (editable option is false) then no operations are allowed. Also no operations are allowed on deleted records or aggregate records.

Operation checking is based on the type of the record (as determined by the type field) and the type information given to the model in the types option. Type names are strings. The special type name "default" is used to provide a default when records don't have a type or the type of the record doesn't specify a value for the operation. Note: The model types option is not currently documented and may change in the future.

Operations are strings. The standard operation permissions are "canAdd", "canDelete", "canEdit", "canDrag". You can define your own as well.

First the record itself is checked to see if it allows the operation by checking if the record metadata contains the specified permission. Next the type of the record is checked to see if it allows the operation. If the record has no type or the operations for that type didn't specify a value for the operation then the default type is checked to see if it allows the operation. The value of an operation is true or false or a function that returns true or false. The function is called in the context of this model with arguments pRecord, pAddAction, pRecordsToAdd. If the model options includes a check function then it is called with the result so far and all the same arguments as this check function. See model.CheckCallback.

Parameters:
Name Type Attributes Description
pOperation string One of the default checks ("canEdit", "canDelete", "canAdd", "canDrag") or a custom operation.
pRecord model.Record <optional>
The record to check if action is allowed on it.
pAddAction string <optional>
Only used by allowAdd see model#allowAdd for details.
pRecordsToAdd Array.<model.Record> <optional>
Only used by allowAdd see model#allowAdd for details.
Returns:
true if the operation is allowed.
Type
boolean

child(pNode, pIndex) → {model.Node}

Return the child at pIndex of node pNode.

This method must only be used on tree shape models.

Parameters:
Name Type Description
pNode model.Node The node who's ith child is to be returned.
pIndex number The index of the child node.
Returns:
The ith child node.
Type
model.Node
Example

This example loops over the children of a parent node.

var i, node;
for ( i = 0; i < model.childCount( parentNode ); i++ ) {
    node = mode.child( parentNode, i );
    // do something with node
}

childCount(pNode) → {number}

Returns the number of children that node pNode has, or null if the answer is not yet known. A node that has its children lazy loaded may not know how many children it has until they are loaded.

This method must only be used on tree shape models.

Parameters:
Name Type Description
pNode model.Node The node who's children are to be counted.
Returns:
Number of children, 0 if none, or null if not known.
Type
number
Example

This example loops over the children of a parent node.

var i, node;
for ( i = 0; i < model.childCount( parentNode ); i++ ) {
    node = mode.child( parentNode, i );
    // do something with node
}

clearChanges()

This marks the model as not having any changes. All change indications will be removed. If any record deletes are pending they will be removed by this method. This does not revert or undo the changes but rather removes all metadata that is tracking changes. This happens implicitly after the model is saved (See model#save). Use this method if changes are persisted in some other way or the changes should be discarded before refreshing the model.
Fires:
Example

This example clears all the changes of an interactive grid with static id "emp" in response to a Cancel or Abort button being pressed by the user. Use in a Execute JavaScript Code dynamic action. If not for the call to clearChanges before refresh the interactive grid would prompt the user to save changes.

var ig$ = apex.region( "emp" ).widget(),
    view = ig$.interactiveGrid( "getCurrentView" );
if ( view.supports.edit ) {
    // leave edit mode so that the column items will be reinitialized
    ig$.interactiveGrid( "getActions" ).set( "edit", false );
    view.model.clearChanges();
}
apex.region("emp").refresh();

clearData(pNotifyopt)

Remove all data from the model.

Parameters:
Name Type Attributes Description
pNotify boolean <optional>
If false don't send the refresh notification. The default is true to send the refresh notification.
Fires:
Examples

Clear the data for a model. This will typically cause any views to refresh, which results in requesting new data from the model.

myModel.clearData();

See example for apex.model.multipleFetch.

clearSelection()

Unselect all the selected records. See also model#setSelectionState.

This method should only be used by view widgets to persist the view selection state in metadata property sel. Note there is no notification about this metadata change. Listen to the view for selection change events. Also use the view to change the selection.

copyRecords(pRecords, pParentRecordopt, pAfterRecordopt) → {Array.<string>}

Copies the given records and inserts the copies into the collection (table or parent node's children) or, for tree shape only, to a new parent node.

Parameters:
Name Type Attributes Description
pRecords Array.<model.Record> Array of records to copy.
pParentRecord model.Record <optional>
Only used when the shape is tree. This is the parent node to insert the copies into. If null then insert to root.
pAfterRecord model.Record <optional>
The copied records are added after this record or if null at the beginning.
Fires:
Returns:
Array of temp primary keys of inserted records.
Type
Array.<string>
Example

This examples copies the selected records to just after the last selected record.

var keys = model.copyRecords( selectedRecords, null, selectedRecords[ selectedRecords.length - 1 ] );

deleteRecords(pRecords) → {number}

Delete one or more records from a table or tree.

If the onlyMarkForDelete option is true the records are just marked for delete. Records marked for delete will be included in data returned by model#forEach, model#forEachInPage, model#walkTree, etc. and can be found by model#getRecord. They will be deleted once the model#clearChanges method is called explicitly or implicitly after data has been saved successfully.

If the onlyMarkForDelete option is false the records are deleted right away and are no longer part of the model. In either case the deleted records are on the change list so the delete can be persisted.

If pRecords contains records that cannot be found in the collection or finds records that can't be deleted they are ignored and a debug warning is given.

Parameters:
Name Type Description
pRecords Array.<model.Record> An array of records to delete.
Fires:
Returns:
The number of records deleted or marked for delete.
Type
number
Example

This example checks if deleting is allowed before deleting a record.

if ( myModel.allowDelete( record ) ) {
    myModel.deleteRecords( [record] );
}

dragOperations(pRecords) → {object}

Determine what drag operations are allowed for a set of records. Not all views support dragging. Dragging is a view operation. The model provides this method simply to allow type based configuration of available drag operations. Note: The model types option is not currently documented and may change in the future.

Parameters:
Name Type Description
pRecords Array.<model.Record> array of records to determine drag operations for or null when dragging an external record into this model.
Returns:
object with allowed drag operations. The properties are: "normal", "ctrl", "alt", "shift", "meta". The standard values are "move", "copy" or "add". Other values are allowed. The normal property is required. The default is: { normal: "move", ctrl: "copy" } or if pRecords is null { normal: "add" }
Type
object

fetch(pOffsetopt, pCallbackopt, pNoProgressopt) → {promise}

Retrieve model data from the server. Data is requested starting at the given offset (or 0 if offset is not given). Data is fetched in model option pageSize chunks. Can use either the callback argument or the returned promise to determine when the request is complete.

Parameters:
Name Type Attributes Description
pOffset number <optional>
Zero based offset of the data to fetch. Only applies to table shape models. This is rarely needed because table data is automatically fetched as needed when requested via the model#forEachInPage method. Omit this param when not needed.
pCallback function <optional>
A function to call when the request is complete. The callback is passed an Error argument only if there is an error.
pNoProgress boolean <optional>
Set to true to not show progress during the fetch.
Fires:
Returns:
A promise if the fetch is initiated, null if there is already a fetch in progress, and false if pOffset is beyond the end of the data or master record is inserted or deleted. If and only if a promise is returned, pCallback will be called. It receives no arguments when resolved and an Error argument when rejected.
Type
promise

fetchAll(pCallback)

Fetch all the data from the server into the model. This repeatedly calls model#fetch until the server reports there is no more data. This is only for table shape models. Data is fetched in model option pageSize chunks.

Use with caution. Loading too much data onto the client can take a long time and cause the browser to become unresponsive.

Parameters:
Name Type Description
pCallback function function that is called after each fetch completes. It receives an object with properties:
  • offset: the current offset in the model that was just added
  • total: total records in the model (see model#getTotalRecords)
  • done: true if all the data is fetched false otherwise. When true this is the last time the callback is called.
Example

This example fetches all the data before using model#forEach to loop over the records.

model.fetchAll( function( status ) {
    if ( status.done } {
        model.forEach( function( record, index, id ) {
            // do something with each record
        }
    }
} );

fetchChildNodes(pNodeopt, pCallbackopt) → {promise}

Fetch child nodes for node pNode. This method is only used for trees that lazy load data from the sever as needed. If pNode is not given or null the whole tree is loaded from the server.

This is an asynchronous operation. When it completes the pCallback function is called with a status argument. Where status is:

  • > 0 (or true) if 1 or more children were fetched.
  • 0 if the node has 0 children.
  • Error if there was an error fetching the children.

Can use either the callback argument or the returned promise to determine when the request is complete.

Parameters:
Name Type Attributes Description
pNode model.Node <optional>
The node record to fetch children for. If null or omitted fetch the root node.
pCallback function <optional>
callback function that is called after nodes have been fetched or there is an error.
Fires:
Returns:
A promise that receives count of children fetched when resolved and an Error argument when rejected.
Type
promise

fetchRecords(pRecords, pCallbackopt) → {promise}

Fetches fresh data from the server for the given records. The existing records in the model are replaced with the new returned record from the server. The model must have a identityField option defined for this to work. Can use either the callback argument or the returned promise to determine when the request is complete.

Parameters:
Name Type Attributes Description
pRecords model.Record Array of records to be fetched.
pCallback function <optional>
A function to call when the request is complete. The callback is passed an Error argument only if there is an error.
Fires:
Returns:
A promise that receives no arguments when resolved and an Error argument when rejected. If there are no records to fetch then null is returned and pCallback is not called.
Type
promise
Example

This example fetches the selected records from interactive grid with static id "emp". There is often no need know when the Ajax request completes because the view is updated from model notifications.

var model = apex.region( "emp" ).call( "getCurrentView" );
model.fetchRecords( apex.region( "emp" ).call( "getSelectedRecords" );

forEach(pCallback, pThisArgopt)

Iterate over the model collection. Calls pCallback for each record in the model. Similar to Array.prototype.forEach. The model shape must be table or tree. This will never fetch new data. This includes aggregate records if any. For shape tree see also model#walkTree.

The callback receives the record, the zero based index of the record, and the identity (recordId) of the record.

Parameters:
Name Type Attributes Description
pCallback model.IteratorCallback Function called for each record in the model collection. The function is given the current record, index, and id.
pThisArg * <optional>
Value to use as this when calling pCallback.
Example

This example calculates the total of field SALARY for all the records that are currently in the model. Deleted and aggregate records are skipped.

var total = 0;
model.forEach( function( record, index, id ) {
    var salary = parseFloat( model.getValue( record, "SALARY" ) ),
        meta = model.getRecordMetadata( id );

    if ( !isNaN( salary ) && !meta.deleted && !meta.agg ) {
        total += salary;
    }
} );
// do something with total

forEachInPage(pOffset, pCount, pCallback, pThisArgopt)

Iterate over a range (page) of the model collection. This is only valid for table shape models. Calls pCallback for pCount records in the collection starting at pOffset. If the model doesn't yet contain the requested records they will be fetched from the server by calling model#fetch. If the collection has fewer records than requested or if there is an error fetching data from the server then pCallback is called with a null record.

The callback receives the record, the zero based index of the record, and the identity (recordId) of the record.

Parameters:
Name Type Attributes Description
pOffset number Zero based index to begin iterating.
pCount number The number of records to call pCallback for.
pCallback model.IteratorCallback Function called for each record in the model collection. The function is given the current record, index, and id.
pThisArg * <optional>
Value to use as this when calling pCallback.
Example

This example renders a pageSize page of records starting at offset currentPageOffset.

var count = 0,
    pageOffset = currentPageOffset;
model.forEachInPage( pageOffset, pageSize, function( record, index, id ) {
    if ( record ) {
        // render the record
        count += 1;
    }
    if ( count === pageSize || !record ) {
        // done rendering this page of records
    }
} );

getChanges() → {Array.<model.RecordMetadata>}

Return an array of record metadata for all changed records. Do not make any changes to the data structure returned. See also model#isChanged.

Returns:
Array of record metadata for changed records.
Type
Array.<model.RecordMetadata>
Example

This example logs a console message if the model has changed that includes the number of changes.

if ( model.isChanged() ) {
    console.log("Model has " + model.getChanges().length + " changes.");
}

getErrors() → {Array.<model.RecordMetadata>}

Return an array of record metadata for all records with errors. Do not make any changes to the data structure returned.

Returns:
Array of record metadata for error records.
Type
Array.<model.RecordMetadata>

getFieldKey(pFieldName) → {string|number|undefined}

Return the index/key to use for the given field name when accessing that field of a record. Use the value returned from this method to access a record field without using model#getValue. This will work regardless of if the records are stored as objects or arrays.

Parameters:
Name Type Description
pFieldName string The field name.
Returns:
returns undefined if the field doesn't exist or is virtual
Type
string | number | undefined
Example

This example gets the field key for the model field named "COST" and uses it in a loop over array of records selectedRecords.

var i, cost,
    costKey = model.getFieldKey("COST");
for ( i = 0; i < selectedRecords.length; i++ ) {
    cost = selectedRecords[i][costKey];
    // do something with cost
}

getFieldMetadata(pFieldName) → {model.FieldMeta}

Return metadata object for given field name. The field metadata is supplied when the model is created in option property fields.

Parameters:
Name Type Description
pFieldName string The field name.
Returns:
Metadata object or null if there is no such field.
Type
model.FieldMeta

getOption(pName) → {*}

Get the value of the given model option. The model options are provided in the call to apex.model.create. See also model#setOption.

Parameters:
Name Type Description
pName string Name of option to get.
Returns:
Option value.
Type
*
Examples

This example gets the onlyMarkForDelete option.

var markForDelete = model.getOption( "onlyMarkForDelete" );

This example gets the hasTotalRecords option.

var hasTotalRecords = model.getOption( "hasTotalRecords" );

getRecord(pRecordIdopt) → {model.Record|null}

Return the record for a given record id. This only considers records that are currently fetched into the model. The server may have a record with the given record id but if it hasn't yet been fetched into the model, it will not be found with this method.

For table or tree shape models that define an identityField option, call with the value of the record's identity field or if the records have multiple identity fields call with an array of ids or a string representation of the combined identity fields as returned by model#getRecordId.

For table shape models that don't define an identityField option call with the index of the record. This is the same as model#recordAt.

For record shape models call with no record id to get the one and only model record.

Parameters:
Name Type Attributes Description
pRecordId string | Array.<string> <optional>
The record id.
Returns:
Record or null if no record corresponding to pRecordId is found.
Type
model.Record | null
Examples

This example returns the record with identity "001002".

record = model.getRecord( "001002" );

This example has a table shape model with two identity fields. It returns the record from a model with identity ["AXB9", "00003"].

record = model.getRecord( ["AXB9", "00003"] );

This example returns the record from a model with shape record.

record = model.getRecord();

getRecordId(pRecord) → {string}

Given a record return the unique identifier (id) for the record. The id is used in calls to model#getRecordMetadata and model#getRecord. If the model has multiple identity fields this returns a string representation of the combined fields.

Parameters:
Name Type Description
pRecord model.Record The record to get the id from.
Returns:
The record id or null if no identityField is defined.
Type
string
Example

This example gets the identity of record someRecord and uses it to get the record metadata.

var id = model.getRecordId( someRecord ),
    meta = model.getRecordMetadata( id );
// use meta for something

getRecordMetadata(pRecordIdopt) → {model.RecordMetadata}

Return the metadata object for the record given by the record id. This only applies to models that define an identity field with option identityField.

Upper layers can store information related to the record here. The metadata should be related to the record itself and not the view of it.

Parameters:
Name Type Attributes Description
pRecordId string | Array.<string> <optional>
Value of the record's identity field or array of values of the record's identity fields or value returned by model#getRecordId. This can be omitted when the model shape is "record".
Returns:
Metadata object or null if there is no record associated with pRecordId.
Type
model.RecordMetadata
Example

This example checks if the record someRecord is updated.

var id = model.getRecordId( someRecord ),
    meta = model.getRecordMetadata( id );
if ( meta.updated ) {
    // do something related to the updated record
}

getRecordValue(pRecordId, pFieldName) → {*}

Get the value of a record field given the record id. This is only useful when the model shape is table or tree. If there are many field values to get or set use model#getRecord followed by model#getValue or model#setValue. See also model#setRecordValue.

Parameters:
Name Type Description
pRecordId string | Array.<string> Value of the record's identity field or array of values of the record's identity fields or value returned by model#getRecordId.
pFieldName string Name of record field to get.
Returns:
Value of record field.
Type
*
Example

This example gets the NAME field of the record with identity "00013".

var name = model.getRecordValue( "00013", "NAME" );

getSelectedCount() → {number}

Return the number of currently selected records. This only applies if a view is storing selection state in the model. See also model#setSelectionState.

This is used by views that store view selection state in the model to return the selection count.

Returns:
The number of selected records.
Type
number

getSelectedRecords() → {Array.<model.Record>}

Return an array of the selected records. This only applies if a view is storing selection state in the model. See also model#setSelectionState.

This is used by views that store view selection state in the model to return the selection.

Returns:
The selected records.
Type
Array.<model.Record>

getServerTotalRecords() → {number}

Returns the total number of records from the server's perspective or -1 if unknown.

For table shape models the server provides the total but for editable grids the number of inserted records is added and the number of deleted records subtracted. This is so the number reflects what is likely to be on the server after changes are saved.

For tree shape models this is not supported; returns -1.

For record shape models the number is always 1.

Note: Aggregate records are never included.

Returns:
The number of records or -1 if unknown.
Type
number

getTotalRecords(pCurrentTotalopt) → {number}

Returns the total number of records in the model collection or -1 if unknown.

For table shape models the total number of records may not be known or it may be an estimate. If the pagination type is "none" then the total records is known and it is the same as what is in the collection. If the pagination type is "progressive" and the model has paged to the end (all pages have been received and the server has said there is no more) then the total records is known and it is the same as what is in the collection (which could be different from what is actually on the server). If the server has told the model how many records it has then that is returned. This is an estimate of what the client model may eventually hold. This value may change as new pages are fetched. If the server has not told the model how many records it has then the total is unknown.

For tree shape models the total number of records is not often needed. It is also not readily available so the nodes must be counted. The total doesn't include nodes that have not yet been fetched and never returns -1 (unknown) even if there are nodes that haven't been fetched.

For record shape the number is always 1.

Note: Includes records that are marked for delete in the count. Also includes aggregate records if any in the count.

Parameters:
Name Type Attributes Description
pCurrentTotal boolean <optional>
If true, for table shape models will return the current total records in the collection rather than -1 if the total records is unknown.
Returns:
The number of records or -1 if unknown.
Type
number

getValue(pRecordopt, pFieldName) → {*}

Get the value of a record field given the record itself or omit the record when the model shape is record. See also model#setValue.

Parameters:
Name Type Attributes Description
pRecord model.Record <optional>
The record to return the value of the given column. Omit if model shape is record.
pFieldName string Name of record field to get.
Returns:
Value of record field.
Type
*
Examples

This example returns the NAME field of the given record.

var name = model.getValue( someRecord, "NAME" );

This example returns the NAME field from a record shape model.

var name = model.getValue( "NAME" );

hasChildren(pNode) → {boolean}

Returns true if the node pNode has children, false if it does not, and null if not yet known. A node that has its children lazy loaded may not know if it has any children until they are loaded.

Parameters:
Name Type Description
pNode model.Node The node to check if it has any children.
Returns:
true if the node has children, false if it does not, and null if not known.
Type
boolean
Example

This example logs a message to the console if the node is a leaf (has no children).

if ( model.hasChildren( node ) === true ) {
    console.log("node is a leaf");
}

hasErrors() → {Boolean}

Return true if the model has any errors.

Returns:
true if model has errors and false otherwise.
Type
Boolean
Example

This example logs a console message if the model has errors.

if ( model.hasErrors() ) {
    console.log("Model has errors.");
}

indexOf(pRecord) → {number}

Return the index of the record within the collection. The collection may include aggregate records. Useful because model#forEachInPage method takes a starting index/offset.

Only applies to table and tree shape models. Throws an error if the model shape is record. For tree shape models returns the index of the node among its siblings.

Parameters:
Name Type Description
pRecord model.Record The record to return the index of.
Returns:
The record index or -1 if not in collection.
Type
number

insertNewRecord(pParentRecordopt, pAfterRecordopt, pNewRecordopt) → {string}

Inserts a new record into the collection. Only applies to tree and table shape models. For tree shape models the record is inserted under the given parent node. The model must allow adding new records. See model#allowAdd.

Parameters:
Name Type Attributes Description
pParentRecord model.Record <optional>
Parent tree node. Only for tree shape models, must be null otherwise.
pAfterRecord model.Record <optional>
Record after which to insert the new record. If not given the new record is inserted at the beginning.
pNewRecord model.Record <optional>
The new record to insert. If not given a new record is created using defaults. The identity, meta, children, and parent fields if any will be initialized.
Fires:
Returns:
The temporary primary key of inserted record.
Type
string

isChanged() → {boolean}

Determine if the model has been changed in any way. See also model#getChanges.

Note: Auto inserted records don't count as changes unless they are also updated but they are returned by model#getChanges.

Returns:
true if the model has changed and false otherwise.
Type
boolean
Example

This example logs a console message if the model has changed.

if ( model.isChanged() ) {
    console.log("Model has changes.");
}

isDisabled(pRecord, pRecordMetaopt) → {boolean}

Return true if the record is disabled and false otherwise. The record disabled state is determined by the record model.RecordMetadata disabled property. If the disabled property is not defined or is null return a default of false.

Parameters:
Name Type Attributes Description
pRecord model.Record The record to determine disabled state for.
pRecordMeta model.RecordMetadata <optional>
Optional record metadata for pRecord. Pass this in if it is already available from a previous call to model#getRecordMetadata otherwise it will be retrieved from the given record.
Returns:
true if disabled and false otherwise.
Type
boolean

isIdentityField(pFieldName) → {boolean}

Return true if the given field name is an identity field and false otherwise.
Parameters:
Name Type Description
pFieldName string Name of record field.
Returns:
Type
boolean

metadataChanged(pRecordId, pFieldNameopt, pPropertyNameopt)

Call this method if any properties of the metadata returned by model#getRecordMetadata are changed external to this module. Most record or field metadata should not be changed externally. However it may be useful and reasonable to externally change metadata that comes from the records initially such as canEdit or custom metadata properties. The result of calling this method is sending a model#event:metaChange notification.

Parameters:
Name Type Attributes Description
pRecordId string Value of the record's identity field or array of values of the record's identity fields or value returned by model#getRecordId.
pFieldName string <optional>
Name of record field that has a metadata change if any.
pPropertyName string <optional>
Name of the metadata property that has changed. If multiple properties changed this can be a comma separated list.
Fires:

modelId() → {model.ModelId}

Return the model id for this model.
Returns:
Type
model.ModelId

moveRecords(pRecords, pParentRecordopt, pAfterRecordopt) → {Array.<string>}

Moves the given records to a new position in the collection (table or parentRecord's children) or, for tree shape only, to a new parent node.

For tree shape models if there is a parentIdentityField the moved records will have the parent identity field set to the identity of the new parent record.

Parameters:
Name Type Attributes Description
pRecords Array.<model.Record> Array of records to move.
pParentRecord model.Record <optional>
Only used when the shape is tree. This is the parent node to insert the moved records into. If null then insert to root.
pAfterRecord model.Record <optional>
The moved records are added after this record or if null at the beginning.
Fires:
Returns:
Array of record identities of moved records.
Type
Array.<string>

parent(pNode) → {model.Node}

Return the parent node of the given node. Only supported for tree shape models that have an identityField option defined.

This method must only be used on tree shape models.

Parameters:
Name Type Description
pNode model.Node The node to get the parent of.
Returns:
Parent node or null for the root node and undefined otherwise
Type
model.Node

recordAt(index) → {model.Record}

Return the record at the given index within the model collection. Only applies to table shape models.

Parameters:
Name Type Description
index number The index of the record to return.
Returns:
The record or null if there is no record at the given index.
Type
model.Record
Example

This example returns the fifth record in the collection assuming it exists.

var record = model.recordAt(5);

revertRecords(pRecords) → {number}

Revert one or more records to the way they were when first added to the model or last saved. This undoes any changes made to the records. See also model#canRevertRecord.

Parameters:
Name Type Description
pRecords Array.<model.Record> The records to revert.
Fires:
Returns:
The number of records reverted. This can be less than the number of records in pRecords if some of the records had no changes to revert.
Type
number
Example

This example checks if a record can be reverted before reverting it.

if ( myModel.canRevertRecord( record ) ) {
    myModel.revertRecords( [record] );
}

root() → {model.Node}

Return the root node of the tree. An error is thrown if the model shape is not tree.

Returns:
Root node or null if there is no root.
Type
model.Node
Example

This example gets the tree shape model root node.

var rootNode = model.root();

save(pCallbackopt) → {promise}

Save all changed model data to the server. The current changes are copied to the save request except that volatile fields are not included (they are omitted/deleted i.e. not null or undefined) and the metadata has the op property added with value "d" if the record was deleted, "i" if the record was inserted, and "u" if the record was updated. If the record has no metadata field defined then one is added. For array records it is the last element, for object records it is property _meta.

It is possible to continue making changes to the model while a save is in progress. Can use either the callback argument or the returned promise to determine when the request is complete.

See also apex.model.save.

Parameters:
Name Type Attributes Description
pCallback function <optional>
A function to call when the save request is complete. callback( error, responseData ); The callback is passed an Error argument or array of server errors only if there is an error. Otherwise error is null.
Returns:
A promise if the save is initiated and null otherwise (there is already a save in progress or there is nothing to save). If and only if a promise is returned, pCallback will be called. The promise receives no arguments when resolved and an Error argument when rejected.
Type
promise

setData(pData, pOffsetopt, pTotalopt, pMoreDataopt)

Give the model data. This is used in cases where the model doesn't get data from the server or at least not using the built in mechanisms.

Parameters:
Name Type Attributes Description
pData array Model data to set.
pOffset number <optional>
Offset at which to add the data. Defaults to 0. If adding the root of a tree shape model set this to null;
pTotal number <optional>
Total number of records in the servers collection. Only applies for table shape models.
pMoreData boolean <optional>
If true there is more data available on the server for this model. If false pData contains all the data. If omitted or null determine if there is more data based on pData and pTotal. If pTotal is not given assume there is more data on server. Only applies for table shape models and only if paginationType is not "none".
Fires:

setDisabledState(pRecordId, pDisabled)

Set the disabled property of the model#getRecordMetadata for the record given by pRecordId. This is a convenience method that looks up the record metadata, sets the disabled property, and calls the model#metadataChanged method if the value changed.

Parameters:
Name Type Description
pRecordId string | Array.<string> The record id to set the disabled state on.
pDisabled boolean | null The new disabled state to set.

setHiddenState(pRecordId, pHidden)

Set the hidden property of the model#getRecordMetadata for the record given by pRecordId. This is a convenience method that looks up the record metadata, sets the hidden property, and calls the model#metadataChanged method if the value changed.

Parameters:
Name Type Description
pRecordId string | Array.<string> The record id to set the hidden state on.
pHidden boolean | null The new hidden state to set.

setOption(pName, pValue)

Set the value of the given model option. The model options are provided in the call to apex.model.create. See also model#getOption.

The options that can be set are:

  • genIdPrefix
  • pageItemsToSubmit
  • fetchData
  • saveData
  • regionData
  • parentRecordId
  • editable
  • pageSize
  • requestOptions
  • callServer
  • visibilityFilter
  • visibilityFilterContext
Parameters:
Name Type Description
pName string Name of option to set. Not all options can be set.
pValue * Value to set the option to.

setRecordValue(pRecordId, pFieldName, pValue)

Set the value of a record field given the record id. This is only useful when the model shape is table or tree. If there are many field values to get or set use model#getRecord followed by model#getValue or model#setValue. See also model#getRecordValue.

Parameters:
Name Type Description
pRecordId string | Array.<string> Value of the record's identity field or array of values of the record's identity fields or value returned by model#getRecordId.
pFieldName string Name of record field to set.
pValue * Value to set.
Example

This example sets the NAME field of the record with identity "00013".

model.setRecordValue( "00013", "NAME", newName );

setSelectionState(pRecordId, pSelected)

Select or unselect the given record.

This method should only be used by view widgets to persist the view selection state in metadata property sel. Note there is no notification about this metadata change. Listen to the view for selection change events. Also use the view to change the selection.

Parameters:
Name Type Description
pRecordId string | Array.<string> The record id to set the selection state metadata.
pSelected boolean The desired record selection state; true to select and false to unselect.

setValidity(pValidity, pRecordId, pFieldNameopt, pMessageopt)

Sets the validity and associated validation message of a record or record field.

Parameters:
Name Type Attributes Description
pValidity string one of "error", "warning", "valid".
pRecordId string Value of the record's identity field or array of values of the record's identity fields or value returned by model#getRecordId.
pFieldName string <optional>
Name of field that the validity state applies to or null if it applies to the whole record.
pMessage string <optional>
Error or warning message text or omit if valid
Example

This examples calls a function, checkRecord, that returns an error message if the record is not valid and null if it is valid. It then sets the validity of the record.

var invalidReasonMessage = checkRecord( recordId );
if ( invalidReasonMessage ) {
    model.setValidity( "error", recordId, null, invalidReasonMessage );
} else {
    this.model.setValidity( "valid", recordId );
}

setValue(pRecordopt, pFieldName, pValue) → {string|null}

Set the value of a record field given the record itself or omit the record when the model shape is record. See also model#getValue.

An error is thrown if the record does not allow editing or the field does not allow being set.

Parameters:
Name Type Attributes Description
pRecord model.Record <optional>
The record that will have a field set to the given value. Omit if model shape is record.
pFieldName string Name of record field to set.
pValue * the value to set
Fires:
Returns:
One of:
  • "SET": The value was set.
  • "DUP": The value was not set because of duplicate identity. This can only happen when setting an identity field. Note: Even if the new value is unique on the client it may still result in an error when saving because the client in general does not have all the data that the server does.
  • "NC": The value was not set because the new value is equal to the old value.
  • null: The record is not in the model.
Type
string | null
Examples

This example sets the NAME field of the given record.

model.setValue( someRecord, "NAME", newName );

This example sets the identity field PART_NO of the given record. It checks for a duplicate value and gives a message if the new part number is already taken.

var result = model.setValue( someRecord, "PART_NO", newPartNo );
if ( result === "DUP" ) {
    apex.message.alert( "The part number " + newPartNo + " is already taken." );
}

This example sets the NAME field of a record shape model.

model.setValue( "NAME", newName );

subscribe(pObserver) → {string}

Subscribe to model change notifications by adding an observer.

Parameters:
Name Type Description
pObserver model.Observer An observer object that includes a callback function to receive notifications.
Returns:
A viewId to use with model#unSubscribe. This is the same as the viewId property if there is one. One is generated if not given in pObserver
Type
string
Examples

This simple example subscribes to a model to handle notifications.

var viewId = model.subscribe( {
    onChange: function( changeType, change ) {
        // respond to model changes
    }
} );

This example is typical of what a widget that displays model data would do to subscribe.

var viewId = model.subscribe( {
    viewId: this.element[0].id
    onChange: function(changeType, change) {
        // respond to model changes
    },
    progressView: this.element
} );

transform(pOptions, pContextopt) → {Object}

Transform a copy of the table shape model data into another data structure according to the provided template rules. The transformed output data structure is returned.

Parameters:
Name Type Attributes Description
pOptions Object An object with properties that define how the model data is to be transformed. All properties are optional except for template.
Properties
Name Type Description
template Array.<Object> An array of rule objects each one describing where and how to create an array in the output data. Each rule object can have these properties:
Properties
Name Type Description
path string A "/" separated list of property names or indexed fields. The path specifies where in the output object structure to create an (or use existing) array to add items to. For example a path of "a/b" will result in output:

 {
     a: {
         b: [<items go here>]
     }
 }
 

An indexed field is the name of a record field wrapped in square brackets. This creates an array for each unique value of the field. For example a path of "a/[ENABLED]/b" where the field ENABLED can have values of "yes" and "no" results in output:


 {
     a: [
         {
             b: [<items for records with enabled = yes go here>]
         },
         {
             b: [<items for records with enabled = no go here>]
         }
     ]
 }
 
filter function Filter function( model, record, index, id) return true to include and return false to skip the given record.
uniqueIndexField string The name of a record field. If given an item will be added to the array only for the first record with a unique value of this field.
item Object | Array | string | function An object, string, array or function that serves as a template for the elements/items of the output array the resulting value depends on the type:
  • string: A string is the name of a record field and the resulting value is the value of that field or if it begins and ends with a single quote then the value is the text inside the single quotes or if it begins with ( and ends with ) the string inside the parens is the name of a record field and the resulting value is the raw value of that field not the display value or showNullAs value.
  • function: The resulting value is the return value of the function f(pContext, self, record, index, id)
  • object: the resulting value is a new object where the properties of the new object are the same as the properties of this template object and the value of the properties support the same options as item.
  • array: The resulting value is a new array where the value items in the new array come from the template items in this array. The template items support the same options as item.
sort string A function suitable as the argument to Array.prototype.sort that will sort the output array after all records are processed.
filter function Filter function( model, record, index, id) return true to include and return false to skip the given record.
showNullAs string A string to substitute for null field values.
includeAggregates boolean If true aggregate records are included otherwise they are skipped this is done before the filter function is called.
offset number Offset index of first record to process defaults to 0.
count number Count of records starting at offset to process. Defaults to all the data currently in the model.
pContext Object <optional>
This is the output object to return with data arrays filled in based on the template rules. If pContext is not given an empty object is used as a starting point. All functions are called in the context of this object. Note: if the template rule(s) don't have a path then pContext can be an array.
Returns:
The output data structure. Same object as pContext if it was given.
Type
Object
Example

The following example generates groups and series data for a jet Bar chart from a model created from:
select job, deptno, avg(sal) as avg_sal from emp group by job, deptno

var data = mymodel.transform( {
             template: [ {
                     path: "groups",
                     uniqueIndexField: "DEPTNO",
                     item: { name: "DEPTNO" }
                 }, {
                     path: "series",
                     uniqueIndexField: "JOB",
                     item: { name: "JOB" }
                 }, {
                     path: "series/[JOB]/items",
                     item: { label: "'AVG_SAL'",
                             value: "AVG_SAL",
                             name: "DEPTNO"
                         }
                 } ]
             });

unSubscribe(pViewId)

Unsubscribe to model change notifications.

Parameters:
Name Type Description
pViewId string The view id returned from model#subscribe.
Example

This example unsubscribes from this model using the viewId returned when subscribing.

model.unSubscribe(viewId);

updateVisibility(pVisibilityContextopt)

Update the visibility of all records currently in the model by calling the visibilityFilter function and setting the record hidden metadata property for each record. Useful for client side filtering of views of table or tree shaped models. This method does nothing if the visibilityFilter or visibilityFilterContext options are not set.

Client side filtering works best for reasonable sized reports and when the model has all the data to filter on. Not all view layer components will make use of the hidden property. For those that do it may only work if the view has rendered all the data.

See also model#setHiddenState and the visibilityFilter and visibilityFilterContext options of apex.model.create.

Parameters:
Name Type Attributes Description
pVisibilityContext object <optional>
If present, the visibilityFilterContext option is set to this value. If omitted the current visibilityFilterContext is used.
Example

The following example filters a Cards region with static id "people" using Text Field item P1_FILTER as the user types with a 200ms delay.

var filterItem = apex.item("P1_FILTER"),
    lastFilterString = null,
    filterContext = {
        matchString: ""
    };

function myFilter( model, record, context ) {
    var match = false;
    // match record against context.matchString and return true if there is a match
    return match;
};

function checkFilter() {
    var value = filterItem.getValue();

    if ( value !== lastFilterString ) {
        // only filter if the value has changed and don't do it too often
        debounceFilterCards( value );
        lastFilterString = value;
    }
};

function filterCards( filterString ) {
    var model = apex.region( "people" ).call( "getModel" );
    filterContext.matchString = filterString.toUpperCase(); // toUpperCase typical for case independent compare
    model.updateVisibility( filterContext );
};
var debounceFilterCards = apex.util.debounce( filterCards, 200 );

// these options could instead be set in region JavaScript Initialization Code
var model = apex.region( "people" ).call( "getModel" );
    model.setOption( "visibilityFilter", myFilter );
    model.setOption( "visibilityFilterContext", filterContext );

filterItem.element.on( "input", function() {
    checkFilter();
} );
checkFilter();

walkTree(pNode, pVisitor, pParentNodeopt)

Traverse the tree shape model. Methods of the pVisitor object are called as follows:

  • First the visitor node method is called for the pNode passed to walkTree.
  • If the node has children the remaining steps are done.
  • The visitor beginChildren method is called.
  • For each child node walkTree is called performing these steps recursively.
  • The visitor endChildren method is called.
Parameters:
Name Type Attributes Description
pNode model.Node The node to start with. This node is visited and then all of its children are.
pVisitor object
Properties
Name Type Attributes Description
node function Function with signature function(node, parent).
beginChildren function <optional>
Function with signature function(node).
endChildren function <optional>
Function with signature function(node).
pParentNode model.Node <optional>
The parent node of pNode or null if pNode is the root. If this argument is omitted or undefined and the model has the identityField option defined the parent node will be determined automatically. If this argument is omitted or undefined and the model does not have the identityField option defined then the parent parameter in each call to the visitor node method is null.
Example

This example walks the tree shape model starting at the root logging information about the tree as it goes. Indentation shows the structure of the tree. The nodes in this model have a NAME field.

var indent = "";
model.walkTree( model.root(), {
    node: function( node, parent ) {
        console.log( indent + "Node: " + model.getValue( node, "NAME" ) );
    },
    beginChildren: function( node ) {
        indent += "    ";
    },
    endChildren: function( node ) {
        indent = indent.substring(4);
    }
}, null );

Type Definitions

CheckCallback(pResult, pOperation, pRecord, pAddActionopt, pRecordsToAddopt) → {boolean}

A callback function to do additional access checking. See the check option property of apex.model.create and the model#check method.

Parameters:
Name Type Attributes Description
pResult boolean The result of the access checking so far.
pOperation string One of the default checks ("canEdit", "canDelete", "canAdd", "canDrag") or a custom operation.
pRecord model.Record The record to check if action is allowed on it.
pAddAction string <optional>
Only used by allowAdd see model#allowAdd for details.
pRecordsToAdd Array.<model.Record> <optional>
Only used by allowAdd see model#allowAdd for details.
Returns:
true if the operation is allowed.
Type
boolean

FieldMeta

The field metadata describes the field and affects how the model uses the field. It may contain additional properties especially if the metadata is shared with view layers.
Type:
  • object
Properties:
Name Type Description
index string Only used when records are arrays. This is the index into the array where the field value is stored.
defaultValue * This value is used when a new record is added or an existing record is duplicated and noCopy is true. The defaultValue has no effect for the identity, meta, children, and parent fields if defined. If there is no defaultValue empty string is used. If defaultValue is a function it is called and the return value is used as the field's value. The function is passed the model. If the new record is a copy of an existing record the source record is also passed in.
dataType string The data type of the field value.
calcValue function This is a function used to calculate the value for the field. When any of the fields listed in the dependsOn property change this function is called. The function signature is calcValue( argsArray, model, record ) return *. The values of the fields listed in dependsOn are passed in the argsArray. This function is also called when a record is received from the server and the value of this field is null or undefined.
dependsOn array An array of field names from this model that this field depends on. When any of the fields named in this array change then this field is either marked stale or if there is a calcValue function the calcValue function is called to recalculate the value of this field.
aggregates array An array of aggregate function names. The built-in aggregate function names are: "COUNT", "COUNT_DISTINCT", "SUM", "AVG", "MIN", "MAX", "MEDIAN".
parentField string Only applies if the model has a parentModel. When a new record is added or an existing record is duplicated and noCopy is true the value of this field is taken from the parentField of the parentModel This is useful for foreign key fields but can be any field that gets a default from the parentModel.
noCopy boolean If true the field value is not copied when a record is copied/duplicated.
readonly boolean If true the field cannot be edited.
volatile boolean The field is generated by the server. It cannot be edited. It is not sent back to the server. This means that for records stored as arrays the volatile fields should be at the end or the server must account for the missing volatile fields when using other field's index. Volatile fields may depend on (are calculated from) other fields and the value may be considered stale if the record is edited. It is up to the view layers to make this determination.
virtual boolean A virtual field has no associated data. None of the other properties apply. The main purpose for including a virtual field is so that view layers and the model can share the same field metadata. This allows view layers to have fields that don't have corresponding data in the model.

IteratorCallback(pRecord, pIndex, pId, pErroropt)

This callback is used by the model#forEach and model#forEachInPage methods.
Parameters:
Name Type Attributes Description
pRecord model.Record The current record.
pIndex number The zero based index within the model collection of the current record.
pId string The identity of the current record if the model identityField option is given. If there is no identity then this is undefined for tree models and is the pIndex as a string for table models.
pError Error <optional>
If and only if there is an error fetching data during a call to model#forEachInPage this is the error object otherwise this is undefined.

ModelId

A model is uniquely identified by a string name and optional string instance id. The instance id is used to support multiple detail models in a master detail arrangement. The instance id is the identity value of the record in the master model for which the detail model pertains. The form for a model id is "name" or a tuple array ["name","instance"]

Type:
  • string | array
Examples

A model with no instance.

"MyModel"

A detail model with instance id "000109".

["MyDetailModel", "000109"]

Node

A model node is a synonym for model.Record that is more naturally used when the model has a tree shape.
Type:
  • array | object

Observer

Information about an observer for subscribing to this model. See model#subscribe and model#unSubscribe.

Type:
  • object
Properties:
Name Type Attributes Description
viewId string <optional>
A unique key that can be used to unsubscribe. A DOM element id makes a good unique key.
onChange function A function to receive change notifications. The signature is function(changeType, change)
changeType is a string describing the change such as "delete"
change is an object with details about the change.
See each notification for details.
progressView jQuery <optional>
jQuery object to center a progress spinner over while performing an asynchronous network operation such as model#fetch or model#save.
progressOptions object <optional>
Options object for apex.util.showSpinner.

Record

A model record is either an array or an object depending on the model option recordIsArray.
Type:
  • array | object

RecordFieldMetadata

Metadata related to a specific record field.
Type:
  • object
Properties:
Name Type Description
changed boolean true if the field has changed.
stale boolean true if the value of this field depends on other fields and those fields have changed and this field has not been recalculated.
error boolean true if the field has an error.
warning boolean true if the field has a warning.
message string Only present when error or warning are true. Describes the error or warning condition.
disabled boolean true if the field is disabled. Disabled fields are written to the server as empty string.
highlight string A string that view layers can use to provide extra styling for the field.
ck string A checksum. If present and not null indicates the record field is readonly.
url string Use for cells that are links. This is the link target. The cell value is the link label.

RecordMetadata

Metadata properties that the model creates and uses.
Type:
  • object
Properties:
Name Type Description
deleted boolean true if the record has been deleted otherwise false or undefined.
inserted boolean true if the record is newly created and inserted/added to the collection otherwise false or undefined.
autoInserted boolean true if the record was auto inserted (these records are not saved if not also updated)
updated boolean true if the record has had any fields changed.
original model.Record When updated is true this is the original record before any changes.
record model.Record Reference to the record that this metadata is about.
parent model.Record The parent record of this record. Only applies to tree shape models.
error boolean true if the record as a whole has an error.
warning boolean true if the record as a whole has a warning.
message string Only present when error or warning are true. Describes the error or warning condition.
sel boolean true if the record is selected and false otherwise.
highlight string A string that view layers can use to provide extra styling for the record.
disabled boolean true if the record is disabled. The model makes the disabled state available to the view layer; it does not act on the disabled state at all. Not all view layers will make use of this property. Typically a view layer will not let disabled records be selected and may show them with different styles. Typically a disabled record also has allowedOperations set to not allow editing or deleting. See model#isDisabled and model#setDisabledState.
hidden boolean true if the record should be hidden by view layers. The model makes the hidden state available to the view layer; it does not act on the hidden state at all. Not all view layers will make use of this property. Typically a view layer will use css or some other means to make hidden records invisible. See model#setHiddenState.
allowedOperations object
Properties
Name Type Description
delete boolean true if the record can be deleted.
update boolean true if the record can be updated.
canEdit boolean Derived from allowedOperations.update
canDelete boolean Derived from allowedOperations.delete
endControlBreak boolean Used by views to implement control break UI. The server sets this to true in the last record of each group of control break records.
agg * For aggregate records this is the name of the aggregate function.
grandTotal boolean For aggregate records this is true for the overall value (grand total) records.
fields Object.<string, model.RecordFieldMetadata> An object that maps from a field name to metadata about the field.