This page is written mostly for NG web component creators, not for Servoy developers that just want to use web components. You might want to view general Servoy Foundset documentation instead.
The 'foundset' property type can be used by web components to access/change a foundset's data/state directly from the browser.
The foundset typed property in the browser will work based on a 'viewport' of the server's foundset. The viewport is controlled directly by the component's code. Server will adjust foundset viewport bounds/contents only when needed due to data changes, deletes, inserts...
The foundset property also gives the possibility of knowing/changing the selection of the foundset.
For advanced uses, the foundset property can be linked to/interact with other property types (dataprovider, tagstring, component, ...), so that those other properties will provide a viewport as well - representing the same rows/records as in the foundset's viewport. The properties that support foundset view of data will allow the web component to specify a "forFoundset: "[foundsetPropertyName]" in their own property's description in the .spec file.
For foundset property types Servoy Developer allows (in properties view) one of the following:
a (parent) form's foundset
a related foundset
a separate foundset (of any table; similar to JSDatabaseManager.getFoundset()). When this option is chosen the user can also choose whether or not the separate foundset should load all records initially. (if not checked, contents can be loaded at any time from scripting)
"- none -" which means that you are going to set that foundset at runtime through scripting.
Foundset property value in browser scripting
In browser js, a foundset property value has the following content:
Browser side provided property content in model
export interface IFoundsetFieldsOnly {
/**
* An identifier that allows you to use this foundset via the 'foundsetRef' and
* 'record' types.
*
* 'record' and 'foundsetRef' .spec types use it to be able to send RowValue
* and FoundsetValue instances as record/foundset references on server (so
* if an argument or property is typed as one of those in .spec file).
*
* In reverse, if a 'foundsetRef' type sends a foundset from server to client
* (for example as a return value of callServerSideApi) it will translate to
* this identifier on client (so you can use it to find the actual foundset
* property in the model, if server side script put it in the model as well).
*/
foundsetId: number;
/**
* the size of the foundset on server (so not necessarily the total record count
* in case of large DB tables)
*/
serverSize: number;
/**
* this is the data you need to have loaded on client (just request what you need via provided
* loadRecordsAsync or loadExtraRecordsAsync)
*/
viewPort: ViewPort;
/**
* array of selected records in foundset; indexes can be out of current
* viewPort as well
*/
selectedRowIndexes: number[];
/**
* sort string of the foundset, the same as the one used in scripting for
* foundset.sort and foundset.getCurrentSort. Example: 'orderid asc'.
*/
sortColumns: string;
/**
* the multiselect mode of the server's foundset; if this is false,
* selectedRowIndexes can only have one item in it
*/
multiSelect: boolean;
/**
* the findMode state of the server's foundset
*/
findMode: boolean;
/**
* if the foundset is large and on server-side only part of it is loaded (so
* there are records in the foundset beyond 'serverSize') this is set to true;
* in this way you know you can load records even after 'serverSize' (requesting
* viewport to load records at index serverSize-1 or greater will load more
* records in the foundset)
*/
hasMoreRows: boolean;
/**
* columnFormats is only present if you specify
* "provideColumnFormats": true inside the .spec file for this foundset property;
* it gives the default column formatting that Servoy would normally use for
* each column of the viewport - which you can then also use in the
* browser yourself; keys are the dataprovider names and values are objects that contain
* the format contents
*/
columnFormats?: Record<string, any>;
}
/**
* Interface for client side values of 'foundset' typed properties in .spec files.
*/
export interface IFoundset extends IFoundsetFieldsOnly {
/**
* Request a change of viewport bounds from the server; the requested data will be loaded
* asynchronously in 'viewPort'.
*
* @param startIndex the index that you request the first record in "viewPort.rows" to have in
* the real foundset (so the beginning of the viewPort).
* @param size the number of records to load in viewPort.
*
* @return a promise that will get resolved when the requested records arrived browser-
* side. As with any promise you can register success, error callbacks, finally, ...
* See JSDoc of RequestInfoPromise.requestInfo and FoundsetChangeEvent.requestInfos
* for more information about determining if a listener event was caused by this call.
*/
loadRecordsAsync(startIndex: number, size: number): RequestInfoPromise<any>;
/**
* Request more records for your viewPort; if the argument is positive more records will be
* loaded at the end of the 'viewPort', when negative more records will be loaded at the beginning
* of the 'viewPort' - asynchronously.
*
* @param negativeOrPositiveCount the number of records to extend the viewPort.rows with before or
* after the currently loaded records.
* @param dontNotifyYet if you set this to true, then the load request will not be sent to server
* right away. So you can queue multiple loadLess/loadExtra before sending them
* to server. If false/undefined it will send this (and any previously queued
* request) to server. See also notifyChanged(). See also notifyChanged().
*
* @return a promise that will get resolved when the requested records arrived browser-
* side. As with any promise you can register success, error callbacks, finally, ...
* That allows custom component to make sure that loadExtra/loadLess calls from
* client do not stack on not yet updated viewports to result in wrong bounds.
* See JSDoc of RequestInfoPromise.requestInfo and FoundsetChangeEvent.requestInfos
* for more information about determining if a listener event was caused by this call.
*/
loadExtraRecordsAsync(negativeOrPositiveCount: number, dontNotifyYet?: boolean): RequestInfoPromise<any>;
/**
* Request a shrink of the viewport; if the argument is positive the beginning of the viewport will
* shrink, when it is negative then the end of the viewport will shrink - asynchronously.
*
* @param negativeOrPositiveCount the number of records to shrink the viewPort.rows by before or
* after the currently loaded records.
* @param dontNotifyYet if you set this to true, then the load request will not be sent to server
* right away. So you can queue multiple loadLess/loadExtra before sending them
* to server. If false/undefined it will send this (and any previously queued
* request) to server. See also notifyChanged(). See also notifyChanged().
*
* @return a promise that will get resolved when the requested records arrived browser
* -side. As with any promise you can register success, error callbacks, finally, ...
* That allows custom component to make sure that loadExtra/loadLess calls from
* client do not stack on not yet updated viewports to result in wrong bounds.
* See JSDoc of RequestInfoPromise.requestInfo and FoundsetChangeEvent.requestInfos
* for more information about determining if a listener event was caused by this call.
*/
loadLessRecordsAsync(negativeOrPositiveCount: number, dontNotifyYet?: boolean): RequestInfoPromise<any>;
/**
* If you queue multiple loadExtraRecordsAsync and loadLessRecordsAsync by using dontNotifyYet = true
* then you can - in the end - send all these requests to server (if any are queued) by calling
* this method. If no requests are queued, calling this method will have no effect.
*/
notifyChanged(): void;
/**
* Sort the foundset by the dataproviders/columns identified by sortColumns.
*
* The name property of each sortColumn can be filled with the dataprovider name the foundset provides
* or specifies. If the foundset is used with a component type (like in table-view) then the name is
* the name of the component on who's first dataprovider property the sort should happen. If the
* foundset is used with another foundset-linked property type (dataprovider/tagstring linked to
* foundsets) then the name you should give in the sortColumn is that property's 'idForFoundset' value
* (for example a record 'dataprovider' property linked to the foundset will be an array of values
* representing the viewport, but it will also have a 'idForFoundset' prop. that can be used for
* sorting in this call; this 'idForFoundset' was added in version 8.0.3).
*
* @param sortColumns an array of JSONObjects { name : dataprovider_id,
* direction : sortDirection }, where the sortDirection can be "asc" or "desc".
* @return a promise that will get resolved when the new sort
* will arrive browser-side. As with any promise you can register success, error
* and finally callbacks.
* See JSDoc of RequestInfoPromise.requestInfo and FoundsetChangeEvent.requestInfos
* for more information about determining if a listener event was caused by this call.
*/
sort(sortColumns: Array<{ name: string; direction: ('asc' | 'desc') }>): RequestInfoPromise<any>;
/**
* Request a selection change of the selected row indexes. Returns a promise that is resolved
* when the client receives the updated selection from the server. If successful, the array
* selectedRowIndexes will also be updated. If the server does not allow the selection change,
* the reject function will get called with the 'old' selection as parameter.
*
* If requestSelectionUpdate is called a second time, before the first call is resolved, the
* first call will be rejected and the caller will receive the string 'canceled' as the value
* for the parameter serverRows.
* E.g.: foundset.requestSelectionUpdate([2,3,4]).then(function(serverRows){},function(serverRows){});
*
* @return a promise that will get resolved when the requested selection update arrived back browser-
* side. As with any promise you can register success, error callbacks, finally, ...
* See JSDoc of RequestInfoPromise.requestInfo and FoundsetChangeEvent.requestInfos
* for more information about determining if a listener event was caused by this call.
*/
requestSelectionUpdate(selectedRowIdxs: number[]): RequestInfoPromise<any>;
/**
* It will send a data update for a cell (a column in a row) in the foundset to the server.
* Please make sure to adjust the viewport value as well not just call this method.
*
* This method is useful if you do not want to use push-to-server SHALLOW in .spec file but do it manually instead, or if
* you have nested JSON object/arrays as cell values and you need to tell the foundset that something nested has changed (DEEP watches are not available in NG2) or
* if you just need a promise to know when the change was done or failed on server.
*
* The calculated pushToServer for the foundset property should be set to 'allow' if you use this method. Then the server will accept
* data changes from this property, but there will be no automatic proxies to detect the changes-by-reference to cell values, so the component uses this call
* to send cell changes instead.
*
* @param rowID the _svyRowId column of the client side row
* @param columnName the name of the column to be updated on server (in that row).
* @param newValue the new data in that cell
* @param oldValue the old data that used to be in that cell
* @return (first versions of this method didn't return anything; more recent ones return this) a promise that will get resolved when the new cell value
* update is done server-side (resolved if ok, rejected if it failed). As with any promise you can register success, error
* and finally callbacks.
*/
columnDataChangedByRowId(rowID: string, columnName: string, newValue: any, oldValue: any): Promise<any>;
/**
* Convenience method that does exactly what #columnDataChangedByRowId does, but based on a row index from the viewport not on that row's ID.
*/
columnDataChanged(rowIndex: number, columnName: string, newValue: any, oldValue: any): Promise<any>;
/**
* Please use columnDataChangedByRowId(...) instead.
*
* @deprecated please use columnDataChangedByRowId(...) instead.
*/
updateViewportRecord(rowID: string, columnID: string, newValue: any, oldValue: any): void;
/**
* Receives a client side rowID (taken from myFoundsetProp.viewPort.rows[idx]._svyRowId)
* and gives a Record reference, an object
* which can be resolved server side to the exact Record via the 'record' property type;
* for example if you call a handler or a servoyapi.callServerSideApi(...) and want
* to give it a Record as parameter and you have the rowID and foundset in your code,
* you can use this method. E.g: servoyapi.callServerSideApi("doSomethingWithRecord",
* [this.myFoundsetProperty.getRecordRefByRowID(clickedRowId)]);
*
* NOTE: if in your component you know the whole row (so myFoundsetProp.viewPort.rows[idx])
* already - not just the rowID - that you want to send you can just give that directly to the
* handler/serverSideApi; you do not need to use this method in that case. E.g:
* // if you have the index inside the viewport
* servoyapi.callServerSideApi("doSomethingWithRecord",
* [this.myFoundsetProperty.viewPort.rows[clickedRowIdx]]);
* // or if you have the row directly
* servoyapi.callServerSideApi("doSomethingWithRecord", [clickedRow]);
*
* This method has been added in Servoy 8.3.
*/
// eslint-disable-next-line @typescript-eslint/ban-types
getRecordRefByRowID(rowId: string): object;
/**
* Sets the preferred viewPort options hint on the server for this foundset, so that the next
* (initial or new) load will automatically return that many rows, even without any of the loadXYZ
* methods above being called.
*
* You can use this when the component size is not known initially and the number of records the
* component wants to load depends on that. As soon as the component knows how many it wants
* initially it can call this method.
*
* These can also be specified initially using the .spec options "initialPreferredViewPortSize" and
* "sendSelectionViewportInitially". But these can be altered at runtime via this method as well
* because they are used/useful in other scenarios as well, not just initially: for example when a
* related foundset changes parent record, when a search/find is performed and so on.
*
* See also the description of "foundsetInitialPageSize" property type for a way to set this
* at design-time (via properties view) or before the form is shown for components that 'page' data.
*
* @param preferredSize the preferred number or rows that the viewport should get automatically
* from the server.
* @param sendViewportWithSelection if this is true, the auto-sent viewport will contain
* the selected row (if any).
* @param centerViewportOnSelected if this is true, the selected row will be in the middle
* of auto-sent viewport if possible. If it is false, then
* the foundset property type will assume a 'paging'
* strategy and will send the page that contains the
* selected row (here the page size is assumed to be
* preferredSize).
*/
setPreferredViewportSize(preferredSize: number, sendViewportWithSelection?: boolean, centerViewportOnSelected?: boolean): void;
/**
* Adds a change listener that will get triggered when server sends changes for this foundset.
*
* @param changeListener the listener to register.
* @return a function to unregister the listener
*/
addChangeListener(changeListener: FoundsetChangeListener): () => void;
removeChangeListener(changeListener: FoundsetChangeListener): void;
}
export interface ViewPort {
startIndex: number;
size: number;
rows: ViewPortRow[];
};
export interface ViewPortRow extends Record<string, any> {
_svyRowId: string;
/** components that use the foundset property are free to use this property however they like; it is not set/used by the foundset impl. */
_cache?: Map<string, any>;
}
/**
* Besides working like a normal Promise that you can use to get notified when some action is done (success/error/finally), chain etc., this promise also
* contains field "requestInfo" which can be set by the user and could later be reported in some listener events back to the user (in case this same action
* is going to trigger those listeners as well).
*
* @since 2021.09
*/
export interface RequestInfoPromise<T> extends Promise<T> {
/**
* You can assign any value to it. The value that you assign - if any - will be given back in the
* event object of any listener that will be triggered as a result of the promise's action. So in
* case the same action, when done, will trigger both the "then" of the Promise and a separate
* listener, that separate listener will contain this "requestInfo" value.
*
* This is useful for some components that want to know if some change (reported by the listener)
* happened due to an action that the component requested or due to changes in the outside world.
* (eg: FoundsetPropertyValue.loadRecordsAsync(...) returns RequestInfoPromise and
* FoundsetChangeEvent.requestInfos array can return that RequestInfoPromise.requestInfo on the
* event that was triggered by that loadRecordsAsync).
*/
requestInfo?: any;
}
foundsetId is controlled by the server; you should not change it
serverSize is controlled by the server; you should not change it
viewPort initial size can be changed using setPreferredViewportSize. When the component detects that more records that it needs are available, it care request viewPort contents using one of the two load async methods
viewPort.startIndex and viewPort.size will have the values requested by the async load methods. But if for example you are using data at the end of the foundset and records are deleted from there then viewport.size will be corrected/decreased from server (as there aren't enough records). A similar thing can happen to viewPort.startIndex. Do not modify these directly as that will have no effect. Use the load async methods instead.
viewPort.rows contains the viewPort data. Each item of the array represents data from a server-side record. Each item will always contain a "_svyRowId" entry that uniquely identifies the record on server. Then there's one entry for every dataprovider that the component needs to use (how those are selected is described below). You should never change the "_svyRowId" entry, but it is possible to change the values of any of the other entries - the new values will be pushed back into the server side record that they belong to (if pushToServer is set on the foundset property to allow/shallow or deep; see "Data synchronization" section of [https://wiki.servoy.com/display/public/DOCS/Specification]).
selectedRowIndexes is an array of selected foundset record indexes. This can get updated by the server if foundset selection changes server side. You can change the contents of this array to change foundset selection (new selection will be pushed to server). However, the preferred way of changing the record selection is by using "requestSelectionUpdate".
sortColumns is a string containing the sort columns of the foundset, like 'columnA desc,columnB asc'
multiselect represents the foundset multiselect state; do not change it as it will not be pushed to server.
columnFormats represents the default column formats for the columns given in the viewport; do not change this - only server pushes this information to the client if asked to do so by the .spec file. It is only present if you specify "provideColumnFormats": true inside the .spec file for this foundset property.
hasMoreRows true if the server side foundset has loaded only a part/chunk of it's records (in case of very large foundsets). In that case there are records even after 'serverSize'. It is controlled and updated by the server; you should not change it.
Adding a change listener
When updates are received from the server for this foundset property, any listeners registered via .addChangeListener() - see above - will get notified.
This was added in order to improve performance by removing the need for angular watches. You no longer need to add lots of angular watches, deep or collection watches in order to be aware of incoming server changes to the foundset property. Each such watch would slow down the page - as watches are triggered a lot for all kinds of user actions or socket traffic. Also the listener can give more detailed information in order to do more granular updates to the UI easier.
Look at this change listener from the client side foundset property's point of view, not from the server's point of view. For example a FoundsetChangeEvent.fullValueChanged does not necessarily mean that the server side foundset has changed by reference. It actually means that all client side contents of the foundset property did change - or might have changed. So it is meant to notify about changes in client side property value.
To add an incoming server change listener to this property type just call:
Adding a change listener (for incomming changes from server)
foundset.addChangeListener((change: FoundsetChangeEvent) => {
// check to see what actually changed and update what is needed in browser
};
If you are using foundset linked properties with your foundset property you might want to add the listener as shown here.
what "changes" parameter can contain:
export interface FoundsetChangeEvent extends ViewportChangeEvent {
/**
* If this change event is caused by one or more calls (by the component) on the IFoundset obj
* (like loadRecordsAsync requestSelectionUpdate and so on), and the caller then assigned a value to
* the returned RequestInfoPromise's "requestInfo" field, then that value will be present in this array.
*
* This is useful for some components that want to know if some change (reported in this FoundsetChangeEvent)
* happened due to an action that the component requested or due to changes in the outside world. (eg:
* IFoundset.loadRecordsAsync(...) returns RequestInfoPromise and FoundsetChangeEvent.requestInfos array can
* contain that RequestInfoPromise.requestInfo on the event that was triggered by that loadRecordsAsync).
*
* @since 2021.09
*/
requestInfos?: any[];
/**
* If a full value update was received from server, this key is set; if both the newValue and
* the oldValue are non-null, the oldValue's reference will be reused (so the reference of the
* foundset property doesn't change, just it's contents are updated) and oldValue given below is
* actually a shallow-copy of the old value's properties/keys; this can help in some component
* implementations.
*/
fullValueChanged?: { oldValue: IFoundsetFieldsOnly; newValue: IFoundset };
// the following keys appear if each of these got updated from server; the names of those
// keys suggest what it was that changed; oldValue and newValue are the values for what changed
// (e.g. new server size and old server size) so not the whole foundset property new/old value
serverFoundsetSizeChanged?: { oldValue: number; newValue: number };
foundsetDefinitionChanged?: boolean;
hasMoreRowsChanged?: { oldValue: boolean; newValue: boolean };
multiSelectChanged?: { oldValue: boolean; newValue: boolean };
columnFormatsChanged?: { oldValue: Record<string, Record<string, unknown>>; newValue: Record<string, Record<string, unknown>> };
sortColumnsChanged?: { oldValue: string; newValue: string };
selectedRowIndexesChanged?: { oldValue: number[]; newValue: number[] };
viewPortStartIndexChanged?: { oldValue: number; newValue: number };
viewPortSizeChanged?: { oldValue: number; newValue: number };
viewportRowsCompletelyChanged?: { oldValue: ViewPortRow[]; newValue: ViewPortRow[] };
userSetSelection?: boolean;
}
export interface ViewportChangeEvent {
// the following keys appear if each of these got updated from server; the names of those
// keys suggest what it was that changed; oldValue and newValue are the values for what changed
// (e.g. new server size and old server size) so not the whole foundset property new/old value
viewportRowsCompletelyChanged?: { oldValue: any[]; newValue: any[] };
// if we received add/remove/change operations on a set of rows from the viewport, this key
// will be set; as seen below, it contains "updates" which is an array that holds a sequence of
// granular update operations to the viewport; the array will hold one or more granular add or remove
// or update operations;
// all the "startIndex" and "endIndex" values below are relative to the viewport's state after all
// previous updates in the array were already processed (so they are NOT relative to the initial state);
// indexes are 0 based
viewportRowsUpdated?: ViewportRowUpdates;
}
export type ViewportChangeListener = (changeEvent: ViewportChangeEvent) => void;
export type FoundsetChangeListener = (changeEvent: FoundsetChangeEvent) => void;
export interface ViewportRowUpdate { type: ChangeType; startIndex: number; endIndex: number }
export type ViewportRowUpdates = ViewportRowUpdate[];
export enum ChangeType {
ROWS_CHANGED = 0,
/**
* When an INSERT happened but viewport size remained the same, it is
* possible that some of the rows that were previously at the end of the viewport
* slided out of it;
* NOTE: insert signifies an insert into the client viewport, not necessarily
* an insert in the foundset itself; for example calling "loadExtraRecordsAsync"
* can result in an insert notification + bigger viewport size notification
*/
ROWS_INSERTED,
/**
* When a DELETE happened inside the viewport but there were more rows available in the
* foundset after current viewport, it is possible that some of those rows
* slided into the viewport;
* NOTE: delete signifies a delete from the client viewport, not necessarily
* a delete in the foundset itself; for example calling "loadLessRecordsAsync" can
* result in a delete notification + smaller viewport size notification
*/
ROWS_DELETED
}
To make the "updates" part above clearer:
Let's say you had in your viewPort (before the incomming changes got applied to it):
row1
row2
row3
row4
row5
Then you got these "updates" from the listener :
updates: [
// "newRow1" inserted
{ type: ChangeType.ROWS_INSERTED,
start: 2, end: 2 },
// update row to "newRow2" contents
{ type: ChangeType.ROWS_CHANGED,
start: 4, end: 4 }
// "row5" slides out of viewport due to
// the initial insert
{ type: ChangeType.ROWS_DELETED,
start: 5, end: 5 },
]
that means that the viewport has changed like this after the first update got applied:
row1
row2
newRow1
row3
row4
row5
and like this after the second update got applied:
row1
row2
newRow1
row3
newRow2
Please note the when your listener is called the actual contents of the viewPort are already updated. So, at that time your viewport already looks like the last version above.
Always make sure to remove listeners when the component is destroyed
It is important to remove the listeners when your component is destroyed. For example if due to a tabpanel switch of tabs your form is hidden, the component and it's angular scope will be destroyed - at which point you have to remove any listeners that you added on model properties (like the foundset property), because the model properties will be reused in the future (for that form when it is shown again) and will keep any listeners in it. When that form will be shown again, it's UI will get recreated - which means your (new) component will probably add the listener again.
If you fail to remove listeners on your component's destroy, it will lead to memory leaks (model properties will keep listeners of obsolete components each time that component's form is hidden, which in turn will prevent those scopes and other objects that they can reference from being garbage collected) and probably weird exceptions (obsolete listeners executing on destroyed scopes of destroyed components).
Defining/using a foundset property with a random set of dataproviders
A web component might want to work with as many dataproviders available in the viewport as the developer wants. Servoy Developer will allow selecting any number of dataproviders of the foundset to be sent to browser web component property value (through the properties view for the foundset typed property; use sub-property 'dataproviders').
For example a component that shows graphical representation of data might allow adding as many 'categories' to it as the developer wants to (each category getting data from one viewport column/dataprovider).
So the component has a property called "myfoundset" that it wants linked to any foundset chosen in ServoyDeveloper, and it allows the developer to choose in properties view any number of dataproviders from the foundset.
browser js
Let's say the developer has chosen a foundset and 3 dataproviders (for example 3 database columns) from it. Those would generate for example a viewPort like this inside the browser property.
Notice the fixed column names: dp0, dp1, ... dp[N-1] where N is the number of foundset dataproviders that the developer has chosen.
Only foundset dataproviders are supported
When using the dataproviders inside foundset property type (static or dynamic), only the record dataproviders are supported - so no form/global variables.
Defining/using a foundset property with a fixed set of dataproviders
A web component can specify in it's .spec file that it requires a foundset property and a fixed number of dataproviders from it. The foundset and required dataproviders are then selected by the developer when creating a solution (using the properties view, 'dataproviders' sub-property).
So the component has a property called "myfoundset" that it wants linked to any foundset chosen in ServoyDeveloper, and it needs two dataproviders from that foundset to be present in the foundset's property viewport.
browser js
Let's say the developer has chosen a foundset and selected for "firstName" a foundset dataprovider (for example a database column called parentFirstName) and for lastName another dataprovider (for example a database column called parentLastName). Those would generate for example a viewport like this inside the browser property:
In this way any foundset dataprovider/column can be mapped to one of the two dataproviders that the component requires. The actual foundset dataprovider name is not even used in browser js.
Defining/using a foundset property that provides default formatting information for columns
A web component can specify in it's .spec file that it requires the foundset property to provide default formatting information for it's columns. We will use a foundset property with fixed number of dataproviders as an example, but it will work the same for other ways of specifying the dataproviders.
So the component has a property called "myfoundset" that it wants linked to any foundset chosen in ServoyDeveloper, and it needs two dataproviders from that foundset to be present in the foundset's property viewport. For each of the two columns it will also receive default formatting information.
browser js
Let's say the developer has chosen a foundset and selected for "image" a foundset dataprovider (for example a database column called 'photo') and for age another dataprovider (for example a database column called 'estimatedStructureAge'). Those would generate a viewport and formatting information similar to the following inside the browser property (note that the column format actual contents might change as needed - this is what Servoy default components receive as well for their component properties):
The formatting information is similar to what default Servoy components get for their format properties, so it could be used in a similar way (for example through FormattingService).
Defining initial load and listener options for a foundset property
A web component can specify in it's .spec file that initially, at first show or each time the foundset gets completely refreshed it wants to automatically receive a number of rows in the viewport. This is useful to avoid some round trips between client and server and send data directly. It is configurable because some components may want to send no records initially while others might need to send many. This is done via the initialPreferredViewPortSize option. Default value is 50.
There is another option sendSelectionViewportInitially which allows a component to say whether this set of initial rows should contain the selected row (if any) or start at first row. This option is "false" by default. When this option is true, the selected row will be in the center of this initial viewPort (if possible) if option centerInitialViewportOnSelected (default: true, available starting with Servoy 2024.12) is true, otherwise a "paging like" viewport containing the selection will be used (it assumes the first page starts at the first record of the foundset).
All of these options can be altered at runtime from browser-side scripting using "setPreferredViewportSize(...)"; see above.
Note that the "foundsetInitialPageSize" property type that can be added "for" a foundset typed property allows you to change the "initialPreferredViewPortSize" (and the "centerInitialViewportOnSelected" would automatically be set to false if that property type is used) from properties view (in developer), or from solution code, but only before showing the form initially. This is useful for components that show pages of records.
A foundset based component can specify (starting with Servoy 2022.03) if it wants to know when the foundset's definition was changed, by adding a foundsetDefinitionListener property to the foundset property with the value true. If that is true, then the foundset's ChangeListener will also get a foundsetDefinitionChanged event passed in when the definition (sql query) of the underlying foundset is changed. This can be handy if you are in a grouped mode and the root foundset only has 200 records loaded but through grouping you really show 1000 records and because of a filter that is applied to the root the first 200 are not changed but the change is somewhere visible after that. Then a grouping table should reflect that by refreshing the groups. Don't use this property if you don't need it because it is not without cost - to calculate the query change and fire the event.
Linking other "foundset aware" property types to a foundset property
Other property types can have content that is 'linked' to foundset records in some way. These property types can be configured in the .spec file as shown below - linking to any other property they have defined with 'foundset' type. When they are linked to a foundset, their javascript value in the browser is no longer only one value, but a viewPort of values (or it will also contain a viewPort of values - the exact content is property type specific) - corresponding to the records loaded in the linked foundset property's viewPort.
In this scenario, the viewPort of the foundset value only contains '_svyRowId' if it's own .spec property configuration doesn't list a dynamic or static list of dataproviders ("dataproviders" : [...] or "dynamicDataproviders": true), and the "foundset aware" property type value will have the viewPort contents in it (check each "foundset aware" type to see how that works, as it could differ from type to type).
Component type (child components that are linked to a foundset - for tables, lists, ...) or custom object types built of/containing other "foundset aware" property types (let's call them 'configurations' - can be used to build lightweight pure HTML tables, lists, ...) are the most common uses in this area.
Examples of foundset aware types are 'component', 'dataprovider', 'tagstring'.
Multiple child components (array of them, notice 'elementConfig' that specifies a config value for each contained element) linked to the foundset. This type of linking is currently used by Servoy's tableviews, listviews and portals:
Have a look at 'component' page to see how these two properties above will look like in browser js.
'Configuration' object for sending other "foundset aware" types as viewPorts follows. In this case the value of those properties - so for example 'myconfigurations[0].mydataprovider' or 'myconfiguration.mydataprovider' will be arrays representing the foundset's viewport, not simple values. If the property is really linked to the record (so not global/form variables but record DP/column) then it will get a special 'idForFoundset' value - for example 'myconfiguration.mydataprovider.idForFoundset' - in it as well; that can be used with the foundset property's sort API. This 'idForFoundset' was added in version 8.0.3. (Note: "forFoundset" usage for "dataprovider" does not yet allow changing the value, but there is a case for making that work)
Foundset change listener & other foundset linked properties (starting with 8.2)
In case you want to use a foundset property type change listener (for incomming changes from server) combined with other foundset linked properties such as dataproviders with "forFoundset", a change of a row on server will send changes both to the foundset property and to the dataprovider properties linked to that foundset. In order to make sure that your foundset notification update code executes after all property changes have been applied (so the dataprovider properties are also up-to-date) you can use:
public changes(changes: FoundsetChangeEvent) {
// wait for all incoming changes to be applied to properties first
this.sabloService.addIncomingMessageHandlingDoneTask(() => {
// now check to see what actually changed and update what is needed in browser
// because even other "forFoundset" properties are up-to-date
});
}
this.myFoundset.addChangeListener(changes);
Runtime property access
At runtime, the foundset property is accessible in (server-side) javascript. If a bean named "myFoundsetBasedBean" has a foundset property named "myFoundset" it can be accessed like this:
elements.myFoundsetBasedBean.myFoundset
That property gives access in scripting to:
the real underlying foundset
to the dataproviders that the property will send to the client webcomponent ( dataproviders contains key-value pairs where key is the name of the column used in web component client side scripting and value is the name of the foundset column attached to that).
Both myFoundset.foundset and myFoundset.dataproviders are read-write properties under the foundset property type.
Setting myFoundset.foundset is only allowed if at design time you selected either "- none -" or a separate foundset for that property (so they are not related to the form directly). Parent form foundset and foundsets related to the form foundset are managed by Servoy automatically and they cannot be set through scripting at runtime. Of course you can alter the contents loaded by those form/related foundsets at runtime, but you cannot change completely the foundset by reference.
Examples:
// elements.myFoundsetBasedBean.myFoundset.foundset gives access to the
// underlying Servoy foundset used by this property
application.output(elements.myFoundsetBasedBean.myFoundset.foundset.getSelectedIndex())
elements.myFoundsetBasedBean.myFoundset.foundset.loadRecords(someQBSelect)
// elements.myFoundsetBasedBean.myFoundset.dataproviders gives access to the
// configured dataproviders of the Servoy foundset property; probably most useful
// in combination with dynamicDataproviders: "true"
elements.myFoundsetBasedBean.myFoundset.dataproviders = {
dp1: "userNickname",
dp2: "userReviewRating",
dp3: "numberOfPurchasedItems"
}
if (!elements.myFoundsetBasedBean.myFoundset.dataproviders.rating)
elements.myFoundsetBasedBean.myFoundset.dataproviders.rating = "userReviewRating";
(Starting with Servoy 8.1.3) Foundset typed properties can be assigned directly to as well. This will create a completely new foundset type property value (if you are not assigning a new foundset). Assigning a completely new foundset value to a foundset type property allows you to configure as well some of the things that are normally defined in the .spec file:
// elements.myFoundsetBasedBean.myFoundset is the foundset typed property
var myNewFoundset = ...; // some Servoy foundset
elements.myFoundsetBasedBean.myFoundset = {
foundset: myNewFoundset,
dataproviders: {
dp1 : "customerName",
dp2 : "city"
},
initialPreferredViewPortSize: 15,
sendSelectionViewportInitially: true,
centerInitialViewportOnSelected: false
};
All keys in the descriptor object above are optional except for "foundset". So if you don't provide "dataproviders", "initialPreferredViewPortSize", "sendSelectionViewportInitially" or "centerInitialViewportOnSelected", default values (see .spec section above) will be used for them. In a similar way you can simply set the foundset directly:
// elements.myFoundsetBasedBean.myFoundset is the foundset typed property
var myNewFoundset = ...; // some Servoy foundset
elements.myFoundsetBasedBean.myFoundset = myNewFoundset; // this will create a new foundset type property value
// that only sends the rowId (no other columns as dataproviders were not specified) and uses defaults for initialPreferredViewPortSize, sendSelectionViewportInitially and centerInitialViewportOnSelected
Combining Foundset Property Type, Foundset Reference Type, Record type and client-to-server scripting calls
You might wonder - "why is setting a complete new foundset into a foundset typed property from server side scripting helpful?". This is helpful for example in implementing more advanced tree-like components, that need to operate with multiple foundsets.
In combination with Foundset Reference type ("foundsetRef"), Record type ("record") and calls from client-side scripting to server-side component scripting, such components can query/create foundsets on server on-the-fly according to different requirements, put them in the model of the component (for example in a foundset array property that is initially empty []). Then they return from the server-side scripting call the "foundsetId" using the Foundset Reference return type (so return a Foundset on an api call that has return type 'foundsetRef'). This means that on the client it has access to the new foundset and it can identify it via the "foundsetId" in the array-of-foundsets-property.
If server-side scripting needs a record from a client-side foundset in order to create it's new foundset (maybe they need to be related in some way), then all the client has to do is send to the server the row from client side foundset property's viewport and on the server it will automatically be translated to a Record by the 'record' property type that is used as argument. Once you have the Record on server you have the foundset as well via Record.foundset.
Similarly, if one needs to send (from client-side) only a foundset as argument to server-side code, it can just give the value of the foundset property to an argument of type 'foundsetRef' and it will automatically be translated on server to a Foundset.
Here is a partial example of what a tree-table might need to do in order to handle large amounts of data properly on all levels:
Client-side .ts
getChildFoundSet(rowObjFromFoundsetsViewport, parentLevelGroupColumnIndex,
newLevelGroupColumnIndex) {
// 'rowObjFromFoundsetsViewport' comes from the foundset (that contributed the expanded row)
// property type's viewport so equivalent to something like
// $scope.model.foundsetProps[i].viewPort.rows[expandedRowIndex]
// 'parentLevelGroupColumnIndex' and 'newLevelGroupColumnIndex' are indexes in
// an array property that holds the grouping column dataproviders
// if 'newLevelGroupColumnIndex' is undefined, then we are requesting tree leafs (not groups)
// and then the server-side query is a bit different
// foundset query needed for leaf level: Select pk from orders where Country = ? and City = ? and ...
// foundset query needed for intermediate grouped level; ie. when you want to expand a country group
// to next level that is grouped by city: SELECT DISTINCT MIN(pk) FROM Customers Where Country =
// "Mexico" GROUP BY City;
// as you can see below I try to send abstract things to the server (the client shouldn't really know
// real datasource names, real column/dataprovider names and so on (those can be determined on server)
// so both client and server code should be done so that these kinds of information never reach the
// client in the first place - only as abstract ids or indexes/names of component properties)
// so server needs to be given the expanded row (it can get the foundset of the Record from that) and
// the groupColumn (index of the column) of the child level if that one is an grouped intermediate level
// otherwise, if it is going to request leafs it should set undefined for "newLevelGroupColumnIndex"
// NOTE: if we could get it nicely from the parent foundset's query there would be no use sending the
// expanded node's group column because that is already available on the server from that foundset's
// query (group by clause)
let childFoundsetPromise;
if (newLevelGroupColumnIndex) {
childFoundsetPromise = this.servoyApi.callServerSideApi("getGroupedChildFoundsetId",
[rowObjFromFoundsetsViewport, parentLevelGroupColumnIndex, newLevelGroupColumnIndex]);
} else {
childFoundsetPromise = this.servoyApi.callServerSideApi("getLeafChildFoundsetId",
[rowObjFromFoundsetsViewport, parentLevelGroupColumnIndex]);
}
childFoundsetPromise.then((childFoundsetId) => {
let childFoundset = this.getFoundSetByFoundsetId(childFoundsetId);
mergeData(..., childFoundset);
}, () => {
// some error happened
(...)
});
}
(...)
getFoundSetByFoundsetId(foundsetId) {
if (this.childFoundsets)
for (let i = 0; i < this.childFoundsets.length; i++) {
if (this.childFoundsets[i].foundsetId == foundsetId)
return this.childFoundsets[i];
return null;
}
Server-side .js
$scope.getGroupedChildFoundsetId = function(parentRecord, parentLevelGroupColumnIndex,
newLevelGroupColumnIndex) {
var parentFoundset = parentRecord.foundset;
var childQuery = parentFoundset.getQuery();
if (parentLevelGroupColumnIndex == undefined) {
// this is the first grouping operation; alter initial query to get all first level groups
(...)
return;
} else {
// this is an intemediate group expand; alter query of parent level for the child level
childQuery.groupBy.clear();
childQuery.groupBy.add(childQuery
.columns[$scope.model.columns[newLevelGroupColumnIndex].dataprovider]);
var parentGroupColumnName = $scope.model.columns[parentLevelGroupColumnIndex].dataprovider;
childQuery.where.add(childQuery.columns[parentGroupColumnName]
.eq(parentRecord[parentGroupColumnName]));
}
var childFoundset = parentFoundset.duplicateFoundSet();
childFoundset.loadRecords(childQuery);
var dps = {};
for (var idx = 0; idx < $scope.model.columns.length; idx++) {
dps["dp" + idx] = $scope.model.columns[idx].dataprovider;
}
$scope.model.childFoundsets.push({
foundset: childFoundset,
dataproviders: dps,
sendSelectionViewportInitially: false,
initialPreferredViewPortSize: 15
}); // send it to client as a foundset property in the array of foundsets
return childFoundset; // return the foudnsetId that points to this foundset (return type
// 'foundsetRed' will make a foundsetID from the childFoundset)
};