DGrid Editor - Changing the Displayed Value when Trying to Edit a Text Cell - javascript

I'm using a DGrid editor column to edit the contents of a store. Of the fields that I want to be able to edit, one is an object. When I click on the field to edit it, what I want is for the value displayed in the editor to match the value displayed by the grid when not editing. The cell formatting just shows the value of the object, but when I click on the field to edit it, instead of the object's value, I instead the field is populated with '[object Object]'. I can still edit it (though the results of doing so is that the field will display 'undefined' until I refresh the page, but I could just force a refresh after the change), but can't seem to get it to show what I want.
Here's the set up code:
// build the store
this.postStore = Observable(Memory({
data: posts
}));
var formatCategory = function(object, data, cell) {
cell.innerHTML = object.category.value;
};
var formatAuthor = function(object, data, cell) {
cell.innerHTML = object.author.value;
};
var formatDate = function(object, data, cell) {
cell.innerHTML = new Date(object.dateCreated).toISOString();
};
// the columns displayed in the grid
var columns = [
selector({
field: 'checkbox',
label: ' ',
selectorType: 'radio',
width:33
}),
{
label: "Author",
field: "author",
width: 120,
renderCell: formatAuthor
},
editor({
label: "Title",
field: "title",
editor: "text",
editOn: "click",
width: 200
}),
editor({
label: "Text",
field: "text",
editor: "text",
editOn: "click",
width:500
}, Textarea),
editor({
label: "Category",
field: "category",
editor: "text",
editOn: "click",
width: 150,
renderCell: formatCategory
}),
{
label: "Date",
field: "date",
renderCell: formatDate,
width: 120
}
];
if (this.postGrid) {
this.postGrid.set("store", this.postStore);
} else {
var SelectionGrid = new declare([OnDemandGrid, Selection, Keyboard, editor, selector, DijitRegistry, ColumnResizer]);
this.postGrid = new SelectionGrid({
store: this.postStore,
columns: columns,
selectionMode: 'none',
sort: [{attribute: "date", descending: false}]
}, this.postGridDiv);
this.postGrid.startup();
this.postGrid.on("dgrid-select, dgrid-deselect", lang.hitch(this, this._postSelected));
this.postGrid.on("dgrid-datachange", lang.hitch(this, function(evt){
var cell = this.postGrid.cell(evt);
var post = cell.row.data;
if (cell.column.field === "title") {
post.title = evt.value;
} else if (cell.column.field === "text") {
post.text = evt.value;
} else if (cell.column.field === "category") {
post.category.value = evt.value;
}
this._updatePost(post);
}));

Instead of defining a renderCell function, define a get function (which is used to transform the value before it is even sent to renderCell) and a set function (which is used to transform data back before it's sent to a store when saving edits).
Something like:
get: function (object) {
return object.category.value;
},
set: function (object) {
return { value: object.category };
}
See also the documentation.

Related

How can you get Tabulator to use Select2 header filter?

Following the example here, we've been trying for over a week to get Tabulator working with a Select2 header filter. There is a JS Fiddle here with all the pieces. It seems like the Tabulator filter (which are really just editors) onRendered() function is not even getting called because the console log we have inside it never gets logged.
The select element itself shows up in the header filter, but never gets the Select2 object applied (probably because the onRendered seems to not even be called). If we put the Select2 object outside the onRendered function, it get applied, but then the filter does not get applied after selection is made. There are no console or other errors and we've followed the Tabulator 'example' to the letter, so we are not sure what to try next.
Does anyone know how to get a basic Select2 header filter functioning with Tabulator?
var tableData = [{
id: "1",
topic: "1.1"
},
{
id: "2",
topic: "2.2"
},
];
var select2Editor = function(cell, onRendered, success, cancel, editorParams) {
var editor = document.createElement("select");
var selData = [{
id: '1.1',
text: "One"
}, {
id: "2.2",
text: "Two"
}, {
id: "3.3",
text: "Three"
}, ];
onRendered(function() {
// TODO: map tracks to id and text
console.log('rendered');
$(editor).select2({
data: selData,
minimumResultsForSearch: Infinity,
width: '100%',
minimumInputLength: 0,
//allowClear: true,
});
$(editor).on('change', function(e) {
success($(editor).val());
});
$(editor).on('blur', function(e) {
cancel();
});
});
return editor
};
var columns = [{
title: "ID",
field: "id"
}, {
title: "Topic",
field: "topic",
headerFilter: select2Editor,
}, ];
var table = new Tabulator("#table", {
placeholder: "No Data Found.",
layout: "fitData",
data: tableData,
columns: columns,
});
I'm new to both Tabulator and select2 and I think this is possibly a bad way to do it but it seems like it miiight work.
If you want to use select2 with text input elements, it looks like you need to use the full package.
https://jsfiddle.net/dku41pjy/
var tableData = [{
id: "1",
topic: "1.1"
},
{
id: "2",
topic: "2.2"
},
];
var columns = [{
title: "ID",
field: "id"
}, {
title: "Topic",
field: "topic",
headerFilter: 'select2Editor'
}, ];
var awaiting_render = [];
function do_render({ editor, cell, success, cancel, editorParams }) {
console.log('possibly dodgy onrender');
var selData = [{
id: '',
text: "-- All Topics --"
}, {
id: '1.1',
text: "One"
}, {
id: "2.2",
text: "Two"
}, {
id: "3.3",
text: "Three"
}, ];
$(editor).select2({
data: selData,
//allowClear: true,
});
$(editor).on('change', function(e) {
console.log('chaaaange')
success($(editor).val());
});
$(editor).on('blur', function(e) {
cancel();
});
}
function render_awaiting() {
var to_render = awaiting_render.shift();
do_render(to_render);
if(awaiting_render.length > 0)
render_awaiting();
}
Tabulator.prototype.extendModule("edit", "editors", {
select2Editor:function(cell, onRendered, success, cancel, editorParams) {
console.log(cell);
var editor = document.createElement("input");
editor.type = 'text';
awaiting_render.push({ editor, cell, success, cancel, editorParams });
return editor
},
});
var table = new Tabulator("#table", {
placeholder: "No Data Found.",
layout: "fitData",
data: tableData,
columns: columns,
tableBuilt:function(){
render_awaiting();
},
});
Edit: my suspicion is that onRendered only gets fired when these edit elements are used in cells to sope with the transition between showing just data and showing an editable field.

Kendo grid when create a new row, auto populate fields with values from existing row

I have 5 columns (kendo grid) that gets data from the database. What I'm trying to do is, whenever I add a new row, I want certain columns to be auto populated dynamically.
For example, I have Name, country, state, value, and effDate columns.
Name, country, state fields are editable = false. So users are only able to edit value and effDate fields.
If Name = John, Country = USA, State = Alaska, Value = 123, effDate = 9/11/2019 and when I add a new row, I want Name, country, state fields to be populated with Name - John, Country - USA, State - Alaska. Value and effDate should only be empty so that users can add new data.
I'm currently using template.
I tried this to populate country column, but it's not showing anything.
template: "#= Country #"
Is there a way to pre-populate dynamically when create a new row?
Part of my grid codes model:
{
id: "NameKey",
HouseKey: houseKey,
fields: {
Name: { editable: false },
Country: { editable: false },
State: { editable: false },
Value: {
validation: {
pattern: {
value: "^[0-9.]{0,10}$",
message: "Only numbers"
},
required: {
message: "Value is required"
},
}
},
EffDate: { validation: { required: true }, type: "date", format: "{0:MM/dd/yyyy}" },
},
...
part of the columns
columns: [
{ field: "Name", template: "#=(Name== '') ? 'Fields are auto populated' : Name#", title: "Name", width: 250 },
{ field: "Country", template: "#=(Country== '') ? 'Fields are auto populated' : Countr#", title: "Country", width: 210 },
{ field: "State", template: "#=(StateName == '') ? 'Fields are auto populated' : State#", title:"State", width: 200 },
{ field: "Value", title:"Value", width: 200 },
{
field: "EffDate", title;"Date", template: "#= kendo.toString(kendo.parseDate(data.EffDate, 'yyyy-MM-dd'), 'MM/dd/yyyy') #", width: 140
},
],
You can use the beforeEdit event to achieve that behaviour. That event is called whenever the user tries to edit or create a new entry in the grid. It receives the current model, which you can change according to your needs:
beforeEdit: function(e) {
let model = e.model;
if (model.isNew()) {
model.Name = "John";
model.Country = "USA";
model.State = "Alaska";
}
}
Demo

Store calculated data in Column of Kendo Grid

What I'm trying to do is store some data in a specific column that is calculated by using the data from another column.
I currently have a function that returns the number of available licenses for the given Id in JSON
function getAvailableLicenses(id) {
var url = "/Host/Organization/AvailableLicenses/" + id;
$.get(url, function (data) {
return data.AvailableLicenses;
});
}
How do I go about storing this number in a column named "AvailableLicenses"?
Here is my current Grid:
$("#OrganizationGrid").kendoGrid({
dataSource: viewModel.get("orgDataSource"),
filterable: {
extra: false
},
sortable: true,
pageable: true,
columns: [
{ field: "Id", hidden: true },
{ field: "Name", template: "<a href='/Host/Organization/Detail/#:Id#'>#:Name#</a>" },
{ field: "LicenseNumber", title: "Number of Licenses" },
{ field: null, title: "Available Licenses", template: "#= getAvailableLicenses(Id) #" },
{ field: "LicenseExpiration", title: "License Expiration", format: "{0:MM/dd/yyyy}" },
{ field: "State" },
{ field: "Active" }
],
editable: false
});
As you can see, I tried to create a null column with a template that calls the function for the given Id.
By using Fiddler I can see that the function is indeed being called for all of the rows, but the AvailableLicenses column just displays Undefined for every row.
Is there something I'm missing here to get this to work?
I think the better way to do this is on dataSource parse() function
First: you column configuration must change like this:
{ field: "AvalableLicenses", title: "Available Licenses" },
You alaways can use you template .
And second, inside your dataSource() you can add:
schema: {
parse: function(response) {
for (var i = 0; i < response.length; i++) {
response[i].AvalableLicenses= null;
response[i].AvalableLicenses = getAvailableLicenses(response[i].Id)
}
return response;
}
}
EDIT:
If you prefer using you way, I dont see any problem in your configuration, probably your $.get is returning undefined, or something you don't expect.
For conviniance I did an example working.
http://jsfiddle.net/jwocf897/
Hope this help

Slick Grid - formatters.delete not showing in the grid when adding values by input type text

I have a grid with two columns: name and delete. When the user enters to an input text a value and clicks the button, that value is added to the grid. The problem is that the column "Delete" doesn't work,the column "Delete" doesn't display anything. See the code below:
grid = new Slick.Grid("#mygrid", gridData.Selections, columns, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
$("#btnAddValue").click(function () {
var newItem = { "SelectionName": $("#Name").val() };
$('#pickListName').val('');
var item = newItem;
data = grid.getData();
grid.invalidateRow(data.length);
data.push(item);
grid.updateRowCount();
grid.render();
});
var columns = [
{ id: "SelectionName", name: "Name", field: "SelectionName", width: 420, cssClass: "cell-title", validator: requiredFieldValidator },
{ id: "Id", name: "Delete", field: "Id", width: 80, resizable: false, formatter: Slick.Formatters.Delete }];
var options = {
enableAddRow: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true};
How should solve this?
Thank you

Kendo Grid keydown event

I have initiated a Kendo Grid using Kendo directives. How do I catch the keydown/keypress event of the grid? My final objective is to populate a grid column based on user input of another column. For example, populate the phone number when the first name is entered. For that I believe I have to use the Kendo Grid edit and the keypress events and do a search on the user input, unless there's a better way to do it. Is this possible?
This is how I initialized the grid:
<section id="dashboard-view" class="mainbar" data-ng-controller="dashboard as vm">
....
<div kendo-grid="vm.testGrid" k-options="vm.testGridOptions" k-rebind="vm.testGridDataSource.data" k-on-edit="vm.onEdit(kendoEvent)"></div>
....
</section>
Options defined in my JavaScript file:
vm.testGridOptions = {
columns: [
{ field: "Id", title: "ID" },
{ field: "FirstName", title: "First Name" },
{ field: "LastName", title: "Last Name" },
{ field: "Phone", title: "Phone" },
{ command: ["destroy"] }
],
toolbar: ["create", "save", "cancel"],
dataSource: vm.testGridDataSource,
editable: {
createAt: "bottom"
},
height: 400,
autoBind: false
};
vm.onEdit = function (e) {
//if grid column == Id && keypressed == Tab key
//search
};
The grid is on batch edit mode.
You can find current column/field name based on the index. Then filter the dropdown present in column next to it: (this is just a sample code, please replace DOM ids with your code)
vm.onEdit = function (e) {
var header = vm.thead;//grid header
var index = vm.cellIndex(e.container);//current cell index
var th = $(header).find("th").eq(index);
var colName = $(th).data("field");//fieldname for current cell
var dataItem = e.model;//row model
if(colName=='LastName')
{
var phoneDropDown = e.container.find("#PhoneDropDownId").data("kendoDropDownList");
if (phoneDropDown) {
phoneDropDown.dataSource.filter({ field: "Phone", operator: "eq", value: e.model.LastName });
}
}
};
Since the Kendo Grid doesn't have a native event for this I used the JQuery onBlur event.
vm.onEdit = function (e) {
alert("Edit event fired");
$('input.k-input.k-textbox').blur(function (f) {
alert("Blur event fired");
}
};

Categories

Resources