v5.20192.624
|

ODataCollectionView Class

Extends the CollectionView class to support loading and saving data to and from OData sources.

You can use the ODataCollectionView class to load data from OData services and use it as a data source for any Wijmo controls.

In addition to full CRUD support you get all the CollectionView features including sorting, filtering, paging, and grouping. The sorting, filtering, and paging functions may be performed on the server or on the client.

The code below shows how you can instantiate an ODataCollectionView that selects some fields from the data source and provides sorting on the client. Notice how the 'options' parameter is used to pass in initialization data, which is the same approach used when initializing controls:

var url = 'http://services.odata.org/Northwind/Northwind.svc';
var categories = new wijmo.odata.ODataCollectionView(url, 'Categories', {
  fields: ['CategoryID', 'CategoryName', 'Description'],
  sortOnServer: false
});

The example below uses an ODataCollectionView to load data from a NorthWind OData provider service, and shows the result in a FlexGrid control:

Example

Hierarchy

Constructors

constructor

Properties

canAddNew

canAddNew: boolean

Gets a value that indicates whether a new item can be added to the collection.

canCancelEdit

canCancelEdit: boolean

Gets a value that indicates whether the collection view can discard pending changes and restore the original values of an edited object.

canChangePage

canChangePage: boolean

Gets a value that indicates whether the pageIndex value can change.

canFilter

canFilter: boolean

Gets a value that indicates whether this view supports filtering via the filter property.

canGroup

canGroup: boolean

Gets a value that indicates whether this view supports grouping via the groupDescriptions property.

canRemove

canRemove: boolean

Gets a value that indicates whether items can be removed from the collection.

canSort

canSort: boolean

Gets a value that indicates whether this view supports sorting via the sortDescriptions property.

currentAddItem

currentAddItem: any

Gets the item that is being added during the current add transaction.

currentEditItem

currentEditItem: any

Gets the item that is being edited during the current edit transaction.

currentItem

currentItem: any

Gets or sets the current item in the view.

currentPosition

currentPosition: number

Gets the ordinal position of the current item in the view.

dataTypes

dataTypes: any

Gets or sets a JavaScript object to be used as a map for coercing data types when loading the data.

The object keys represent the field names and the values are DataType values that indicate how the data should be coerced.

For example, the code below creates an ODataCollectionView and specifies that 'Freight' values, which are stored as strings in the database, should be converted into numbers; and that three date fields should be converted into dates:

import { ODataCollectionView } from '@grapecity/wijmo.odata';
var orders = new ODataCollectionView(url, 'Orders', {
  dataTypes: {
    Freight: wijmo.DataType.Number
    OrderDate: wijmo.DataType.Date,
    RequiredDate: wijmo.DataType.Date,
    ShippedDate: wijmo.DataType.Date,
  }
});

This property is useful when the database contains data stored in formats that do not conform to common usage.

In most cases you don't have to provide information about the data types, because the inferDataTypes property handles the conversion of Date values automatically.

If you do provide explicit type information, the inferDataTypes property is not applied. Because of this, any data type information that is provided should be complete, including all fields of type Date.

expand

expand: string

Gets or sets a string that specifies whether related entities should be included in the return data.

This property maps directly to OData's $expand option.

For example, the code below retrieves all the customers and their orders from the database. Each customer entity has an "Orders" field that contains an array of order objects:

var url = 'http://services.odata.org/Northwind/Northwind.svc';
var customersOrders = new wijmo.odata.ODataCollectionView(url, 'Customers', {
  expand: 'Orders'
});

fields

fields: string[]

Gets or sets an array containing the names of the fields to retrieve from the data source.

If this property is set to null or to an empty array, all fields are retrieved.

For example, the code below creates an ODataCollectionView that gets only three fields from the 'Categories' table in the database:

import { ODataCollectionView } from '@grapecity/wijmo.odata';
var categories = new ODataCollectionView(url, 'Categories', {
  fields: ['CategoryID', 'CategoryName', 'Description']
});

