getting devextreme dataGrid to work with webpack - npm

I am just trying to get a simple demo app working using webpack and devextreme components. I built the app first without webpack and it all worked fine. I am now trying to refactor it to use webpack. I can't get the dataGrid page to work I am just getting a console error .dxDataGrid is not a function. If anyone can see where I have gone wrong any ideas would be great.
var $ = require('jquery');
var ko = require('knockout');
require('devextreme/integration/knockout');
require('devextreme/ui/data_grid');
require('devextreme/ui/form');
require('devextreme/ui/text_box');
require('devextreme/ui/button');
require('devextreme/ui/check_box');
require('devextreme/ui/popup');
var AspNetData = require('devextreme-aspnet-data/js/dx.aspnet.data');
$(function () {
var url = CONST_URL + 'Login/';
$("#userGrid").dxDataGrid({
showColumnLines: false,
showRowLines: true,
rowAlternationEnabled: true,
columnHidingEnabled: true,
showBorders: true,
dataSource: AspNetData.createStore({
key: "id",
loadUrl: url + "GetUsers",
insertUrl: url + "UpsertUser",
updateUrl: url + "UpsertUser",
deleteUrl: url + "DeleteUser"
}),
columnChooser: {
//enabled: true,
//mode: "select"
},
paging: {
pageSize: 5
},
pager: {
showPageSizeSelector: true,
//allowedPageSizes: [5, 10, 15],
showInfo: true
},
editing: {
allowUpdating: true,
mode: "form",
allowAdding: true,
allowDeleting: true
},
columns: [
{
dataField: "id",
caption: "User ID",
formItem: {
visible: false
},
hidingPriority: 1
},
{
dataField: "username",
caption: "Username",
validationRules: [{
type: "required",
message: "Username"
}, {
type: 'pattern',
pattern: /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/,
message: 'Please supply a valid email address.'
}],
formItem: {
visible: true
},
hidingPriority: 3
},
{
dataField: "password",
caption: "password",
mode: "password",
validationRules: [{
type: "required",
message: "Password",
}, {
type: "stringLength",
min: 8,
message: "Your password must have at least 8 characters."
}],
visible: false,
formItem: {
visible: true
}
},
{
dataField: "date_created",
caption: "Date Created",
formItem: {
visible: false
},
hidingPriority: 2
},
{
dataField: "is_locked",
caption: "User Locked Out",
hidingPriority: 0
}],
onEditorPreparing: function (e) {
if (e.dataField === "password") {
e.editorOptions.mode = 'password';
}
if (e.parentType === "dataRow" && e.dataField === "username") {
setTimeout(function () { $(e.editorElement).dxTextBox("focus") }, 100);
}
},
onToolbarPreparing: function (e) {
var dataGrid = e.component;
e.toolbarOptions.items.unshift({
location: "before",
template: function () {
return $("<div/>")
.append(
$("<h2 />")
.text("User List")
);
}
});
},
onEditingStart: function (e) {
isUpdateCanceled = false;
e.component.columnOption("date_created", "allowEditing", false);
e.component.columnOption("id", "allowEditing", false);
},
onInitNewRow: function (e) {
isUpdateCanceled = false;
e.component.columnOption("date_created", "allowEditing", false);
e.component.columnOption("id", "allowEditing", false);
e.component.columnOption("is_locked", "allowEditing", false);
},
onContentReady: function (e) {
var saveButton = $(".dx-button[aria-label='Save']");
if (saveButton.length > 0)
saveButton.click(function (event) {
console.log(e.component);
if (!isUpdateCanceled) {
upsert(e.component);
event.stopPropagation();
}
});
}
});
});

Devexpress team gave me the solution. I thought I would post it here in case anyone else has the same issue. I was missing the jquery intergration.
require('devextreme/integration/jquery');

Related

I need ordering the user's likes with start current user like in prisma

I am using prisma.
I need to get likes of posts with last 3 liked user .
So I want to get these user that starts with current user like .
Becouse I can check is liked this post in frontend part easly.
How can I do this issue with prisma.
Thanks for your help :)
let posts = await prisma.posts.findMany({
where: {
active: true,
},
orderBy: {
id: 'desc'
},
select: {
id: true,
userId: true,
text: true,
files: {
select: {
files: true
}
},
createdAt: true,
active: true,
user: {
select: {
id: true,
fullName: true,
profileImg: {
select: {
url: true
}
}
},
},
_count: {
select: {
likes: true,
comments: true
}
},
likes: {
orderBy: {
id: 'desc'
},
select: {
postId: true,
userId: true,
user: {
select: {
id: true,
fullName: true,
profileImg: {
select: {
url: true
}
}
},
}
},
take: 3
}
},
})

