Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic default value for Kendo Grid

I want an auto increment column in my Kendo Grid. This field isn't server side auto increment, because I want the user to see the value and be able to change it.

My current solution is to add a click attribute to Create button and loop over rows to find the highest value and increment it.

But how can I insert this value inside the newly created row? Click event happens before the new row is created.

So there is two possible solution:

  1. Have a variable as default value and update it in my JS code.
  2. Access the newly created row somehow, and update the value.

This is my JS code:

function createClick(id) {
    var grid = $("#" + id).data('kendoGrid');
    var highestRadif = 0;
    grid.tbody.find('>tr').each(function () {
        var dataItem = grid.dataItem(this);
        var radif = dataItem.SRadifReqR;
        highestRadif = highestRadif < radif ? radif : highestRadif;
    })
    alert(++highestRadif);
}
like image 208
Akbari Avatar asked May 24 '15 03:05

Akbari


2 Answers

You can use Grid's edit event to add your new generatedId value to new Grid's model.

This is some explanation from their documentation:

Edit

fired when the user edits or creates a data item.

  • e.container jQuery, jQuery object of the edit container element, which wraps the editing UI.
  • e.model kendo.data.Model, The data item which is going to be edited. Use its isNew method to check if the data item is new (created) or not (edited).
  • e.sender kendo.ui.Grid, The widget instance which fired the event.

I suppose your click have something like this

//generate id code
vm.newId = ++highestRadif; // we need to store generated Id
grid.addRow();

then on edit event

edit: function(e) {
    var model = e.model; // access edited/newly added model
    // model is observable object, use set method to trigger change event
    model.set("id", vm.newId);
}

Note: Your schema model's field must set property editable: true, due to enable us to change model field value using set method. Also if your field schema have validation required, you need to remove it.

model: {
    id: "ProductID",
    fields: {
        ProductID: { editable: true, nullable: true },
    }
}

Sample

like image 119
Dion Dirza Avatar answered Oct 02 '22 02:10

Dion Dirza


I was able to put a function in the datasource schema for this.

schema: {
    model: {
        id: "id",
        fields: {
            currencyType: { defaultValue: getDefaultCurrency },
            invoiceDate: { type: "date" }
        }
    }
}

    function getDefaultCurrency() {
        return _.find(vm.currencyTypes, { id: vm.currencyId });
    };
like image 27
What-About-Bob Avatar answered Oct 02 '22 02:10

What-About-Bob