DevExtreme jQuery/JS - Custom Sources

Access to a custom data source is configured using the CustomStore component. DevExtreme provides ASP.NET and PHP extensions to configure the CustomStore and implement server-side data processing. You can also use the third-party extension for MongoDB. If these extensions are not suitable, use the instructions below to configure the CustomStore manually.

Load Data

The CustomStore requires the load function. It sends data processing settings to the server and gets processed data back. These settings depend on which remoteOperations are enabled. The following data processing settings apply to the TreeList:

  • Sorting settings: sort

  • Filtering settings: filter

  • Grouping settings: group
    The groupInterval field of the group setting is present only when the widget requests the header filter's data, and only if this data contains numbers or dates. Note that for numbers, the groupInterval option should be specified explicitly.

After receiving these settings, the server should apply them to data and send back an object with the following structure:

{
    data: [{
        key: "Group 1",
        items: [ ... ],  // subgroups or data objects (for the last group when isExpanded = true)
                         // can be null when isExpanded = false and there are no further groups
        count: 3         // count of items in this group; required only when items = null
    },
    ...
    ]
}

If the server has not received the group parameter, the resulting object should be as follows:

{
    data: [ ... ] // result data objects
}

Below is a generalized CustomStore configuration for the TreeList widget:

jQuery
JavaScript
var treeListDataSource = new DevExpress.data.DataSource({
    load: function(loadOptions) {
        var d = $.Deferred(),
                params = {};
        [
            "sort", 
            "filter", 
            "group", 
            "parentIds"
        ].forEach(function(i) {
            if(i in loadOptions && isNotEmpty(loadOptions[i])) 
                params[i] = JSON.stringify(loadOptions[i]);
        });
        $.getJSON("http://mydomain.com/MyDataService", params)
            .done(function(result) {
                // You can process the received data here
                d.resolve(result.data);
            });
        return d.promise();
    }
});
function isNotEmpty(value) {
    return value !== undefined && value !== null && value !== "";
}
$(function() {
    $("#treeListContainer").dxTreeList({
        dataSource: treeListDataSource,
        remoteOperations: {
            filtering: true,
            sorting: true,
            grouping: true
        }
    });
});
Angular
TypeScript
HTML
import { ..., Inject } from "@angular/core";
import { HttpClient, HttpClientModule, HttpParams } from "@angular/common/http";
import { DxTreeListModule } from "devextreme-angular";
import DataSource from "devextreme/data/data_source";
import CustomStore from "devextreme/data/custom_store";
import "rxjs/add/operator/toPromise";
// ...
export class AppComponent {
    treeListDataSource: any = {};
    constructor(@Inject(HttpClient) httpClient: HttpClient) {
        function isNotEmpty(value: any): boolean {
            return value !== undefined && value !== null && value !== "";
        }
        this.treeListDataSource = new DataSource({
            load: (loadOptions) => {
                let params: HttpParams = new HttpParams();
                [
                    "sort", 
                    "filter", 
                    "group", 
                    "parentIds"
                ].forEach(function(i) {
                    if(i in loadOptions && isNotEmpty(loadOptions[i])) 
                        params = params.set(i, JSON.stringify(loadOptions[i]));
                });
                return httpClient.get("http://mydomain.com/MyDataService", { params: params })
                    .toPromise()
                    .then(result => {
                        // You can process the received data here
                        return result.data;
                    });
            }
        });
    }
}
@NgModule({
    imports: [
        // ...
        DxTreeListModule,
        HttpClientModule
    ],
    // ...
})
<dx-tree-list ...
    [dataSource]="treeListDataSource">
    <dxo-remote-operations
        [filtering]="true"
        [sorting]="true"
        [grouping]="true">
    </dxo-remote-operations>
</dx-tree-list>
Vue
<template>
    <DxTreeList ... 
        :data-source="dataSource"
        :remote-operations="remoteOperations" />