Disable the pagination navigation buttons during an API request in AG Grid

How could I disable the pagination navigation buttons during an API request in AG Grid? I am using Vue.js if it matters.
E.g. here I would like to disable the controls while the API request is in progress. How could I do that?
var checkboxSelection = function (params) {
// we put checkbox on the name if we are not doing grouping
return params.columnApi.getRowGroupColumns().length === 0;
};
var headerCheckboxSelection = function (params) {
// we put checkbox on the name if we are not doing grouping
return params.columnApi.getRowGroupColumns().length === 0;
};
const columnDefs = [
{
field: 'athlete',
minWidth: 170,
checkboxSelection: checkboxSelection,
headerCheckboxSelection: headerCheckboxSelection,
},
{ field: 'age' },
{ field: 'country' },
{ field: 'year' },
{ field: 'date' },
{ field: 'sport' },
{ field: 'gold' },
{ field: 'silver' },
{ field: 'bronze' },
{ field: 'total' },
];
var autoGroupColumnDef = {
headerName: 'Group',
minWidth: 170,
field: 'athlete',
valueGetter: (params) => {
if (params.node.group) {
return params.node.key;
} else {
return params.data[params.colDef.field];
}
},
headerCheckboxSelection: true,
// headerCheckboxSelectionFilteredOnly: true,
cellRenderer: 'agGroupCellRenderer',
cellRendererParams: {
checkbox: true,
},
};
const gridOptions = {
defaultColDef: {
editable: true,
enableRowGroup: true,
enablePivot: true,
enableValue: true,
sortable: true,
resizable: true,
filter: true,
flex: 1,
minWidth: 100,
},
suppressRowClickSelection: true,
groupSelectsChildren: true,
// debug: true,
rowSelection: 'multiple',
rowGroupPanelShow: 'always',
pivotPanelShow: 'always',
enableRangeSelection: true,
columnDefs: columnDefs,
paginationAutoPageSize: true,
pagination: true,
autoGroupColumnDef: autoGroupColumnDef,
};
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function () {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
fetch('https://www.ag-grid.com/example-assets/olympic-winners.json')
.then((response) => response.json())
.then((data) => gridOptions.api.setRowData(data));
});
I found the example above in the documentation.

jsgrid need functionality to upload and show image

I am using jsGrid for showing data from database. But I am stuck with a problem.
All text field or select field are rendering correctly. But I need to add a custom field with functionality to add image on edit (when no image added) a row and show image on the field while page load using jsGrid. I searched the web but not find any solution to solve my issue.
This is how it could be implemented:
var data = [
{ Name: "John", Img: "http://placehold.it/250x250" },
{ Name: "Jimmy", Img: "http://placehold.it/250x250" },
{ Name: "Tom", Img: "http://placehold.it/250x250" },
{ Name: "Frank", Img: "http://placehold.it/250x250" },
{ Name: "Peter", Img: "http://placehold.it/250x250" }
];
$("#dialog").dialog({
modal: true,
autoOpen: false,
position: {
my: "center",
at: "center",
of: $("#jsgrid")
}
});
$("#jsgrid").jsGrid({
autoload: true,
width: 350,
filtering: true,
inserting: true,
controller: {
loadData: function(filter) {
return !filter.Name
? data
: $.grep(data, function(item) { return item.Name.indexOf(filter.Name) > -1; });
// use ajax request to load data from the server
/*
return $.ajax({
method: "GET",
url: "/YourUrlToAddItemFilteringScript",
data: filter
});
*/
},
insertItem: function(insertingItem) {
var formData = new FormData();
formData.append("Name", insertingItem.Name);
formData.append("Img[]", insertingItem.Img, insertingItem.Img.name);
return $.ajax({
method: "post",
type: "POST",
url: "/YourUrlToAddItemAndSaveImage",
data: formData,
contentType: false,
processData: false
});
}
},
fields: [
{
name: "Img",
itemTemplate: function(val, item) {
return $("<img>").attr("src", val).css({ height: 50, width: 50 }).on("click", function() {
$("#imagePreview").attr("src", item.Img);
$("#dialog").dialog("open");
});
},
insertTemplate: function() {
var insertControl = this.insertControl = $("<input>").prop("type", "file");
return insertControl;
},
insertValue: function() {
return this.insertControl[0].files[0];
},
align: "center",
width: 120
},
{ type: "text", name: "Name" },
{ type: "control", editButton: false }
]
});
Checkout the working fiddle http://jsfiddle.net/tabalinas/ccy9u7pa/16/
According issue on GitHub: https://github.com/tabalinas/jsgrid/issues/107