filter

filter: IPredicate

Gets or sets a callback used to determine if an item is suitable for inclusion in the view.

The callback function should return true if the item passed in as a parameter should be included in the view.

NOTE: If the filter function needs a scope (i.e. a meaningful 'this' value) remember to set the filter using the 'bind' function to specify the 'this' object. For example:

  collectionView.filter = this._filter.bind(this);

filterDefinition

filterDefinition: string

Gets or sets a string containing an OData filter specification to be used for filtering the data on the server.

The filter definition syntax is described in the OData documentation.

For example, the code below causes the server to return records where the 'CompanyName' field starts with 'A' and ends with 'S':

view.filterDefinition = "startswith(CompanyName, 'A') and endswith(CompanyName, 'B')";

Filter definitions can be generated automatically. For example, the FlexGridFilter component detects whether its data source is an ODataCollectionView and automatically updates both the ODataCollectionView.filter and ODataCollectionView.filterDefinition properties.

Note that the ODataCollectionView.filterDefinition property is applied even if the ODataCollectionView.filterOnServer property is set to false. This allows you to apply server and client filters to the same collection, which can be useful in many scenarios.

For example, the code below uses the ODataCollectionView.filterDefinition property to filter on the server and the ODataCollectionView.filter property to further filter on the client. The collection will show items with names that start with 'C' and have unit prices greater than 20:

var url = 'http://services.odata.org/V4/Northwind/Northwind.svc/';
var data = new wijmo.odata.ODataCollectionView(url, 'Products', {
  oDataVersion: 4,
  filterDefinition: 'startswith(ProductName, \'C\')', // server filter
  filterOnServer: false, // client filter
  filter: function(product) {
    return product.UnitPrice > 20;
  },
});

filterOnServer

filterOnServer: boolean

Gets or sets a value that determines whether filtering should be performed on the server or on the client.

Use the filter property to perform filtering on the client, and use the filterDefinition property to perform filtering on the server.

In some cases it may be desirable to apply independent filters on the client and on the server.

You can achieve this by setting (1) the filterOnServer property to false and the filter property to a filter function (to enable client-side filtering) and (2) the filterDefinition property to a filter string (to enable server-side filtering).

The default value for this property is true.

getError

getError: Function

Gets or sets a callback that determines whether a specific property of an item contains validation errors.

If provided, the callback should take two parameters containing the item and the property to validate, and should return a string describing the error (or null if there are no errors).

For example:

import { CollectionView } from '@grapecity/wijmo';
var view = new CollectionView(data, {
    getError: function (item, property) {
        switch (property) {
            case 'country':
                return countries.indexOf(item.country) < 0
                    ? 'Invalid Country'
                    : null;
            case 'downloads':
            case 'sales':
            case 'expenses':
                return item[property] < 0
                    ? 'Cannot be negative!'
                    : null;
            case 'active':
                return item.active && item.country.match(/US|UK/)
                    ? 'No active items allowed in the US or UK!'
                    : null;
        }
        return null;
    }
});

groupDescriptions

groupDescriptions: ObservableArray

Gets a collection of GroupDescription objects that describe how the items in the collection are grouped in the view.

groups

Gets an array of CollectionViewGroup objects that represents the top-level groups.

inferDataTypes

inferDataTypes: boolean

Gets or sets a value that determines whether fields that contain strings that look like standard date representations should be converted to dates automatically.

This property is set to true by default, because the ODataCollectionView class uses JSON and that format does not support Date objects.

This property has no effect if specific type information is provided using the dataTypes property.

isAddingNew

isAddingNew: boolean

Gets a value that indicates whether an add transaction is in progress.

isEditingItem

isEditingItem: boolean

Gets a value that indicates whether an edit transaction is in progress.

isEmpty

isEmpty: boolean

Gets a value that indicates whether this view contains no items.

isLoading

isLoading: boolean

