Redirect to a function by a button defined in Kendogrid


#1

Hi,
I have defined a button in Kendogrid so:
{
“colType”: “command”,
“command”: [
{
“text”: “Mostra gerarchia”,
“className”: “removeFromPlan”,
“click”: {
“type”: “LCI.EnterpriseExportCSV”,
“target”: “SensorsListView”,
“exportFileName”: “Sensors”,
“exportAll”: true
}
}
],
“align”: “center”,
“id”: “showHierarchy”

        }

Now, I have the problem that I can’t pass to a class inserted in click. Practically, command results empty.

The class defined is:

C3.define(‘C3.action.LCI.EnterpriseExportCSV’, {
extend: ‘C3.action.Action’,

config: {
    /**
     * @cfg {C3.view.Component} target The Component or array of Components clear
     */
    target: null,

    /**
     * @cfg {String} displayName The header name in csv
     */
    displayName: 'label',

    /**
     * @cfg {String} dataField The field name in data source
     */
    dataField: 'field',

    /**
     * If we want to export all items in the collection.
     * @type {Boolean}
     */
    exportAll: false,

    /**
     * @cfg {String} exportFileName THe csv file name
     */
    exportFileName: 'dataExport'
},

processFetchResults: function(target, columnsField, csvData,exportFileName)
{
    var datas =  target.get("data");
    var reqConfig = _.clone(datas.map["collection"]._config.values);
    reqConfig.request._config.raw.c3arguments.spec.limit = -1;
    reqConfig.request._config.raw.c3arguments.spec.offset = 0;
    var self = this;
    successFn = function(res)
    {
        records = res.response.get('data');
        _.each(records, function (record) {
            var row = [];
            _.each(columnsField, function (fielddata) {
                var field     = fielddata.field,
                    format    = fielddata.format,
                    value     = self.jsonPathToValue(record,field),
                    exportRaw = fielddata.exportRaw;
                if (C3.util.exists(value) && format && !exportRaw) {
                    value = C3.script.helpers.call(format, value);
                }
                if (_.isString(value)) {
                    value = value.replace(/\n/g, ' ');
                    if (value.indexOf(';') > -1) {
                        value = '"' + value + '"' ;
                    }
                }
                row.push(value);
            });
            csvData.push(row.join(';'));
        });
        csv = new Blob([csvData.join('\n')], { type: 'text/csv;charset=utf-8' });
        saveAs(csv, exportFileName);
    };

    var cloneReq = new C3.network.C3Request({
        c3type: reqConfig.c3type,
        c3function: reqConfig.request._config.raw.c3function,
        c3arguments: reqConfig.request._config.raw.c3arguments,
        environment: reqConfig.request._config.raw.environment,
        success: successFn,
        responseSelector: reqConfig.responseSelector,
        autoExecute: false,
        error: function (res) {
            alert("Error Exporting CSV");
        }
    });

    cloneReq.execute();

},

/**
 * @inheritDoc
 */
dispatch: function (component, args) {
    debugger;
    var dataField = this.get('dataField'),
        displayName = this.get('displayName'),
        target = component.findComponent(this.get('target')),
        columns = target.get('columns.items') || target.get('columns'),
        dataSource = target.getData('collection') || target.get('collection'),
        records, csv, columnHeader = [], columnsField = [], csvData = [],
        exportFileName = C3.script.helpers.appendCSVSuffix(this.get('exportFileName'));

    if (target instanceof C3.view.KendoGrid) {
        _.each(columns, function (column) {
            columnsField.push({
                field: column[dataField],
                format: column.format,
                exportRaw: column.exportRaw
            });
            columnHeader.push(column[displayName]);
        });
    } else {
        _.each(columns, function (column) {
            columnsField.push({
                field: column.get(dataField),
                format: column.get('format')
            });
            columnHeader.push(column.get(displayName));
        });
    }

    if (dataSource.state === 'loaded') {
        csvData.push(columnHeader.join(';'));
        if (this.get('exportAll')) {
        if(!this.get('clientSide'))
        {
            this.processFetchResults(target,columnsField,csvData,exportFileName);
            return;
        }
        else
        {
            records = dataSource.get('items');
        }  

        } else {
            records = dataSource.getSelected();
        }
        _.each(records, function (record) {
            var row = [];
            _.each(columnsField, function (fielddata) {
                var field     = fielddata.field,
                    format    = fielddata.format,
                    value     = record.getData(field),
                    exportRaw = fielddata.exportRaw;
                if (C3.util.exists(value) && format && !exportRaw) {
                    value = C3.script.helpers.call(format, value);
                }
                if (_.isString(value)) {
                    value = value.replace(/\n/g, ' ');
                    if (value.indexOf(';') > -1) {
                        value = '"' + value + '"' ;
                    }
                }
                row.push(value);
            });
            csvData.push(row.join(';'));
        });
        csv = new Blob([csvData.join('\n')], { type: 'text/csv;charset=utf-8' });
        saveAs(csv, exportFileName);
    }
}
,
/**
 * Converts a string path to a value that is existing in a json object.
 * 
 * @param {Object} jsonData Json data to use for searching the value.
 * @param {Object} path the path to use to find the value.
 * @returns {valueOfThePath|undefined}
 */
jsonPathToValue: function(jsonData, path) {
    if (!(jsonData instanceof Object) || typeof (path) === "undefined") {
        throw "Not valid argument:jsonData:" + jsonData + ", path:" + path;
    }
    path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    path = path.replace(/^\./, ''); // strip a leading dot
    var pathArray = path.split('.');
    for (var i = 0, n = pathArray.length; i < n; ++i) {
        var key = pathArray[i];
        if (key in jsonData) {
            if (jsonData[key] !== null) {
                jsonData = jsonData[key];
            } else {
                return null;
            }
        } else {
            return '';
        }
    }
    return jsonData;
}  

});

Does a method exist that resolves it?


#2

Hi @Vincenzo,

I’ve never seen a click defined inline with the grid column configuration, so I don’t think that will work. What I have seen is defining a "command" colType with a special className (like you have), and then a corresponding behavior defined at the component level or its parent component.

So your grid column would look like:

{
  "colType": "command",
  "command": [
    {
      "text": "Mostra gerarchia",
      "className": "removeFromPlan"
    }
  ],
  "align": "center",
  "id": "showHierarchy"
}

And then at the grid component level (or the component that contains it), you would define a behavior like this:

"behavior": [
  {
    "query": "$ .removeFromPlan",
    "trigger": "click",
    "action": {
      "type": "LCI.EnterpriseExportCSV",
      "target": "SensorsListView",
      "exportFileName": "Sensors",
      "exportAll": true
    }
  }
]

And in C3 UI terminology, C3.action.LCI.EnterpriseExportCSV is called an “action”.