ag-grid agTextColumnFilter defaultOption - ag-grid-ng2

I have to set default value to ag-grid agTextColumnFilter.
I order to do that I I added filterParams and defaultOption, but the filter does't works after my changes.
gridOptions = {
enableFilter: true,
...
columnDefs: [
{headerName: "Status", field: "status", filter: "agTextColumnFilter",
filterParams: { defaultOption: { notContains: 'default text'} } }
]
}
I am using this documentation.
https://www.ag-grid.com/javascript-grid-filter-text/

Just do this when you are pushing data in ag-grid
columnData.push({
headerName: "Site Name",
field: "siteName",
dataType: "string",
enableValue: true,
filter: "agTextColumnFilter",
editable: false,
});

Related

Kendo Filter is Not Working on the Date Column

I have an grid with date column in which I applied a filterable option and i did not get any results when I filter.
My grid:
var element = $("#grid").kendoGrid({
dataSource: {
data: gridDataSource,
schema: {
model: {
fields: {
Date: { type: "date", editable: false },
}
}
}
},
scrollable: true,
filterable : true,
columns: [
{
"field": "Date", "title": "Date", "format": "{0:MM/dd/yyyy}", filterable : {ui: function (e) {e.kendoDatePicker({format: "MM/dd/yyyy"})}}, width: "100px" }],
});
Probably is missing .data("kendoGrid"); in end of kendogrid() declaration.
For convinience I did an working example.
Hope this help
ps: Filter by 1966/01/27 in example to check.

in jqgrid : I want to show an empty grid with no pagination and display a message "no records found" if no records

I need to show an empty grid with no pagination and display a message "You have no records found" if empty results in jqGrid.i'm pretty new to this jqgrid.
I have added the code as below. Please Find the Oleg Demo1, Demo2
$(function () {
var $grid = $("#oversight-sample"),
//mydata = [{actions: "a", url: "http://stackoverflow.com/q/24609566/315935", created: "7/7/2014"}];
mydata = [];
emptyMsgDiv = $("<div><span style='color:red;font-size:24px'>You have no records found</span></div>");
$grid.jqGrid({
//autowidth: true,
caption: "Evaluated URLs",
colNames: ["Actions", "URL", "Fetch Date"],
colModel: [
{ name: "actions", align: "center", title: false, width: 60, resizable: false, sortable: false },
{ name: "url", width: 400 },
{ name: "created", align: "center", width: 125, sorttype: "date" }
],
data: mydata,
datatype: "local",
emptyrecords: "0 records found",
localReader: {
page: function (obj) {
return (obj.page === 0 || obj.page === undefined) ? "0" : obj.page;
}
},
loadComplete: function () {
var ts = this;
if (ts.p.reccount === 0) {
$(this).hide();
emptyMsgDiv.show();
} else {
$(this).show();
emptyMsgDiv.hide();
}
},
height: "auto",
sortname: "created",
toppager: true,
pager: "#url-pager",
viewrecords: true
});
// place div with empty message insde of bdiv
emptyMsgDiv.insertAfter($grid.parent());
});
<table id="oversight-sample"><tbody><tr><td></td></tr></tbody></table>
<div id="url-pager"></div>
Here is the link to fiddler with the 'No records found' message. I hope it will give you an idea on how to create a basic jqgrid and what library references are required.
https://jsfiddle.net/99x50s2s/2/
<table id="sg1"></table>
<div id="psg1"></div>
jQuery("#sg1").jqGrid({
datatype: "local",
gridview: true,
loadonce: true,
shrinkToFit: false,
autoencode: true,
height: 'auto',
viewrecords: true,
sortorder: "desc",
scrollrows: true,
loadui: 'disable',
emptyrecords: 'No records found',
pager: '#psg1',
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:60, sorttype:"int"},
{name:'invdate',index:'invdate', width:90, sorttype:"date"},
{name:'name',index:'name', width:80},
{name:'amount',index:'amount', width:80, align:"right",sorttype:"float"},
{name:'tax',index:'tax', width:80, align:"right",sorttype:"float"},
{name:'total',index:'total', width:80,align:"right",sorttype:"float"},
{name:'note',index:'note', width:150, sortable:false}
],
caption: "Test Grid"
});
var mydata = [];//pass empty data
for(var i=0;i<=mydata.length;i++)
jQuery("#sg1").jqGrid('addRowData',i+1,mydata[i]);

Kendo.Web Grid Popup Create with ComboBox