Gets a value that indicates the ODataCollectionView is currently loading data.

This property can be used to provide progress indicators.

isPageChanging

isPageChanging: boolean

Gets a value that indicates whether the page index is changing.

isUpdating

isUpdating: boolean

Gets a value that indicates whether notifications are currently suspended (see beginUpdate and endUpdate).

itemCount

itemCount: number

Gets the total number of items in the view taking paging into account.

items

items: any[]

Gets items in the view.

itemsAdded

itemsAdded: ObservableArray

Gets an ObservableArray containing the records that were added to the collection since trackChanges was enabled.

itemsEdited

itemsEdited: ObservableArray

Gets an ObservableArray containing the records that were edited in the collection since trackChanges was enabled.

itemsRemoved

itemsRemoved: ObservableArray

Gets an ObservableArray containing the records that were removed from the collection since trackChanges was enabled.

jsonReviver

jsonReviver: Function

Gets or sets a custom reviver function to use when parsing JSON values returned from the server.

If provided, the function must take two parameters (key and value), and must return the parsed value (which can be the same as the original value).

For details about reviver functions, please refer to the documentation for the JSON.parse method.

keys

keys: string[]

Gets or sets an array containing the names of the key fields.

Key fields are required for update operations (add/remove/delete).

newItemCreator

newItemCreator: Function

Gets or sets a function that creates new items for the collection.

If the creator function is not supplied, the CollectionView will try to create an uninitialized item of the appropriate type.

If the creator function is supplied, it should be a function that takes no parameters and returns an initialized object of the proper type for the collection.

oDataVersion

oDataVersion: number

Gets or sets the OData version used by the server.

There are currently four versions of OData services, 1.0 through 4.0. Version 4.0 is used by the latest services, but there are many legacy services still in operation.

If you know what version of OData your service implements, set the oDataVersion property to the appropriate value (1 through 4) when creating the ODataCollectionView (see example below).

var url = 'http://services.odata.org/Northwind/Northwind.svc';
var categories = new wijmo.odata.ODataCollectionView(url, 'Categories', {
  oDataVersion: 1.0, // legacy OData source
  fields: ['CategoryID', 'CategoryName', 'Description'],
  sortOnServer: false
});

If you do not know what version of OData your service implements (perhaps you are writing an OData explorer application), then do not specify the version. In this case, the ODataCollectionView will get this information from the server. This operation requires an extra request, but only once per service URL, so the overhead is small.

pageCount

pageCount: number

Gets the total number of pages.

pageIndex

pageIndex: number

Gets the zero-based index of the current page.

pageOnServer

pageOnServer: boolean

Gets or sets a value that determines whether paging should be performed on the server or on the client.

Use the pageSize property to enable paging.

The default value for this property is true.

pageSize

pageSize: number

Gets or sets the number of items to display on a page.

requestHeaders

requestHeaders: any

Gets or sets an object containing request headers to be used when sending or requesting data.

The most typical use for this property is in scenarios where authentication is required. For example:

import { ODataCollectionView } from '@grapecity/wijmo.odata';
var categories = new ODataCollectionView(serviceUrl, 'Categories', {
  fields: ['Category_ID', 'Category_Name'],
  requestHeaders: { Authorization: db.token }
});

showDatesAsGmt

showDatesAsGmt: boolean

Gets or sets a value that determines whether dates should be adjusted to look like GMT rather than local dates.

sortComparer

sortComparer: Function

Gets or sets a function used to compare values when sorting.

If provided, the sort comparer function should take as parameters two values of any type, and should return -1, 0, or +1 to indicate whether the first value is smaller than, equal to, or greater than the second. If the sort comparer returns null, the standard built-in comparer is used.

This sortComparer property allows you to use custom comparison algorithms that in some cases result in sorting sequences that are more consistent with user's expectations than plain string comparisons.

