Pre-General Availability: 2018-4-26

Interface: model

QuickNav

model

A model holds data in memory for use by the UI layer. 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 UI terms the record might be called a row.
  • 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 and UI table/grid terms the fields are called columns. The actual storage of an 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 is used to map from the field name to the record array index.

The model doesn't impose any restrictions on the values of fields and doesn't know the data type of the field. However typically when the model data is backing APEX items or HTML form controls the values will all be strings. There are five specific (optional and configurable) fields that the model will use if you configure the model with the name of the field used for the purpose:

  • identity: a string value that uniquely identifies the record. There can be multiple identity fields. Required for editable models.
  • type: a string value that identifies the type of record for the purpose of making decisions such as if the record can be edited or deleted etc. The type is used to access additional metadata about the record based on its type. See the types model option.
  • meta: an object with additional metadata about the record.
  • children: (tree shape only) an array of the child records (nodes).
  • parent identity: (tree shape only) a string value that identifies the parent record (node) of this record (node). Required for editable tree shaped models.
  • sequence: a number value that determines the order of a record in the collection (lower numbers first). If the collection is a tree then it is the sequence among its siblings. Only required for editable models that support reordering.

Another special case is for cell values that have both a display value and an intrinsic value. These composite values have the form: { d: "display value", v: value } The only time the model cares about this internal structure is when accessing the "type" field. When comparing values during setValue only the value is considered not the display value. Also when the changes are saved 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 rows that the server includes in order among all the other rows marked with meta data property agg: true. The aggregate record has most fields empty except for the aggregate fields that contain the aggregate value.

Since:
  • 5.1

Example

usage
1) getting initial data to render and paging
widget_foo.init(...)
   var m = model.create(name, options, data, total); // data and total may be omitted or null
   m.forEachInPage(...); // ask for just what widget wants to render. Start at page offset 0.
                         // Model will get data from server as needed.
on page change (could be due to buttons or scrolling)
   m.forEachInPage(...); // ask for just what widget wants to render. Model will get data from server as needed.

2) when widget settings change that affect the result set
   m.clearData(); // calling setData with the new result set will have same effect
use model observer to listen for "refresh" and reset the widget page offset to 0 then call
   m.forEachInPage(...); // ask for just what widget wants to render. Model will get data from server as needed.

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 integer Index into the client model data. 0 for tree or record shape models
count integer 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 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.

instanceRename

Sent when the model instance changes. This happens when model.renameInstance is called, which is generally the result of the value of the master column in a master model changing.
Properties:
Name Type Description
changeType string "instanceRename"
change object
Properties
Name Type Description
oldInstance string xxx
newInstance string xxx

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 should call 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 object The record that changed.
field object The name of the field that changed or null if field metadata didn't change.

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 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(pParentRecord, 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 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

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

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

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).
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

check(pOperation, pRecord, 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.

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, and 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 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 integer The index of the child node.
Returns:
The ith child node.
Type
model.Node

childCount(pNode) → {integer}

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
integer

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.
Fires:

clearData()

Remove all data from the model.

Fires:

clearSelection()

Unselect all the selected records.

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. todo details, access checks
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.
Returns:
Array of temp primary keys of inserted records.
Type
Array.<string>

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 forEach, forEachInPage, walkTree, etc. and can be found by getRecord. They will be deleted once the 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.
Returns:
The number of records deleted or marked for delete.
Type
number

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.
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 nodes 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) Can use either the callback argument or the returned promise to determine when the request is complete.
Parameters:
Name Type Attributes Description
pOffset integer <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 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
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(callback)

Fetch all the data from the server into the model. This repeatedly calls fetch until the server reports there is no more data. This is only for table shape models. Data is fetched in in pageSize chunks.
Parameters:
Name Type Description
callback 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 getTotalRecords) done: true if all the data is fetched. This is the last time the callback is called.

fetchChildNodes(pNode, pCallbackopt) → {promise}

Fetch child nodes for node pNode. This method is only used for trees that lazy load data from the sever as needed. The top level of nodes should not be lazy loaded. This is an asynchronous operation. When it completes the pCallback function is called as follows: pCallback( status ) 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 the node record to fetch children for
pCallback function <optional>
callback function that is called after nodes have been fetched or there is an error
Returns:
receives no arguments 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 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.
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

forEach(pCallback, pThisArgopt)

Iterate over the model collection. Calls pCallback for each record in the model. Similar to Array.prototype.forEach. 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.
Parameters:
Name Type Attributes Description
pCallback function ( pRecord, pIndex, pId ) when the shape is tree and there is no identityField the pId argument is meaningless.
pThisArg * <optional>
Value to use as this when calling pCallback

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 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 integer Zero based index to begin iterating
pCount integer The number of records to call pCallback for
pCallback function (record, index, recordId)
pThisArg * <optional>
Value to use as this when calling pCallback

getChanges() → {array}

Return an array of changes todo details todo is a copy needed? Is this just what will be sent to the server or is there a different method for that? likely different
Returns:
Type
array