Event that is taking place after inline edit

I have jqgrid, which sends row's data to another view (MVC4) when row is selected. But when I edit row's info (I'm using inline edit) this view doesn't changed. And I can't find event that is taking place after inline edit. This is js, what should I change to change my view after row editing
$(function () {
$("#GridTable").jqGrid({
url: "/Goods/GoodsList",
editurl: "/Goods/Edit",
datatype: 'json',
mtype: 'Get',
colNames: ['GoodId', 'Имя', 'Цена'],
colModel: [
{ key: true, hidden: true, name: 'GoodId', index: 'GoodId', editable: true },
{
key: false, name: 'GoodName', index: 'GoodName', editable: true, sortable: true,
editrules: {
required: true, custom: true, custom_func: notATag
}
},
{
key: false, name: 'Price', index: 'Price', editable: true, sortable: true, formatter: numFormat,
unformat: numUnformat,
//sorttype: 'float',
editrules: { required: true, custom: true, custom_func: figureValid}
}, ],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 25, 50, 100],
height: '100%',
viewrecords: true,
caption: 'Список товаров',
sortable: true,
emptyrecords: 'No records to display',
cellsubmit : 'remote',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
//to get good's full view when row is selected
onSelectRow:
function () {
var myGrid = $('#GridTable'),
selRowId = myGrid.jqGrid('getGridParam', 'selrow'),
celValue = myGrid.jqGrid('getCell', selRowId, 'GoodId');
$.ajax({
url: "/Goods/DetailInfo",
type: "GET",
data: { id: celValue }
})
.done(function (partialViewResult) {
$("#goodDetInfo").html(partialViewResult);
});
},
//to change good's full view after row deleting
loadComplete: function(data){
var myGrid = $('#GridTable'),
selRowId = myGrid.jqGrid('getGridParam', 'selrow'),
celValue = myGrid.jqGrid('getCell', selRowId, 'GoodId');
$.ajax({
url: "/Goods/DetailInfo",
type: "GET",
data: { id: celValue }
})
.done(function (partialViewResult) {
$("#goodDetInfo").html(partialViewResult);
});
},
autowidth: true,
multiselect: false
}).navGrid('#pager', { edit: false, add: true, del: true, search: false, refresh: true },
{
// edit options
zIndex: 100,
url: '/Goods/Edit',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
var myGrid = $('#GridTable'),
selRowId = myGrid.jqGrid('getGridParam', 'selrow'),
celValue = myGrid.jqGrid('getCell', selRowId, 'GoodId');
$.ajax({
url: "/Goods/DetailInfo",
type: "GET",
data: { id: celValue }
})
.done(function (partialViewResult) {
$("#goodDetInfo").html(partialViewResult);
});
}
},
{
// add options
zIndex: 100,
url: "/Goods/Create",
closeOnEscape: true,
closeAfterAdd: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
// delete options
zIndex: 100,
url: "/Goods/Delete",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
$('#GridTable').inlineNav('#pager', {
edit: true,
add: false,
del: false,
cancel: true,
editParams: {
keys: true,
afterSubmit: function (response) {
if (response.responseText) {
alert(response.responseText);
}
var myGrid = $('#GridTable'),
selRowId = myGrid.jqGrid('getGridParam', 'selrow'),
celValue = myGrid.jqGrid('getCell', selRowId, 'GoodId');
$.ajax({
url: "/Goods/DetailInfo",
type: "GET",
data: { id: celValue }
})
.done(function (partialViewResult) {
$("#goodDetInfo").html(partialViewResult);
});
}
},
});
});
The properties and callback function of editParams parameter of inlineNav can be found here. What you need is probably aftersavefunc or successfunc instead of afterSubmit, which exist only in form editing method (see here). The parameters of aftersavefunc or successfunc callbacks are described here (as parameters of saveRow), but the parameters depend on the version of jqGrid, which you use and from the fork of jqGrid (free jqGrid, commercial Guriddo jqGrid JS or an old jqGrid in version <=4.7). I develop free jqGrid fork and I would recommend you to use the current (4.13.3) version of free jqGrid.

How to bind .Url(Url.Action()) property to toolbar in kendo ui grid(html)

i have a grid developed using kendo ui and asp.net mvc4 razor.in there i have used the html syntax for kendo grid instead of asp.net mvc.
this is the code of my grid
<div id="example" class="k-content">
<div id="batchgrid">
</div>
</div>
<script type="text/javascript" lang="javascript">
$("#batchGrid").click(function () {
var crudServiceBaseUrl = "http://demos.kendoui.com/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true} },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
UnitsInStock: { type: "number", validation: { min: 0, required: true} },
Discontinued: { type: "boolean" },
TotalStock: { type: "number" }
}
}
},
// group: {
// field: "UnitPrice", aggregates: [
// { field: "UnitPrice", aggregate: "sum" },
// { field: "TotalStock", aggregate: "sum" }
// ]
// },
aggregate: [{ field: "TotalStock", aggregate: "sum"}]
});
$("#batchgrid").kendoGrid({
dataSource: dataSource,
dataBound: onDataBound,
navigatable: true,
filterable: {
messages: {
and: "And",
or: "Or",
filter: "Apply filter",
clear: "Clear filter",
info: "Filter by"
},
extra: false, //do not show extra filters
operators: { // redefine the string operators
string: {
contains: "Contains",
doesnotcontain: "Doesn't contain",
startswith: "Starts With",
endswith: "Ends"
},
number: {
eq: "Is Equal To",
neq: "Not equal to",
gte: "Greater than or equal to",
lte: "Less than or equal to",
gt: "Greater than",
lt: "Less than"
}
}
},
reorderable: true, //not working
selectable: "multiple",
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50, 100]
},
height: 430,
width: 300,
toolbar: [
{
name: "my-create",
text: "Add new record"
},
{
name: "save",
text: "save changes"
},
{
name: "cancel",
text: "cancel changes"
},
{
name: "export",
text: "Export To Excel"
}
],
columns: [
// { field: "ProductID", title: "No", width: "90px" },
{title: "No", template: "#= ++record #", width: 45 },
{ field: "ProductName", title: "Product Name", width: "350px" },
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
{ field: "UnitsInStock", title: "Units In Stock", width: "150px" },
{ field: "Discontinued", title: "Purchase", width: "110px" },
{ field: "TotalStock", title: "Total Stock", width: "150px", footerTemplate: "Total : #= kendo.toString(sum, 'C') #", format: "{0:c2}" }
//{ command: ["destroy"], title: " ", width: "175px" }
],
export: {
cssClass: "k-grid-export-image",
title: "people",
createUrl: "/Home/ExportToExcel",
downloadUrl: "/Home/GetExcelFile"
},
groupable: {
messages: {
empty: "Drop columns here"
}
}, //not working
columnMenu: {
sortable: true,
filterable: true,
messages: {
columns: "Hide/Show Columns",
filter: "Apply filter",
sortAscending: "Sort (asc)",
sortDescending: "Sort (desc)"
}
},
resizable: true,
dataBinding: function () {
record = (this.dataSource.page() - 1) * this.dataSource.pageSize();
},
sortable: {
mode: "multiple"
},
sort: { field: "ProductID", dir: "asc" },
editable: { mode: "incell", createAt: "bottom" }
});
//custom global variables
newRowAdded = false;
checkedOnce = false;
var grid = $("#batchgrid").data("kendoGrid");
$(".k-grid-my-create", grid.element).on("click", function (e) {
window.newRowAdded = true;
var dataSource = grid.dataSource;
var total = dataSource.data().length;
dataSource.insert(total, {});
dataSource.page(dataSource.totalPages());
grid.editRow(grid.tbody.children().last());
});
grid.bind("saveChanges", function () {
window.newRowAdded = false;
// var grid = $("#batchgrid").data("kendoGrid");
// grid.dataSource.sort({ field: "ProductID", dir: "asc" });
// GetValOf();
// var grid = $('#batchgrid').data("kendoGrid");
// var total = 0;
// $.each(grid.dataSource.view(), function () {
// total += this.TotalStock;
// });
// alert(total);
});
grid.bind("cancelChanges", function () {
window.newRowAdded = false;
});
$(".k-grid-export", "#batchgrid").bind("click", function (ev) {
// your code
// alert("Hello");
var grid = $("#batchgrid").data("kendoGrid");
grid.dataSource.pageSize(parseInt($("#batchgrid").data("kendoGrid").dataSource.data().length));
excelImport();
});
});
</script>
but i got some example code for importing grid data to excel and in there they used asp.net mvc syntax.
here is the code.
#(
Html.Kendo().Grid(Model).Name("Grid")
.DataSource(ds => ds.Ajax()
.Model(m =>
{
m.Id(p=>p.ProductID);
})
.Read(r => r.Action("Read", "Home"))
)
.ToolBar(toolBar =>
toolBar.Custom()
.Text("Export To Excel")
.HtmlAttributes(new { id = "export" })
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
)
.Columns(columns =>
{
columns.Bound(p => p.ProductID);
columns.Bound(p => p.ProductName);
columns.Bound(p => p.UnitPrice).Format("{0:c}");
columns.Bound(p => p.QuantityPerUnit);
})
.Events(ev => ev.DataBound("onDataBound"))
.Pageable()
.Sortable()
.Filterable()
)
but my problem is i need to add below line of code to my grid(in first code mentioned above).
.ToolBar(toolBar =>
toolBar.Custom()
.Text("Export To Excel")
.HtmlAttributes(new { id = "export" })
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
)
but im stucked with this single line
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
can somebody please tell me that how to use this code in my html grid..
Write Toolbar manual
<div class="k-toolbar k-grid-toolbar k-grid-top">
<a class="k-button k-button-icontext " id="exportCsv" href="/Home/ExportToCsv?take=50&skip=0&page=1&pageSize=10&filter=~&sort=" id="exportToCSV"><span></span>Export CSV</a>
<a class="k-button k-button-icontext " id="exportXls" href="/Home/ExportToXls?take=50&skip=0&pageSize=10&filter=~&sort=" id="exportToExcel"><span></span>Export Excel</a>
</div>
then add databound to kendoGrid
....
editable: false, // enable editing
sortable: true,
filterable: true,
scrollable: false,
dataBound: onDataBound,
columns: [.....
then write 'onDataBound' function
<script>
function onDataBound(e) {
var grid = $('#grid').data('kendoGrid');
var take = grid.dataSource.take();
var skip = grid.dataSource.skip();
var page = grid.dataSource.page();
var sort = grid.dataSource.sort();
var pageSize = grid.dataSource.pageSize();
var filter = JSON.stringify(grid.dataSource.filter());
// Get the export link as jQuery object
var $exportLink = $('#exportXls');
// Get its 'href' attribute - the URL where it would navigate to
var href = $exportLink.attr('href');
// Update the 'take' parameter with the grid's current page
href = href.replace(/take=([^&]*)/, 'take=' + take || '~');
// Update the 'skip' parameter with the grid's current page
href = href.replace(/skip=([^&]*)/, 'skip=' + skip || '~');
// Update the 'page' parameter with the grid's current page
href = href.replace(/page=([^&]*)/, 'page=' + page || '~');
// Update the 'sort' parameter with the grid's current sort descriptor
href = href.replace(/sort=([^&]*)/, 'sort=' + sort || '~');
// Update the 'pageSize' parameter with the grid's current pageSize
href = href.replace(/pageSize=([^&]*)/, 'pageSize=' + pageSize);
//update filter descriptor with the filters applied
href = href.replace(/filter=([^&]*)/, 'filter=' + (filter || '~'));
// Update the 'href' attribute
$exportLink.attr('href', href);
$('#exportCsv').attr('href', href.replace('ExportToXls', 'ExportToCsv'));
}
</script>
And this is the Action, and parameters
public FileResult ExportToXls(int take, int skip, IEnumerable<Sort> sort, string filter)
{
try
{
Filter objfilter = JsonConvert.DeserializeObject<Filter>(filter);
var lstContactFormData = XmlData.GetIletisimBilgileri().OrderByDescending(i => i.tarih);
//Get the data representing the current grid state - page, sort and filter
//IEnumerable products = _db.Products.ToDataSourceResult(request).Data;
IEnumerable contactsDatas = lstContactFormData.AsQueryable().ToDataSourceResult(take, skip, sort, objfilter).Data;
...
...