For example, see Dave Koele's Alphanum algorithm. It breaks up strings into chunks composed of strings or numbers, then sorts number chunks in value order and string chunks in ASCII order. Dave calls the result a "natural sorting order".

The example below shows a typical use for the sortComparer property:

// create a CollectionView with a custom sort comparer
var dataCustomSort = new wijmo.collections.CollectionView(data, {
  sortComparer: function (a, b) {
    return wijmo.isString(a) && wijmo.isString(b)
      ? alphanum(a, b) // use custom comparer for strings
      : null; // use default comparer for everything else
  }
});

The example below shows how you can use an Intl.Collator to control the sort order:

// create a CollectionView that uses an Intl.Collator to sort
var collator = window.Intl ? new Intl.Collator() : null;
var dataCollator = new wijmo.collections.CollectionView(data, {
  sortComparer: function (a, b) {
    return wijmo.isString(a) && wijmo.isString(b) && collator
      ? collator.compare(a, b) // use collator for strings
      : null; // use default comparer for everything else
  }
});

sortConverter

sortConverter: Function

Gets or sets a function used to convert values when sorting.

If provided, the function should take as parameters a SortDescription, a data item, and a value to convert, and should return the converted value.

This property provides a way to customize sorting. For example, the FlexGrid control uses it to sort mapped columns by display value instead of by raw value.

For example, the code below causes a CollectionView to sort the 'country' property, which contains country code integers, using the corresponding country names:

var countries = 'US,Germany,UK,Japan,Italy,Greece'.split(',');
collectionView.sortConverter = function (sd, item, value) {
  if (sd.property == 'countryMapped') {
    value = countries[value]; // convert country id into name
  }
  return value;
}

sortDescriptions

sortDescriptions: ObservableArray

Gets an array of SortDescription objects that describe how the items in the collection are sorted in the view.

sortNullsFirst

sortNullsFirst: boolean

Gets or sets a value that determines whether null values should appear first or last when the collection is sorted (regardless of sort direction).

This property is set to false by default, which causes null values to appear last on the sorted collection. This is also the default behavior in Excel.

sortOnServer

sortOnServer: boolean

Gets or sets a value that determines whether sort operations should be performed on the server or on the client.

Use the sortDescriptions property to specify how the data should be sorted.

The default value for this property is true.

sourceCollection

sourceCollection: any

Gets or sets the underlying (unfiltered and unsorted) collection.

tableName

tableName: string

Gets the name of the table (entity) that this collection is bound to.

totalItemCount

totalItemCount: number

Gets the total number of items in the view before paging is applied.

trackChanges

trackChanges: boolean

Gets or sets a value that determines whether the control should track changes to the data.

If trackChanges is set to true, the CollectionView keeps track of changes to the data and exposes them through the itemsAdded, itemsRemoved, and itemsEdited collections.

Tracking changes is useful in situations where you need to update the server after the user has confirmed that the modifications are valid.

After committing or cancelling changes, use the clearChanges method to clear the itemsAdded, itemsRemoved, and itemsEdited collections.

The CollectionView only tracks changes made when the proper CollectionView methods are used (editItem/commitEdit, addNew/commitNew, and remove). Changes made directly to the data are not tracked.

useStableSort

useStableSort: boolean

Gets or sets whether to use a stable sort algorithm.

Stable sorting algorithms maintain the relative order of records with equal keys. For example, consider a collection of objects with an "Amount" field. If you sort the collection by "Amount", a stable sort will keep the original order of records with the same Amount value.

This property is set to false by default, which causes the CollectionView to use JavaScript's built-in sort method, which is very fast but not stable. Setting the useStableSort property to true increases sort times by 30% to 50%, which can be significant for large collections.

Methods