getDataOverflow() → {boolean}

Return true if the number of records in the data set on the server exceeds some configured maximum
Returns:
Type
boolean

getErrors() → {array}

Return an array of errors todo details
Returns:
Type
array

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

Return the index/key to use for the given field name when accessing that field of a record.
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
Usage to return the value of a record field<br>
    model.getRecord( recordId )[model.getFieldKey("last_name")]<br>
Using this method will work regardless of if the records are stored as objects or arrays.

getFieldMetadata(pFieldName) → {object}

Return metadata object for given field name. Upper layers can store information related to the field here. The metadata should be related to the field itself and not the view of it. See above overview for field metadata properties that the model creates and/or uses
Parameters:
Name Type Description
pFieldName string The field name.
Returns:
Metadata object or null if there is no such field.
Type
object

getOption(pName) → {*}

Get the value of the given model option.
Parameters:
Name Type Description
pName string Name of option to get.
Returns:
Option value.
Type
*

getRecord(pRecordId)

Return the record for a given record id.
Parameters:
Name Type Description
pRecordId string for models that define an identityField this is the value of the record's identity field or if the records have multiple identity fields this can be an array of ids or a string representation of the combined identity fields as returned by getRecordId. otherwise it is the table (array) index
Returns:
record or null if no record corresponding to pRecordId

getRecordId(pRecord) → {string}

Given an record return the unique identifier (id) for the record. The id is used in calls to model#getRecordMetadata and model#getRecord.
Parameters:
Name Type Description
pRecord model.Record The record to get the id of.
Returns:
The record id or null if no identityField is defined.
Type
string

getRecordMetadata(pRecordId) → {object}

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

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.

todo there was supposed to be something to distinguish metadata that had to go back to the server
Parameters:
Name Type Description
pRecordId string this is the value of the record's identity field or array of values of the record's identity fields.
Properties:
Name Type Description
error boolean true if the record is in error state.
warning boolean true if the record is in warning state.
Returns:
metadata object or null if there is no record associated with pRecordId
Type
object

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 getRecord followed by getValue or setValue
Parameters:
Name Type Description
pRecordId string for models that define an identityField this is the value of the record's identity field or if the records have multiple identity fields this can be an array of ids or a string representation of the combined identity fields as returned by getRecordId. otherwise it is the table (array) index
pFieldName string name of record field to get
Returns:
value of record field
Type
*

getSelectedCount() → {integer}

Return the number of currently selected records.
Returns:
The number of selected records.
Type
integer

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

Return an array of the selected records.
Returns:
The selected records
Type
Array.<model.Record>

getServerTotalRecords() → {number}

Returns the total number of records from the server's perspective -1 if unknown. For table shape 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 not supported; returns -1. todo consider if the server could specify the total like it does for tables For record shape the number is always 1. Note: Aggregate records are never included.
Returns:
number of records or -1 if unknown.
Type
number

getTotalRecords() → {integer}

Returns the total number of records in the model collection or -1 if unknown. For table shape 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 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.
Returns:
number of records or -1 if unknown.
Type
integer

getTypeMetadata(pTypeName) → {object}

Return metadata for given type name. See comments before model.create for more information on the properties associated with a type.
Parameters:
Name Type Description
pTypeName the type name
Returns:
metadata object or null if there is no such type
Type
object

getValue(pRecordopt, pFieldName) → {*}

Get the value of a record field given the record itself or omit the record when the model shape is record.
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
*

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 how 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

hasErrors() → {Boolean}

Return true if the model has any errors
Returns:
true if model has errors and false otherwise
Type
Boolean

indexOf(pRecord) → {integer}

Return the index of the record within the collection. Useful because forEachInPage method takes a starting index/offset.
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
integer

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

Inserts a new record into the collection. todo details
Parameters:
Name Type Attributes Description
pParentRecord model.Record <optional>
Parent tree node, only for tree shape models null otherwise.
pAfterRecord model.Record <optional>
Record after which to insert the new record.
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.
Returns:
Temp primary key of inserted record.
Type
string

isChanged() → {boolean}

Determine if the model has been changed in any way. Note: Auto inserted records don't count as changes unless they are also updated but they are returned by getChanges.
Returns:
true if the model has changed and false otherwise
Type
boolean

isIdentityField(pFieldNameopt) → {boolean}

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

metadataChanged(pRecordId, pFieldNameopt)

Call this method if any properties of the metadata returned by 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.
Parameters:
Name Type Attributes Description
pRecordId string for models that define an identityField this is the value of the record's identity field or if the records have multiple identity fields this can be an array of ids or a string representation of the combined identity fields as returned by getRecordId. otherwise it is the table (array) index
pFieldName string <optional>
name of record field that has a metadata change if any Sends metaChange notification.

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.

If there is a sequenceField the records are assumed to already be sorted by the sequence. The moved records will be given new sequence numbers that maintain the order.

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

todo access checks

Note: Unless the parent record changes or there is a sequence field there is no change and nothing to revert.

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.
Returns:
Array of primary keys 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.

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. Only applies to table shape models.