I am using the free Kendo web controls. I have used the grid view in several places before and decided to use the popup style editing for my current project.
I have most of it working. I have three combo boxes for category, bank account and payee and when I edit an existing item, the model object passed back to my MVC action has the correct values in it. However, when I click on the create button, the three combo box values are returned as null to the controller.
Here is the CSHTML code for this view:
#using System
#using System.Linq
#{
ViewBag.Title = "Transactions";
}
#section Head
{
<link href="~/Content/kendo/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo/kendo.default.min.css" rel="stylesheet" />
<script src="~/Scripts/kendo/kendo.web.min.js"> </script>
}
#section featured
{
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#ViewBag.Title</h1>
</hgroup>
</div>
</section>
}
<div id="grid"></div>
<script>
$(function() {
$("#grid").kendoGrid({
height: 350,
toolbar: [{ name: "create", text: "Create New Transaction" }],
columns:
[
{ field: "Date", width: "100px", template: '#= kendo.toString(Date,"MM/dd/yyyy") #' },
{ field: "Amount", format: "{0:c}", width: "100px" },
{ field: "Category", width: "80px", editor: categoryDropDownEditor, template: "#=Category.Name#" },
{ field: "BankAccount", title: "Account", width: "80px", editor: bankAccountDropDownEditor, template: "#=BankAccount.Name#" },
{ field: "Payee", width: "80px", editor: payeeDropDownEditor, template: "#=Payee.Name#" },
{ command: ["edit", "destroy"], title: " ", width: "160px" }
],
editable: { mode: "popup", confirmation: "Are you sure you want to delete this transaction?" },
pageable:
{
refresh: true,
pageSizes: true
},
sortable: true,
filterable: false,
dataSource:
{
serverPaging: true,
serverFiltering: true,
serverSorting: true,
pageSize: 7,
schema:
{
data: "Data",
total: "Total",
model:
{
id: "Id",
fields:
{
Id: { editable: false, nullable: true },
Date: { type: "Date" },
Amount: { type: "number", validation: { required: true, min: 0 } },
Category: { validation: { required: true } },
BankAccount: { validation: { required: true } },
Payee: { validation: { required: true } },
Note: { validation: { required: false } }
}
}
},
batch: false,
transport:
{
create:
{
url: "#Url.Action("Create", "Transaction")",
contentType: "application/json",
type: "POST"
},
read:
{
url: "#Url.Action("Read", "Transaction")",
contentType: "application/json",
type: "POST"
},
update:
{
url: "#Url.Action("Update", "Transaction")",
contentType: "application/json",
type: "POST"
},
destroy:
{
url: "#Url.Action("Delete", "Transaction")",
contentType: "application/json",
type: "POST"
},
parameterMap: function(data)
{
return JSON.stringify(data);
}
}
}
});
function categoryDropDownEditor(container, options)
{
$('<input required data-text-field="Name" data-value-field="Id" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList(
{
autoBind: true,
dataValueFileld: "Id",
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetCategories", "Transaction")" }
}
});
}
function bankAccountDropDownEditor(container, options)
{
$('<input required data-text-field="Name" data-value-field="Id" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList(
{
autoBind: true,
dataValueFileld: "Id",
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetBankAccounts", "Transaction")" }
}
});
}
function payeeDropDownEditor(container, options)
{
$('<input required data-text-field="Name" data-value-field="Id" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList(
{
autoBind: true,
dataValueFileld: "Id",
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetPayees", "Transaction")" }
}
});
}
});
</script>
The binding to the kendo combo box must be working, otherwise the edit would fail as well. All I can think is that the object is not created correctly. Also, it selects the first item in the combo box by default, but even so, does not bind the value.
Following is the code for my create and update actions:
[HttpPost]
public ActionResult Create(TransactionModel transactionModel)
{
var transaction = _moneyBO.CreateTransaction();
Mapper.Map(transactionModel, transaction);
_moneyBO.UpdateTransaction(transaction);
return Json(Mapper.Map<TransactionModel>(transaction));
}
public ActionResult Update(TransactionModel transactionModel)
{
var transaction = _moneyBO.Transactions.SingleOrDefault(x => x.Id == transactionModel.Id);
if (transaction == null)
return View("NotFound");
Mapper.Map(transactionModel, transaction);
_moneyBO.UpdateTransaction(transaction);
return Json(Mapper.Map<TransactionModel>(transaction));
}
I have not found a good example using the popup custom edit. The example on the Kendo site works inline, but if you change the example to popup it does not work.
I have a same problem. Write, if you solve it, please
I found, that Kendo think that "null" (default for int?) is ObservableObject (while initialization of ComboBox), thats why it can't be parsed to "number". If you edit item (not create), value id not "null" and model bindind work's fine
Not sure if it's the only issue here but in your code example it looks like the initialization of your dropdown isn't quite correct. You have written dataValueFileld which should be dataValueField
kendoDropDownList({
autoBind: true,
dataValueFileld: "Id", <-- Incorrect spelling
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetPayees", "Transaction")" }
}
});