addNew

  • addNew(): any
  • Creates a new item and adds it to the collection.

    This method takes no parameters. It creates a new item, adds it to the collection, and defers refresh operations until the new item is committed using the commitNew method or canceled using the cancelNew method.

    The code below shows how the addNew method is typically used:

    // create the new item, add it to the collection
    var newItem = view.addNew();
    // initialize the new item
    newItem.id = getFreshId();
    newItem.name = 'New Customer';
    // commit the new item so the view can be refreshed
    view.commitNew();
    

    You can also add new items by pushing them into the sourceCollection and then calling the refresh method. The main advantage of addNew is in user-interactive scenarios (like adding new items in a data grid), because it gives users the ability to cancel the add operation. It also prevents the new item from being sorted or filtered out of view until the add operation is committed.

    Returns any

    The item that was added to the collection.

beginUpdate

  • beginUpdate(): void

cancelEdit

  • cancelEdit(): void

cancelNew

  • cancelNew(): void

clearChanges

  • clearChanges(): void

commitEdit

  • commitEdit(): void

commitNew

  • commitNew(): void

contains

  • contains(item: any): boolean

deferUpdate

  • deferUpdate(fn: Function): void

editItem

  • editItem(item: any): void

endUpdate

  • endUpdate(): void

getAggregate

  • getAggregate(aggType: Aggregate, binding: string, currentPage?: boolean): any
  • Calculates an aggregate value for the items in this collection.

    Parameters

    • aggType: Aggregate

      Type of aggregate to calculate.

    • binding: string

      Property to aggregate on.

    • Optional currentPage: boolean

      Whether to include only items on the current page.

    Returns any

    The aggregate value.

implementsInterface

  • implementsInterface(interfaceName: string): boolean

load

  • load(): void
  • Loads or re-loads the data from the OData source.

    Returns void

moveCurrentTo

  • moveCurrentTo(item: any): boolean

moveCurrentToFirst

  • moveCurrentToFirst(): boolean

moveCurrentToLast

  • moveCurrentToLast(): boolean

moveCurrentToNext

  • moveCurrentToNext(): boolean

moveCurrentToPosition

  • moveCurrentToPosition(index: number): boolean

moveCurrentToPrevious

  • moveCurrentToPrevious(): boolean

moveToFirstPage

  • moveToFirstPage(): boolean

moveToLastPage

  • moveToLastPage(): boolean

moveToNextPage

  • moveToNextPage(): boolean

moveToPage

  • moveToPage(index: number): boolean

moveToPreviousPage

  • moveToPreviousPage(): boolean

onCollectionChanged

onCurrentChanged

onCurrentChanging

onError

onLoaded

onLoading

onPageChanged

onPageChanging

onSourceCollectionChanged

  • onSourceCollectionChanged(e?: EventArgs): void

onSourceCollectionChanging

refresh

  • refresh(): void

remove

  • remove(item: any): void

removeAt

  • removeAt(index: number): void
  • Removes the item at the specified index from the collection.

    Parameters

    • index: number

      Index of the item to be removed from the collection. The index is relative to the view, not to the source collection.

    Returns void

updateFilterDefinition

  • updateFilterDefinition(filterProvider: any): void
  • Updates the filter definition based on a known filter provider such as the FlexGridFilter.

    Parameters

    • filterProvider: any

      Known filter provider, typically an instance of a FlexGridFilter.

    Returns void

Events

collectionChanged

collectionChanged: Event

Occurs when the collection changes.

currentChanged

currentChanged: Event

Occurs after the current item changes.

currentChanging

currentChanging: Event

Occurs before the current item changes.

error

error: Event

Occurs when there is an error reading or writing data.

loaded

loaded: Event

Occurs when the ODataCollectionView finishes loading data.

loading

loading: Event

Occurs when the ODataCollectionView starts loading data.

pageChanged

pageChanged: Event

Occurs after the page index changes.

pageChanging

pageChanging: Event

Occurs before the page index changes.

sourceCollectionChanged

sourceCollectionChanged: Event

Occurs after the value of the sourceCollection property changes.

sourceCollectionChanging

sourceCollectionChanging: Event

Occurs before the value of the sourceCollection property changes.