Parameters:
Name Type Description
index integer
Returns:
The record or null if there is no record at the given index.
Type
model.Record

revertRecords(pRecords) → {integer}

Return one or more records to the way they were when first added to the model (fetched).
Parameters:
Name Type Description
pRecords Array.<model.Record>
Returns:
The number of records reverted.
Type
integer

root() → {model.Node}

Return the root node of the tree
Returns:
root node or null if there is no root
Type
model.Node

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.
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 a 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). Iff a promise is returned, pCallback will be called. The promise receives no arguments when resolved and an Error argument when rejected.
Type
promise

saveInProgress() → {boolean}

Determine if a save operation is in progress
Returns:
true if currently saving the model, false otherwise
Type
boolean

setData(pData, pOffsetopt)

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 integer <optional>
optional offset of the data
Fires:

setOption(pName, pValue)

Set the value of the given model option.
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 getRecord followed by getValue or setValue
Parameters:
Name Type Description
pRecordId string for models that define an identityField this is the value of the record's identity field or if the records have multiple identity fields this can be an array of ids or a string representation of the combined identity fields as returned by getRecordId. otherwise it is the table (array) index
pFieldName string name of record field to set
pValue * value to set

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 view for selection change events. Also use view to change the selection.

Parameters:
Name Type Description
pRecordId 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
pFieldName string <optional>
if the validity applies to a specific field
pMessage string <optional>
error or warning message text or omit if valid

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

Set the value of a record field given the record itself or omit the record when the model shape is record.
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
Returns:
One of "SET": value was set, "DUP": not set because duplicate identity, "NC": not set because no change
Type
string

subscribe(observer) → {string}

Subscribe to model change notifications by adding an observer.
Parameters:
Name Type Description
observer model.Observer Has these properties viewId: string optional, unique key can be used to unsubscribe. A DOM element id makes a good unique key. onChange: function(changeType, change) changeType is a string describing the change such as "delete" change is an object with details about the change. progressView: jQuery object to center a progress spinner over while performing a long running network operation progressOptions: options object for apex.util.showSpinner
Returns:
viewId (one is generated if not given in observer)
Type
string

transform(pOptions, pContextopt) → {object}

Transform a copy of the 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 template: required. 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: path: A / separated last 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: [] } } 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: [] }, { b: [] } ] } filter: Filter function( model, record, index, id) return true to include and return false to skip the given record uniqueIndexField: 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: 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: 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. the resulting value is the return value of the function f(pContext, self, record, index, id) 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. 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: A function suitable as the argument to Array.sort that will sort the output array after all records are processed filter: Filter function( model, record, index, id) return true to include and return false to skip the given record showNullAs: includeAggregates: boolean optional. if true aggregate records are included otherwise they are skipped this is done before the filter is run offset: optional offset index of first record to process defaults to 0. count: optional count of records starting at offset to process. If fetchData is false defaults to all the data currently in the model. If fetchData is true defaults to the models pageSize option. If fetchData is true and count is -1 then all the data will be fetched in pageSize chunks. todo this is async fetchData: If true allow more data to be fetched as needed by using forEachInPage otherwise forEach is used to loop over the records that are currently in the model. done: function( data ) todo to support async
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(viewId)

Unsubscribe to model change notifications.
Parameters:
Name Type Description
viewId string view xxx

walkTree(pNode, pVisitor, pParentNodeopt)

Traverse the tree data model calling the visitor. The visitor is called as each node is processed. When the visitor node method is called pParentNode is null unless nodes have an identityField.
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 function an object with methods node(pNode, pParentNode), beginChildren(pNode), and endChildren(pNode)
pParentNode model.Node <optional>
xxx

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 may contain additional properties especially if the metadata is shared with view layers. todo xxx Fields: The model must be given metadata about each of the fields a record contains. The fields metadata is an object map from field name to object with the following properties.
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.
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.

ModelId

A model is uniquely identified by a string name and optional string instance id. The instance id is useful 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

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

xxx
Properties:
Name Type Attributes Description
viewId string <optional>
onChange function
progressView Element

Record

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

RecordMetadata

Metadata properties that the model creates and uses.
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 changed)
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
recordId string internal use, only applies briefly after saving an inserted record this is the previous id by which the record was known
error boolean true if the record as a whole has an error
warning boolean true if the record as a whole has an error
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 Metadata from records
allowedOperations object { delete: , update: , protected: }
Properties
Name Type Description
delete boolean true if the record can be deleted
update boolean true if the record can be updated
protected string xxx
canEdit: boolean derived from allowedOperations.updated
canDelete: boolean derived from allowedOperations.delete
canDrag boolean xxx
protected string xxx
rowVersion * opaque to model
salt * opaque to model
endControlBreak boolean used by views to implement control break UI
agg * xxx
grandTotal * xxx
highlight string xxx
fields object { : { } } allows setting error, warning, message, and highlight etc. metadata on specific fields xxx see model.RecordFieldMetadata.