Add DatePicker range in single column of jqgrid filter

I’ve been able to add a datepicker into the filter toolbar of a jqgrid with the code below. However, I’m wondering if there’s a way to squeeze two datepickers into this single DateCreated column, so as to specify the range (From, To). Any ideas?
function loadGrid() {
$(tableID).jqGrid({
…
colModel: [
…
{ name: 'DateCreated', index: 'DateCreated', width: 125, searchoptions:{dataInit:datePick, att:{title:'Select Date'}} },
…
})
…
}
datePick = function(elem) {
$(elem).datepicker();
}
If you are open to adding in a plugin, I found the range picker from filament group to be very easy to work with. In under an hour, I had the 3 files downloaded and installed into my project, and the range picker working.
link:filament group daterangepicker
Being that I'm using jquery 1.8 in my project, I ended up getting an updated version from
link:Github filament group daterangepicker jquery 1.8
daterangepicker is also able to take all of the options that datepicker supports, so you shouldn't have much trouble converting. Let me know if you have questions and I'll see if I can help.
For reference, the plugin is dual licensed with MIT and GPL. This is the same license structure as jqgrid, so I assume if you are able to use jqgrid, than this plugin should not be a problem.
UPDATE: Adding Code Example
The important part of this code is in the colModel for date. You simply specify a dataInit function for the search options, then add the daterangepicker. Be careful on the capitalization. That got me more than once. The beforeSelectRow is simply some modification I did in order to make my checkboxes along the side behave as a radio button. It is not needed for daterangepicker to work.
$("#myGrid").jqGrid(
{
url:url,
datatype: "json",
colNames:['Version','Date'],
colModel:[
{name:'version', search:true, stype:'text'},
{name:'date', search:true,stype:"text",searchoptions:{dataInit:function(el){
$(el).daterangepicker({dateFormat:'yy/mm/dd'});
}
}}
],
toolbarfilter: true,
sortname: 'version',
sortorder: "desc",
pager: jQuery('#myPager'),
viewrecords: true,
gridview: true,
multiselect: true,
beforeSelectRow: function(rowId)
{
var selectedIds = jQuery('#myGrid').jqGrid().getGridParam("selarrrow");
jQuery("#myGrid").jqGrid().resetSelection();
if(selectedIds)
{
var id = selectedIds[0]
if(id != rowId)
{
jQuery("#myGrid").jqGrid().setSelection(rowId, false);
}
}
else
{
jQuery("#myGrid").jqGrid().setSelection(rowId, false);
}
}
});
I had to do the very same thing, and Joseph's answer above got me 90% of the way there. So, most of the credit is due to him. I had to modify some stuff to get it to work because the filament date range picker allows for single dates (the today option, the specific date option, etc). I also had to add some code to trigger the search after you selected your date. Here's my update...the meat of what I needed to add was in the beginRequest function:
$(document).ready(function() {
var grid = jQuery('#list').jqGrid({
url: '/myajaxurl',
datatype: 'json',
mtype: 'GET',
colNames: ['Reference #', 'CreatedOn', 'Product', 'Model Number', 'Quantity', 'Transaction Type', 'Created By'],
colModel: [
{ name: 'InventoryTransactionLogId', index: 'InventoryTransactionLogId', align: 'center', sortable: true, search: false },
{
name: 'CreatedOn',
search: true,
stype: 'text',
align: 'center',
formatter: 'date',
formatoptions: { newformat: 'm-d-y H:i' },
sortable: true,
searchoptions: {
dataInit: function(el) {
$(el).daterangepicker({ dateFormat: 'yy/mm/dd', onChange: datePick });
}
}
},
{ name: 'ProductName', index: 'ProductName', align: 'center', sortable: true, search: false },
{ name: 'ModelNo', index: 'ModelNo', align: 'center', sortable: true, search: true },
{ name: 'Quantity', index: 'Quantity', align: 'center', sortable: true, search: false },
{ name: 'Description', index: 'Description', align: 'center', sortable: true, search: false },
{ name: 'UserName', index: 'UserName', align: 'center', sortable: true, search: false }
],
loadtext: "Retrieving Inventory Transaction Log...",
rowNum: 50,
rowList: [25, 50, 100],
sortname: 'InventoryTransactionLogId',
sortorder: 'asc',
pager: '#pager',
ignoreCase: true,
viewrecords: true,
height: 450,
autowidth: true,
scrollOffset: 45,
caption: 'Inventory Transaction Log',
emptyrecords: "No records",
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
records: 'records',
repeatitems: false,
cell: 'cell',
id: 'InventoryTransactionLogId',
userdata: 'userdata'
},
beforeRequest: function () {
var theGrid = jQuery("#list");
var postData = theGrid.jqGrid('getGridParam', 'postData');
if (postData != undefined && postData.filters != undefined) {
postData.filters = jQuery.jgrid.parse(postData.filters);
//Remove if current field exists
postData.filters.rules = jQuery.grep(postData.filters.rules, function(value) {
if (value.field != 'CreatedOn')
return value;
});
// Parse the range picker field into start/end date
var dateRangeString = $('#gs_CreatedOn').val();
if (dateRangeString.length > 0) {
var dateRange = dateRangeString.split(' - ');
if (dateRange.length == 1) {
startDate = dateRange[0] + ' 00:00:00';
endDate = dateRange[0] + ' 23:59:59.999';
} else {
startDate = dateRange[0] + ' 00:00:00';
endDate = dateRange[1] + ' 23:59:59.999';
}
var startDateFilter = { "field": "CreatedOn", "op": "ge", "data": startDate };
var endDateFilter = { "field": "CreatedOn", "op": "le", "data": endDate };
// Add new filters
postData.filters.rules.push(startDateFilter);
postData.filters.rules.push(endDateFilter);
}
} else {
jQuery.extend(postData, {
});
}
if (postData != undefined && postData.filters != undefined) {
postData.filters = JSON.stringify(postData.filters);
postData._search = true;
}
return [true, ''];
}
});
$('.date').datepicker();
grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: "bw" });
grid.jqGrid('navGrid', '#pager', { del: false, add: false, edit: false, search: false });
});
datePick = function() {
var grid = $("#list");
$("#list")[0].triggerToolbar();
$("#list").trigger("reloadGrid", [{ page: 1 }]);
}