</template>
<script>
import DxTreeList from "devextreme-vue/tree-list";
import CustomStore from "devextreme/data/custom_store";
// ...
function isNotEmpty(value) {
    return value !== undefined && value !== null && value !== "";
}
function handleErrors(response) {
    if (!response.ok)
        throw Error(response.statusText);
    return response;
}
const treeListDataSource = {
    store: new CustomStore({
        key: "ID",
        load: (loadOptions) => {
            let params = "?";
            [
                "sort", 
                "filter", 
                "group", 
                "perentIds"
            ].forEach(function(i) {
                if(i in loadOptions && isNotEmpty(loadOptions[i])) 
                    params += `${i}=${JSON.stringify(loadOptions[i])}&`;
            });
            params = params.slice(0, -1);
            return fetch(`https://domain.com/MyDataService${params}`)
                .then(handleErrors)
                .then(response => response.json())
                .then((result) => {
                    return result.data;
                });
        }
    })
}
export default {
    // ...
    data() {
        return {
            dataSource: treeListDataSource,
            remoteOperations: { 
                filtering: true,
                sorting: true,
                grouping: true
            }
        };
    },
    components: {
        // ...
        DxTreeList
    }
}
</script>
React
import React from "react";
import TreeList, { RemoteOperations } from "devextreme-react/tree-list";
import CustomStore from "devextreme/data/custom_store";
// ...
function isNotEmpty(value) {
    return value !== undefined && value !== null && value !== "";
}
function handleErrors(response) {
    if (!response.ok) 
        throw Error(response.statusText);
    return response;
}
const treeListDataSource = {
    store: new CustomStore({
        key: "ID",
        load: (loadOptions) => {
            let params = "?";
            [
                "sort", 
                "filter", 
                "group",
                "parentIds"
            ].forEach(function(i) {
                if(i in loadOptions && isNotEmpty(loadOptions[i])) 
                    params += `${i}=${JSON.stringify(loadOptions[i])}&`;
            });
            params = params.slice(0, -1);
            return fetch(`https://mydomain.com/MyDataService${params}`)
                .then(handleErrors)
                .then(response => response.json())
                .then((result) => {
                    return result.data;
                });
        }
    })
}
class App extends React.Component {
    render() {
        return (
            <TreeList ...
                dataSource={treeListDataSource}>
                <RemoteOperations
                    filtering={true}
                    sorting={true}
                    grouping={true} />
            </TreeList>
        );
    }
}
export default App;

Add, Delete, Update Data

To allow a user to add, delete and update data in the TreeList, assign true to the corresponding field of the editing object.

View Demo

jQuery
JavaScript
$(function(){
    $("#treeListContainer").dxTreeList({
        // ...
        editing: {
            allowUpdating: true, 
            allowDeleting: true, 
            allowAdding: true
        }
    });
});
Angular
HTML
TypeScript
<dx-tree-list ... >
    <dxo-editing
        [allowUpdating]="true"
        [allowDeleting]="true"
        [allowAdding]="true">
    </dxo-editing>
</dx-tree-list>
import { DxTreeListModule } from "devextreme-angular";
// ...
export class AppComponent {
    // ...
}
@NgModule({
    imports: [
        // ...
        DxTreeListModule
    ],
    // ...
})
Vue
<template>
    <DxTreeList ... >
        <DxEditing
            :allow-adding="true"
            :allow-updating="true"
            :allow-deleting="true" />
    </DxTreeList>
</template>
<script>
import { DxTreeList, DxEditing } from "devextreme-vue/tree-list";
export default {
    // ...
    data() {
        return {
            // ...
        };
    },
    components: {
        // ...
        DxTreeList,
        DxEditing
    }
}
</script>
React
import React from "react";
import TreeList, { Editing } from "devextreme-react/tree-list";
// ...
class App extends React.Component {
    render() {
        return (
            <TreeList ... >
                <Editing
                    allowAdding={true}
                    allowDeleting={true}
                    allowUpdating={true} />
            </TreeList>
        );
    }
}
export default App;

With these settings, the TreeList expects that the server can also add, update and delete data. In addition, you need to configure the CustomStore as shown below. Note that in this example, the CustomStore is not declared explicitly. Instead, CustomStore operations are implemented directly in the DataSource configuration object to shorten the example.

