# ViewFoundSet

## Overview

A **View Foundset Datasource** is a virtual table that loads data at runtime, often based on a **QBSelect** query object. It is useful for combining datasets from multiple tables, improving performance compared to standard relations, valuelists, or aggregates.

## Creating View Foundset Datasources

View Foundset Datasources can be created in two ways:

1. **Solution Explorer**: Accessed via *Datasources -> View foundsets -> Create view foundset* in the Solution Explorer context menu. This opens the [Table Editor](https://docs.servoy.com/reference/servoy-developer/object-editors/table-editor) for defining the datasource structure.
2. **Runtime Creation**: Created via `databaseManager.getViewFoundSet(String name, QBSelect query)`. This returns a `ViewFoundSet` object with essential operations like `getSize()`, `getRecord()`, and `loadAllRecords()`, but it doesn’t support `find()` or `search()`.

## Data Broadcast and Monitoring Changes

View Foundsets do not listen for databroadcast changes by default but can be enabled using `viewfoundset.enableDatabroadcastFor(QBTableClause queryTable, int flags)`. Available flags include:

* [**MONITOR\_COLUMNS**](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/viewfoundset#monitor_columns): Tracks changes in specific columns.
* [**MONITOR\_JOIN\_CONDITIONS**](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/viewfoundset#monitor_join_conditions): Listens for changes in join conditions.
* [**MONITOR\_WHERE\_CONDITIONS**](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/viewfoundset#monitor_where_conditions): Tracks updates to WHERE clause columns.
* [**MONITOR\_INSERT**](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/viewfoundset#monitor_insert): Monitors inserts, triggering a full query update.
* [**MONITOR\_DELETES**](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/viewfoundset#monitor_deletes): Tracks deletions, updating records as needed.
* [**MONITOR\_DELETES\_FOR\_PRIMARY\_TABLE**](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/viewfoundset#monitor_deletes_for_primary_table): Monitors primary table deletions more efficiently.
* [**MONITOR\_AGGREGATES**](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/viewfoundset#monitor_aggregates): Observes changes impacting aggregates in the query.

## Editable View Foundsets

A **View Foundset** can be made editable with `save()` if the primary key (PK) is included in the `QBSelect`. Data updates pause databroadcast refreshes until the records are committed.

## Commands Summary

* *Create view foundset datasource*: Opens the [Table Editor](https://docs.servoy.com/reference/servoy-developer/object-editors/table-editor).
* *Edit table/view*: Edits the View Foundset structure via the [Table Editor](https://docs.servoy.com/reference/servoy-developer/object-editors/table-editor).
* *Delete View Foundset*: Deletes the View Foundset.
* *Rename View Foundset*: Renames the View Foundset.

For more details, refer to the [View Foundset Datasource](https://docs.servoy.com/guides/develop/application-design/data-modeling/view-datasource) documentation in the **Data modeling** section.

## **Extends**

[JSFoundSet](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsfoundset)

## Constants Summarized

| Type                                                                         | Name                                                                        | Summary                                                                                                                                                                                        |
| ---------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) | [MONITOR\_AGGREGATES](#monitor_aggregates)                                  | Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen for changes in columns (selected) of the given datasource in the query that can affect aggregates.              |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) | [MONITOR\_COLUMNS](#monitor_columns)                                        | Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen also for column changes of the given table/datasource.                                                          |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) | [MONITOR\_DELETES](#monitor_deletes)                                        | Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen for deletes on the given table/datasource.                                                                      |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) | [MONITOR\_DELETES\_FOR\_PRIMARY\_TABLE](#monitor_deletes_for_primary_table) | Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen for deletes on the given table/datasource which should be the primary/main table of this query.                 |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) | [MONITOR\_INSERT](#monitor_insert)                                          | Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen for inserts on the given table/datasource.                                                                      |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) | [MONITOR\_JOIN\_CONDITIONS](#monitor_join_conditions)                       | Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen also for column changes of the given table/datasource in the join statement - like order\_lines.                |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) | [MONITOR\_WHERE\_CONDITIONS](#monitor_where_conditions)                     | Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen also for column changes of the given table/datasource that are used in the where statement - like order\_lines. |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) | [VIEW\_FOUNDSET](#view_foundset)                                            |                                                                                                                                                                                                |

## Properties Summarized

| Type                                                                           | Name                        | Summary |
| ------------------------------------------------------------------------------ | --------------------------- | ------- |
| [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) | [multiSelect](#multiselect) |         |

## Methods Summarized

| Type                                                                                                     | Name                                                                                              | Summary                                                                                                                                                                                                                                                                                                                           |
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean)                           | [dispose()](#dispose)                                                                             | Dispose and unregisters a view foundset from memory when is no longer needed.                                                                                                                                                                                                                                                     |
| [JSFoundSet](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsfoundset)           | [duplicateFoundSet()](#duplicatefoundset)                                                         | Get a duplicate of the viewfoundset.                                                                                                                                                                                                                                                                                              |
| void                                                                                                     | [enableDatabroadcastFor(queryTable)](#enabledatabroadcastfor-querytable)                          | Databroadcast can be enabled per select table of a query, the select table can be the main QBSelect or on of it QBJoins By default this monitors only the column values that are in the result of the QBSelect, you can only enable this default monitoring for a table if for that table also the PK is selected in the results. |
| void                                                                                                     | [enableDatabroadcastFor(queryTableclause, flags)](#enabledatabroadcastfor-querytableclause-flags) | Enable the databroadcast for a specific table of the QBSelect or QBJoin with flags for looking for join or where criteria or deletes/inserts.                                                                                                                                                                                     |
| [Object](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/object)                             | [forEach(callback)](#foreach-callback)                                                            | Iterates over the records of a foundset taking into account inserts and deletes that may happen at the same time.                                                                                                                                                                                                                 |
| [Object](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/object)                             | [forEach(callback, thisObject)](#foreach-callback-thisobject)                                     | Iterates over the records of a foundset taking into account inserts and deletes that may happen at the same time.                                                                                                                                                                                                                 |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                             | [getCurrentSort()](#getcurrentsort)                                                               | Get the last sort columns that were set using viewfoundset sort api.                                                                                                                                                                                                                                                              |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                             | [getDataSource()](#getdatasource)                                                                 | Returns the datasource (view:name) for this ViewFoundSet.                                                                                                                                                                                                                                                                         |
| [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array)                               | [getEditedRecords()](#geteditedrecords)                                                           | Get the edited records of this view foundset.                                                                                                                                                                                                                                                                                     |
| [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array)                               | [getFailedRecords()](#getfailedrecords)                                                           | Get the records which could not be saved.                                                                                                                                                                                                                                                                                         |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                             | [getName()](#getname)                                                                             | Get foundset name.                                                                                                                                                                                                                                                                                                                |
| [QBSelect](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/qbselect)               | [getQuery()](#getquery)                                                                           | Get the cloned query that created this ViewFoundSset (modifying this QBSelect will not change the foundset).                                                                                                                                                                                                                      |
| [JSRecord](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecord)               | [getRecord(index)](#getrecord-index)                                                              | Get the ViewRecord object at the given index.                                                                                                                                                                                                                                                                                     |
| [JSRecord](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecord)               | [getRecordByPk(pk)](#getrecordbypk-pk)                                                            | Get the ViewRecord from the primary key values.                                                                                                                                                                                                                                                                                   |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)                             | [getRecordIndex(record)](#getrecordindex-record)                                                  | Get the record index.                                                                                                                                                                                                                                                                                                             |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                             | [getSQL()](#getsql)                                                                               | Returns the internal SQL of the JSFoundset.                                                                                                                                                                                                                                                                                       |
| [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)                             | [getSQL(includeFilters)](#getsql-includefilters)                                                  | Returns the internal SQL of the JSFoundset.                                                                                                                                                                                                                                                                                       |
| [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array)                               | [getSQLParameters()](#getsqlparameters)                                                           | Returns the parameters for the internal SQL of the QBSelect.                                                                                                                                                                                                                                                                      |
| [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array)                               | [getSQLParameters(includeFilters)](#getsqlparameters-includefilters)                              | Returns the parameters for the internal SQL of the QBSelect.                                                                                                                                                                                                                                                                      |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)                             | [getSelectedIndex()](#getselectedindex)                                                           | Get the current record index of the foundset.                                                                                                                                                                                                                                                                                     |
| [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array)                               | [getSelectedIndexes()](#getselectedindexes)                                                       | Get the indexes of the selected records.                                                                                                                                                                                                                                                                                          |
| [JSRecord](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecord)               | [getSelectedRecord()](#getselectedrecord)                                                         |                                                                                                                                                                                                                                                                                                                                   |
| [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array)                               | [getSelectedRecords()](#getselectedrecords)                                                       | Get the selected records.                                                                                                                                                                                                                                                                                                         |
| [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)                             | [getSize()](#getsize)                                                                             | Get the number of records in this viewfoundset.                                                                                                                                                                                                                                                                                   |
| [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean)                           | [hasRecordChanges()](#hasrecordchanges)                                                           | Check whether the foundset has record changes.                                                                                                                                                                                                                                                                                    |
| [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean)                           | [hasRecords()](#hasrecords)                                                                       | Returns true if the viewfoundset has records.                                                                                                                                                                                                                                                                                     |
| [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean)                           | [loadAllRecords()](#loadallrecords)                                                               | This will reload the current set of ViewRecords in this foundset, resetting the chunk size back to the start (default 200).                                                                                                                                                                                                       |
| void                                                                                                     | [revertEditedRecords()](#reverteditedrecords)                                                     | Revert changes of all unsaved view records of the view foundset.                                                                                                                                                                                                                                                                  |
| void                                                                                                     | [revertEditedRecords(rec)](#reverteditedrecords-rec)                                              | Revert changes of the provided view records.                                                                                                                                                                                                                                                                                      |
| [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean)                           | [save()](#save)                                                                                   | Saves all records in the view foundset that have changes.                                                                                                                                                                                                                                                                         |
| [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean)                           | [save(record)](#save-record)                                                                      | Saved a specific record of this foundset.                                                                                                                                                                                                                                                                                         |
| void                                                                                                     | [setSelectedIndex(index)](#setselectedindex-index)                                                | Set the current record index.                                                                                                                                                                                                                                                                                                     |
| void                                                                                                     | [setSelectedIndexes(indexes)](#setselectedindexes-indexes)                                        | Set the selected records indexes.                                                                                                                                                                                                                                                                                                 |
| void                                                                                                     | [sort(sortString)](#sort-sortstring)                                                              | Sorts the foundset based on the given sort string.                                                                                                                                                                                                                                                                                |
| void                                                                                                     | [sort(sortString, defer)](#sort-sortstring-defer)                                                 | Sorts the foundset based on the given sort string.                                                                                                                                                                                                                                                                                |
| void                                                                                                     | [sort(recordComparisonFunction)](#sort-recordcomparisonfunction)                                  | Sorts the foundset based on the given record comparator function.                                                                                                                                                                                                                                                                 |
| [JSRecordMarkers](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecordmarkers) | [validate(record)](#validate-record)                                                              | Validates the given record, it runs first the method that is attached to the entity event "onValidate".                                                                                                                                                                                                                           |
| [JSRecordMarkers](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecordmarkers) | [validate(record, customObject)](#validate-record-customobject)                                   | Validates the given record, it runs first the method that is attached to the entity event "onValidate".                                                                                                                                                                                                                           |

## Constants Detailed

### MONITOR\_AGGREGATES

Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen for changes in\
columns (selected) of the given datasource in the query that can affect aggregates. This means that when\
there are deletes, inserts or updates on columns selected from that datasource, a full re-query will\
happen to refresh the aggregates.

IMPORTANT: in general, this flag should be set on (possible multiple) datasources from the query that\
have group by on their columns, and the columns don't contain the pk, or that have the actual aggregates\
on their columns (because all those could influence the value of aggregates).

For example (ignoring the fact that in a real-life situation these fields might not change), a view\
foundset based on this query:

SELECT orders.customerid, orders.orderdate, SUM(order\_details.unitprice) FROM orders\
&#x20;  LEFT OUTER JOIN order\_details ON orders.orderid = order\_details.orderid\
&#x20;  GROUP BY orders.customerid, orders.orderdate\
&#x20;     ORDER BY orders.customerid asc, orders.orderdate desc

will want to enable databroadcast flag MONITOR\_AGGREGATES on both "orders" (because if "orderdate" or\
"customerid" - that are used in GROUP BY - change/are corrected on a row, that row could move from one\
group to the other, affecting the SUM(order\_details.unitprice) for the groups involved) and "order\_details"\
(because if "unitprice" changes/is corrected, the aggregate will be affected).

But if the above query would also select the orders.odersid (and also group by that) then the orders row\
that you select for that sum will always be unique and only #MONITOR\_COLUMNS has to be used for\
those - if needed.

**Type**\
[Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)

### MONITOR\_COLUMNS

Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen also for column\
changes of the given table/datasource. This is used by default if you just use enableDatabroadcastFor()\
without flags. If you use the one with the flags you need to give this one if you just want to listen to\
column changes that are in the result for a given datasource and pk.

This constants needs to have the pk's selected for the given datasource (should be in the results).

**Type**\
[Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)

### MONITOR\_DELETES

Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen for deletes on the given table/datasource. This will always result in a full query to detect changes whenever an delete on that table happens.

**Type**\
[Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)

### MONITOR\_DELETES\_FOR\_PRIMARY\_TABLE

Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen for deletes on the\
given table/datasource which should be the primary/main table of this query. If a delete comes in for this\
table, then we will only remove the records from the ViewFoundSet that do have this primary key in its\
value. So no need to do a full query. So this will only work if the query shows order\_lines for the\
order\_lines table, not for the products table that is joined to get the product\_name. Only 1 of the 2\
monitors for deletes should be registered for a table/datasource.

This constants needs to have the pk's selected for the given datasource (should be in the results)

**Type**\
[Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)

### MONITOR\_INSERT

Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen for inserts on the given table/datasource. This will always result in a full query to detect changes whenever an insert on that table happens.

**Type**\
[Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)

### MONITOR\_JOIN\_CONDITIONS

Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen also for column changes of the given table/datasource in the join statement - like order\_lines.productid that has a join to orders and is displaying the productname. If a change in such a join condition (like order\_lines.productid in the sample above) is seen then the query will be fired again to detect changes.

**Type**\
[Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)

### MONITOR\_WHERE\_CONDITIONS

Constant for the flags in #enableDatabroadcastFor(QBTableClause,int) to listen also for column changes of the given table/datasource that are used in the where statement - like order\_lines.unit\_price > 100. If a change is seen on that datasource on such a column used in the where a full query will be fired again to detect changes.

**Type**\
[Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number)

### VIEW\_FOUNDSET

**Type**\
[String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string)

## Properties Detailed

### multiSelect

**Type**\
[Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) \`true\` if the ViewFoundSet supports selecting multiple records; \`false\` if only single selection is allowed.

## Methods Detailed

### dispose()

```
Dispose and unregisters a view foundset from memory when is no longer needed.
Returns whether foundset was disposed.
If linked to visible form or component, view foundset cannot be disposed.

Normally ViewFoundSets are not hold on to by the system, so if you only use this inside a method it will be disposed by itself.
This method is then just helps by also calling clear()

For ViewFoundSets that are also registered  by using true as the last argument in the call: databaseMananager.getViewFoundSet(name, query, boolean register)
are hold on to by the system and Forms can use it for there foundset. Calling dispose on those will remove it from the system, so it is not usable anymore in forms.
```

**Returns:** [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) boolean foundset was disposed

**Sample**

```js
vfs.dispose();
```

### duplicateFoundSet()

Get a duplicate of the viewfoundset. This is a full copy of the view foundset.

**Returns:** [JSFoundSet](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsfoundset) foundset duplicate.

**Sample**

```js
var dupFoundset = foundset.duplicateFoundSet();
```

### enableDatabroadcastFor(queryTable)

Databroadcast can be enabled per select table of a query, the select table can be the main QBSelect or on of it QBJoins\
By default this monitors only the column values that are in the result of the QBSelect, you can only enable this default monitoring for a table if for that table also the PK is selected in the results.

you can use #enableDatabroadcastFor(QBTableClause,int) to specify what should be monitored more besides pure column values per pk.\
Those have impact on performance because for the most part if we see a hit then a full query is done to see if there are changes.

**Parameters**

* [QBTableClause](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/qbtableclause) **queryTable** The QBSelect or QBJoin of a full query where this foundset should listen for data changes.

**Returns:** void

**Sample**

```js
var select = datasources.db.example_data.order_details.createSelect();
 var join = select.joins.add("db:/example_data/products");
 join.on.add(select.columns.productid.eq(join.columns.productid));
 select.result.add(); // add columns of the select or join
 var vf = databaseManager.getViewFoundSet("myorders",select)
 vf.enableDatabroadcastFor(select);
 vf.enableDatabroadcastFor(join);
```

### enableDatabroadcastFor(queryTableclause, flags)

```
Enable the databroadcast for a specific table of the QBSelect or QBJoin with  flags for looking for join or where criteria or deletes/inserts.
These  flags can be a performance hit because the query needs to be executed again to see if there are any changes.
For certain flags #MONITOR_COLUMNS and #MONITOR_DELETES_FOR_PRIMARY_TABLE the pk for that table must be in the results.
```

**Parameters**

* [QBTableClause](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/qbtableclause) **queryTableclause** The QBSelect or QBJoin of a full query where this foundset should listen for data changes.
* [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) **flags** One or more of the ViewFoundSet.XXX flags added to each other.

**Returns:** void

**Sample**

```js
var select = datasources.db.example_data.order_details.createSelect();
 var join = select.joins.add("db:/example_data/products");
 join.on.add(select.columns.productid.eq(join.columns.productid));
 select.result.add(); // add columns of the select or join
 var vf = databaseManager.getViewFoundSet("myorders",select)
 // monitor for the main table the join conditions (orders->product, when product id changes in the orders table) and requery the table on insert events, delete directly the record if a pk delete happens.
 vf.enableDatabroadcastFor(select, ViewFoundSet.MONITOR_JOIN_CONDITIONS | ViewFoundSet.MONITOR_INSERT | ViewFoundSet.MONITOR_DELETES_FOR_PRIMARY_TABLE);
 vf.enableDatabroadcastFor(join);
```

### forEach(callback)

Iterates over the records of a foundset taking into account inserts and deletes that may happen at the same time.\
It will dynamically load all records in the foundset (using Servoy lazy loading mechanism). If callback function returns a non null value the traversal will be stopped and that value is returned.\
If no value is returned all records of the foundset will be traversed. Foundset modifications( like sort, omit...) cannot be performed in the callback function.\
If foundset is modified an exception will be thrown. This exception will also happen if a refresh happens because of a rollback call for records on this datasource when iterating.\
When an exception is thrown from the callback function, the iteration over the foundset will be stopped.

**Parameters**

* [Function](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/function) **callback** The callback function to be called for each loaded record in the foundset. Can receive three parameters: the record to be processed, the index of the record in the foundset, and the foundset that is traversed.

**Returns:** [Object](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/object) Object the return value of the callback

**Sample**

```js
foundset.forEach(function(record,recordIndex,foundset) {
 	//handle the record here
 });
```

### forEach(callback, thisObject)

Iterates over the records of a foundset taking into account inserts and deletes that may happen at the same time.\
It will dynamically load all records in the foundset (using Servoy lazy loading mechanism). If callback function returns a non null value the traversal will be stopped and that value is returned.\
If no value is returned all records of the foundset will be traversed. Foundset modifications( like sort, omit...) cannot be performed in the callback function.\
If foundset is modified an exception will be thrown. This exception will also happen if a refresh happens because of a rollback call for records on this datasource when iterating.\
When an exception is thrown from the callback function, the iteration over the foundset will be stopped.

**Parameters**

* [Function](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/function) **callback** The callback function to be called for each loaded record in the foundset. Can receive three parameters: the record to be processed, the index of the record in the foundset, and the foundset that is traversed.
* [Object](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/object) **thisObject** What the this object should be in the callback function (default it is the foundset)

**Returns:** [Object](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/object) Object the return value of the callback

**Sample**

```js
foundset.forEach(function(record,recordIndex,foundset) {
 	//handle the record here
 });
```

### getCurrentSort()

Get the last sort columns that were set using viewfoundset sort api.s

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) String sort columns

**Sample**

```js
//reverse the current sort

//the original sort "companyName asc, companyContact desc"
//the inversed sort "companyName desc, companyContact asc"
var foundsetSort = foundset.getCurrentSort()
var sortColumns = foundsetSort.split(',')
var newFoundsetSort = ''
for(var i=0; i<sortColumns.length; i++)
{
	var currentSort = sortColumns[i]
	var sortType = currentSort.substring(currentSort.length-3)
	if(sortType.equalsIgnoreCase('asc'))
	{
		newFoundsetSort += currentSort.replace(' asc', ' desc')
	}
	else
	{
		newFoundsetSort += currentSort.replace(' desc', ' asc')
	}
	if(i != sortColumns.length - 1)
	{
		newFoundsetSort += ','
	}
}
foundset.sort(newFoundsetSort)
```

### getDataSource()

Returns the datasource (view:name) for this ViewFoundSet.

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) the datasource string representing the ViewFoundSet, typically in the format "view:\<name>".

**Sample**

```js
solutionModel.getForm("x").dataSource  = viewFoundSet.getDataSource();
```

### getEditedRecords()

Get the edited records of this view foundset.

**Returns:** [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array) an array of edited records

**Sample**

```js
var editedRecords = foundset.getEditedRecords();
for (var i = 0; i < editedRecords.length; i++)
{
   application.output(editedRecords[i]);
}
```

### getFailedRecords()

Get the records which could not be saved.

**Returns:** [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array) an array of failed records

### getName()

Get foundset name. If foundset is not named foundset will return null.

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) name.

**Sample**

```js
var name = foundset.getName()
```

### getQuery()

Get the cloned query that created this ViewFoundSset (modifying this QBSelect will not change the foundset).\
The ViewFoundSets main query can't be altered after creation; you need to make a new ViewFoundSet for that (it can have the same datasource name).

**Returns:** [QBSelect](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/qbselect) query.

**Sample**

```js
var q = foundset.getQuery()
q.where.add(q.columns.x.eq(100))
var newVF = databaseManager.getViewFoundset("name", q);
```

### getRecord(index)

Get the ViewRecord object at the given index.\
Argument "index" is 1 based (so first record is 1).

**Parameters**

* [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) **index** record index (1 based).

**Returns:** [JSRecord](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecord) ViewRecord record.

**Sample**

```js
var record = vfs.getRecord(index);
```

### getRecordByPk(pk)

Get the ViewRecord from the primary key values.

**Parameters**

* [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array) **pk** pk values as array

**Returns:** [JSRecord](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecord) ViewRecord record.

**Sample**

```js
var record = vfs.getRecordByPk(1);  // or getRecordByPk(1,2) or ([1,2]) for multicolumn pk
```

### getRecordIndex(record)

Get the record index. Will return -1 if the record can't be found.

**Parameters**

* [JSBaseRecord](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsbaserecord) **record** Record

**Returns:** [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) int index.

**Sample**

```js
var index = foundset.getRecordIndex(record);
```

### getSQL()

Returns the internal SQL of the JSFoundset.\
Optionally, the foundset and table filter params can be excluded in the sql (includeFilters=false).

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) String representing the sql of the JSFoundset.

**Sample**

```js
var sql = foundset.getSQL(true)
```

### getSQL(includeFilters)

Returns the internal SQL of the JSFoundset.\
Optionally, the foundset and table filter params can be excluded in the sql (includeFilters=false).

**Parameters**

* [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) **includeFilters** include the foundset and table filters \[default true].

**Returns:** [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) String representing the sql of the JSFoundset.

**Sample**

```js
var sql = foundset.getSQL(true)
```

### getSQLParameters()

Returns the parameters for the internal SQL of the QBSelect.\
Table filters are on by default.

**Returns:** [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array) An Array with the sql parameter values.

**Sample**

```js
var parameters = foundset.getSQLParameters(true)
```

### getSQLParameters(includeFilters)

Returns the parameters for the internal SQL of the QBSelect.\
Table filters are on by default.

**Parameters**

* [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) **includeFilters** include the foundset and table filters \[default true].

**Returns:** [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array) An Array with the sql parameter values.

**Sample**

```js
var parameters = foundset.getSQLParameters(true)
```

### getSelectedIndex()

Get the current record index of the foundset.

**Returns:** [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) int current index (1-based)

**Sample**

```js
//gets the current record index in the current foundset
var current = foundset.getSelectedIndex();
//sets the next record in the foundset
foundset.setSelectedIndex(current+1);
```

### getSelectedIndexes()

Get the indexes of the selected records.\
When the foundset is in multiSelect mode (see property multiSelect), a selection can consist of more than one index.

**Returns:** [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array) Array current indexes (1-based)

**Sample**

```js
// modify selection to the first selected item and the following row only
var current = foundset.getSelectedIndexes();
if (current.length > 1)
{
	var newSelection = new Array();
	newSelection[0] = current[0]; // first current selection
	newSelection[1] = current[0] + 1; // and the next row
	foundset.setSelectedIndexes(newSelection);
}
```

### getSelectedRecord()

**Returns:** [JSRecord](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecord) the currently selected \`ViewRecord\`, or \`null\` if no record is selected.

### getSelectedRecords()

Get the selected records.\
When the viewfoundset is in multiSelect mode (see property multiSelect), selection can be a more than 1 record.

**Returns:** [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array) Array current records.

**Sample**

```js
var selectedRecords = foundset.getSelectedRecords();
```

### getSize()

Get the number of records in this viewfoundset.\
This is the number of records loaded, note that when looping over a foundset, size() may\
increase as more records are loaded.

**Returns:** [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) int current size.

**Sample**

```js
var nrRecords = vfs.getSize()

// to loop over foundset, recalculate size for each record
for (var i = 1; i <= foundset.getSize(); i++)
{
	var rec = vfs.getRecord(i);
}
```

### hasRecordChanges()

Check whether the foundset has record changes.

**Returns:** [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) true if the foundset has any edited records, false otherwise

### hasRecords()

Returns true if the viewfoundset has records.

**Returns:** [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) true if the viewfoundset has records.

### loadAllRecords()

This will reload the current set of ViewRecords in this foundset, resetting the chunk size back to the start (default 200).\
All edited records will be discarded! So this can be seen as a full clean up of this ViewFoundSet.

**Returns:** [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) true if the records were successfully reloaded.

### revertEditedRecords()

Revert changes of all unsaved view records of the view foundset.

**Returns:** void

### revertEditedRecords(rec)

Revert changes of the provided view records.

**Parameters**

* [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array) **rec** an array of view records

**Returns:** void

### save()

Saves all records in the view foundset that have changes.\
You can only save columns from a table if the pks of that table are also selected by the view foundset's query.

**Returns:** [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) true if the save was successfull, false if not and then the record will hav the exception set.

### save(record)

Saved a specific record of this foundset.\
You can only save columns from a table if also the pk is selected of that table

**Parameters**

* [JSRecord](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecord) **record** ;

**Returns:** [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) true if the save was successfull, false if not and then the record will hav the exception set.

### setSelectedIndex(index)

Set the current record index.

**Parameters**

* [Number](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/number) **index** index to set (1-based)

**Returns:** void

**Sample**

```js
//gets the current record index in the current foundset
var current = foundset.getSelectedIndex();
//sets the next record in the foundset
foundset.setSelectedIndex(current+1);
```

### setSelectedIndexes(indexes)

Set the selected records indexes.

**Parameters**

* [Array](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/array) **indexes** An array with indexes to set.

**Returns:** void

**Sample**

```js
// modify selection to the first selected item and the following row only
var current = foundset.getSelectedIndexes();
if (current.length > 1)
{
	var newSelection = new Array();
	newSelection[0] = current[0]; // first current selection
	newSelection[1] = current[0] + 1; // and the next row
	foundset.setSelectedIndexes(newSelection);
}
```

### sort(sortString)

Sorts the foundset based on the given sort string.\
Column in sort string must already exist in ViewFoundset.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **sortString** the specified columns (and sort order)

**Returns:** void

**Sample**

```js
foundset.sort('columnA desc,columnB asc');
```

### sort(sortString, defer)

Sorts the foundset based on the given sort string.\
Column in sort string must already exist in ViewFoundset.

**Parameters**

* [String](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/string) **sortString** the specified columns (and sort order)
* [Boolean](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/boolean) **defer** when true, the "sortString" will be just stored, without performing a query on the database (the actual sorting will be deferred until the next data loading action).

**Returns:** void

**Sample**

```js
foundset.sort('columnA desc,columnB asc');
```

### sort(recordComparisonFunction)

Sorts the foundset based on the given record comparator function.\
Tries to preserve selection based on primary key. If first record is selected or cannot select old record it will select first record after sort.\
The comparator function is called to compare\
two records, that are passed as arguments, and\
it will return -1/0/1 if the first record is less/equal/greater\
then the second record.

The function based sorting does not work with printing.\
It is just a temporary in-memory sort.

NOTE: starting with 7.2 release this function doesn't save the data anymore

**Parameters**

* [Function](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/function) **recordComparisonFunction** record comparator function

**Returns:** void

**Sample**

```js
foundset.sort(mySortFunction);

function mySortFunction(r1, r2)
{
	var o = 0;
	if(r1.id < r2.id)
	{
		o = -1;
	}
	else if(r1.id > r2.id)
	{
		o = 1;
	}
	return o;
}
```

### validate(record)

Validates the given record, it runs first the method that is attached to the entity event "onValidate".\
Those methods do get a parameter JSRecordMarkers where the problems can be reported against.\
All columns are then also null/empty checked and if they are and the Column is marked as "not null" an error will be\
added with the message key "servoy.record.error.null.not.allowed" for that column.

An extra state object can be given that will also be passed around if you want to have more state in the validation objects\
(like giving some ui state so the entity methods know where you come from)

It will return a JSRecordMarkers when the record had validation problems

**Parameters**

* [JSRecord](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecord) **record** ;

**Returns:** [JSRecordMarkers](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecordmarkers) Returns a JSRecordMarkers if the record has validation problems

### validate(record, customObject)

Validates the given record, it runs first the method that is attached to the entity event "onValidate".\
Those methods do get a parameter JSRecordMarkers where the problems can be reported against.\
All columns are then also null/empty checked and if they are and the Column is marked as "not null" an error will be\
added with the message key "servoy.record.error.null.not.allowed" for that column.

An extra state object can be given that will also be passed around if you want to have more state in the validation objects\
(like giving some ui state so the entity methods know where you come from)

It will return a JSRecordMarkers when the record had validation problems

**Parameters**

* [JSRecord](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecord) **record** The ViewRecord to validate
* [Object](https://docs.servoy.com/reference/servoycore/dev-api/js-lib/object) **customObject** An extra customObject to give to the validate method.

**Returns:** [JSRecordMarkers](https://docs.servoy.com/reference/servoycore/dev-api/database-manager/jsrecordmarkers) a \`JSRecordMarkers\` object indicating validation problems for the given record with the provided custom context, or \`null\` if no issues are found.

***