jqgrid MVC omit some columns from ModelState

I have a jqGrid in MVC setup as:
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/Home/DynamicGridData/',
datatype: 'json',
mtype: 'POST',
colNames: ['id', 'note', 'tax', 'PaymentType', 'CreatedByUsername', 'Actions'],
colModel: [
{ name: 'id', index: 'id', hidden: true, key: true, editable: true, editrules:{ required:false } },
{ name: 'note', index: 'note', width: 40,align:'center', editable: true, editrules: { required : true } },
{ name: 'tax', index: 'tax', width: 400, align: 'center', editable: true, editrules: { required : true } },
{ name: 'PaymentTypeId', index: 'PaymentTypeId', width: 400, align: 'center', editable: true, edittype:"select",
editoptions: { dataUrl: '/Home/PaymentTypes/' }},
{ name: 'CreatedByUsername', index: 'CreatedByUsername', hidden: true, editable: true, editrules:{ required:false } },
{ name: 'act',index:'act',width:55,align:'center',sortable:false,formatter:'actions',
formatoptions:{
keys: true, // we want use [Enter] key to save the row and [Esc] to cancel editing.
beforeSubmit:function(postdata, formid) {
alert("Hi");
jQuery("#ValidationSummary").show('slow');
},
},}
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '',
caption: 'My first grid',
editurl: '/Home/Save/'
});
jQuery("#list").navGrid('#pager', { edit: false, search: false, add: true });
});
</script>
When creating on submit it goes to the save method on the controller.
As you can see CreatedByUsername and id are hidden for normal view and edit.
When I add new data though I find that ModelState.IsValid = false.
I've managed to make it so that CreatedByUsername does not added an error to the ModelState even though no data is added for it on insert through editrules:{ required:false }.
The problem is this same piece of code doesn't work for the id and is adding an Error to the ModelState of "The id field is required."
Can anyone please tell me how to prevent this from happening for the id field?
The problem is that your id field has the key attribute and besides your validation rule this field is required. A workaround is to define a custom function for validation an always return true
Can you set the id field in your viewmodel to nullable? Like this:
public int? Id { get; set; }
If the id is not nullable, mvc will automatically create a validation error. If you're not using a viewmodel, but just using parameters on your save action, you can set the id parameter to nullable.

Resources