jQuery
JavaScript
var treeListDataSource = new DevExpress.data.DataSource({ 
    // ...
    insert: function (values) {
        return $.ajax({
            url: "http://mydomain.com/MyDataService/",
            method: "POST",
            data: values
        })
    },
    remove: function (key) {
        return $.ajax({
            url: "http://mydomain.com/MyDataService/" + encodeURIComponent(key),
            method: "DELETE",
        })
    },
    update: function (key, values) {
        return $.ajax({
            url: "http://mydomain.com/MyDataService/" + encodeURIComponent(key),
            method: "PUT",
            data: values
        })
    }
});

$(function() {
    $("#treeListContainer").dxTreeList({
        dataSource: treeListDataSource,
        // ...
    });
});
Angular
TypeScript
HTML
import { ..., Inject } from "@angular/core";
import { HttpClient, HttpClientModule } from "@angular/common/http";
import { DxTreeListModule } from "devextreme-angular";
import DataSource from "devextreme/data/data_source";
import CustomStore from "devextreme/data/custom_store";
import "rxjs/add/operator/toPromise";
// ...
export class AppComponent {
    treeListDataSource: any = {};
    constructor(@Inject(HttpClient) httpClient: HttpClient) {
        this.treeListDataSource = new DataSource({
            // ...
            insert: function (values) {
                return httpClient.post('http://mydomain.com/MyDataService', values)
                    .toPromise();
            },
            remove: function (key) {
                return httpClient.delete('http://mydomain.com/MyDataService' + encodeURIComponent(key))
                    .toPromise();
            },
            update: function (key, values) {
                return httpClient.put('http://mydomain.com/MyDataService' + encodeURIComponent(key), values)
                    .toPromise();
            }
        });
    }
}
@NgModule({
    imports: [
        // ...
        DxTreeListModule,
        HttpClientModule
    ],
    // ...
})
<dx-tree-list ...
    [dataSource]="treeListDataSource">
</dx-tree-list>
Vue
<template>
    <DxTreeList ... 
        :data-source="dataSource" />
</template>
<script>
import DxTreeList from "devextreme-vue/tree-list";
import CustomStore from "devextreme/data/custom_store";
// ...
function handleErrors(response) {
    if (!response.ok)
        throw Error(response.statusText);
    return response;
}
const treeListDataSource = {
    store: new CustomStore({
        // ...
        insert: (values) => {
            return fetch("https://mydomain.com/MyDataService", {
                method: "POST",
                body: JSON.stringify(values),
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(handleErrors);
        },
        remove: (key) => {
            return fetch(`https://mydomain.com/MyDataService/${encodeURIComponent(key)}`, {
                method: "DELETE"
            }).then(handleErrors);
        },
        update: (key, values) => {
            return fetch(`https://mydomain.com/MyDataService/${encodeURIComponent(key)}`, {
                method: "PUT",
                body: JSON.stringify(values),
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(handleErrors);
        }
    })
}
export default {
    // ...
    data() {
        return {
            dataSource: treeListDataSource
        };
    },
    components: {
        // ...
        DxTreeList
    }
}
</script>
React
import React from "react";
import TreeList from 'devextreme-react/tree-list';
import CustomStore from 'devextreme/data/custom_store';
// ...
function handleErrors(response) {
    if (!response.ok)
        throw Error(response.statusText);
    return response;
}
const treeListDataSource = {
    store: new CustomStore({
        // ...
        insert: (values) => {
            return fetch("https://mydomain.com/MyDataService", {
                method: "POST",
                body: JSON.stringify(values),
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(handleErrors);
        },
        remove: (key) => {
            return fetch(`https://mydomain.com/MyDataService/${ encodeURIComponent(key)}`, {
                method: "DELETE"
            }).then(handleErrors);
        },
        update: (key, values) => {
            return fetch(`https://mydomain.com/MyDataService/${ encodeURIComponent(key)}`, {
                method: "PUT",
                body: JSON.stringify(values),
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(handleErrors);
        }
    })
}
class App extends React.Component {
    render() {
        return (
            <TreeList ...
                dataSource={treeListDataSource}>
            </TreeList>
        );
    }
}
export default App;
See Also