Kendo Template cannot read/refresh grid - php

I have a general grid that list a serie of processes each one with a sub-grid with the participants of each process.
Just like this
Here is the code:
$("#grid").kendoGrid({
dataSource: {
type: "json",
data: <?php echo $datos_procesos; ?>,
pageSize: 20
},
sortable: true,
filterable: {
extra: false,
operators: {
string: {
startswith: "Empieza con",
eq: "Igual a",
neq: "No es igual a",
contains: "Contiene",
endswith: "Termina con"
}
}
},
selectable: "multiple",
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
});
function detailInit(e) {
var detailRow = e.detailRow;
detailRow.find(".tabstrip").kendoTabStrip({
animation: {
open: { effects: "fadeIn" }
}
});
detailRow.find("#participantes").kendoGrid({
dataSource: {
type: "json",
data: <?php echo $datos_usuarios; ?>,
serverPaging: false,
pageSize: 7,
filter: { field: "IDPROCESO", operator: "eq", value: e.data.IDPROCESO }
},
scrollable: false,
sortable: true,
pageable: {
refresh: true
},
filterable: {
extra: false,
operators: {
string: {
startswith: "Empieza con",
eq: "Igual a",
neq: "No es igual a",
contains: "Contiene",
endswith: "Termina con"
}
}
},
columns: [
{ field: "NOMBRE", title:"Nombre" },
{ field: "EMAIL", title:"Email" },
{ field: "ACCIONES", title: "", encoded: false },
]
});
$("a[id^='delete']").kendoTooltip({
content: "Desasignar usuario",
position: "top"
});
$("a[id^='delete']").click(function(event){
event.preventDefault();
var u = $(this).attr("href");
$.ajax({
url: u
}).success(function() {
alert("Se ha desasignado al usuario del proceso.");
}).error(function() {
alert("Se ha producido un error al desasignar el usuario del proceso.");
});
});
});
The html code is just a simple lines
<div id="grid"></div>
<script type="text/x-kendo-template" id="template">
<div class="tabstrip">
<ul>
<li class="k-state-active">
Participantes
</li>
</ul>
<div>
<div id="participantes"></div>
</div>
</div>
</script>
All works fine, the grids are displayed correctly, the data come from a php function which extracts from database the processes and the participants of each one.
My problem comes when I try to delete a participant of a process, I want to refresh or read the new updated data but It doesnt work.
If I click in link created a[id^='delete'] it calls a php function through ajax deleting the participant but then I cant reload the grid in the success callback. The "pageable: {refresh: true}" property also doesnt work
I have several problems like "Cannot read property 'dataSource' of undefined" or "Cannot read property 'read' of undefined"
I am new with the kendoUI and I am a bit lost, if anyone could give me a clue it would be appreciated.
Thanks for the help

I would suggest to use command line destory in participantes sub-grid. Kendo Grid handles removing item from sub-grid and you don't need to load data again.
detailRow.find("#participantes").kendoGrid({
dataSource: {
transport: {
read: {
url: //here url where sub grid data is read,
dataType: "jsonp"
},
destroy: {
url: // here server side url which removes particpant,
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
serverPaging: false,
pageSize: 7,
filter: { field: "IDPROCESO", operator: "eq", value: e.data.IDPROCESO }
},
scrollable: false,
sortable: true,
pageable: {
refresh: true
},
filterable: {
extra: false,
operators: {
string: {
startswith: "Empieza con",
eq: "Igual a",
neq: "No es igual a",
contains: "Contiene",
endswith: "Termina con"
}
}
},
columns: [
{ field: "NOMBRE", title:"Nombre" },
{ field: "EMAIL", title:"Email" },
{ field: "ACCIONES", title: "", encoded: false },
{ command: ["destroy"], title: " " }],
]
});

Related

How to insert a date field JSGrid?

I'm using this code to create a simple CRUD using Jsgrid and php, but the page isn't loading when i change the type field to date. I watched almost the entire youtube and I didn't find anything about.
I dont even know what to do
Can somebody help me?
index.php:
<body>
<div class="container">
<br />
<div class="table-responsive">
<h3 align="center">Inline Table Insert Update Delete in PHP using jsGrid</h3><br />
<div id="grid_table"></div>
</div>
</div>
<script type="text/javascript" src="js.js"></script>
</body>
js.js
var db = {
loadData: function(filter){
return $.ajax({
type: "GET",
url: "fetch_data.php",
data: filter
});
},
insertItem: function(item){
return $.ajax({
type: "POST",
url: "fetch_data.php",
data: item
});
},
updateItem: function(item){
return $.ajax({
type: "PUT",
url: "fetch_data.php",
data: item
});
},
deleteItem: function(item){
return $.ajax({
type: "DELETE",
url: "fetch_data.php",
data: item
});
}
};
var MyDateField = function (config) {
jsGrid.Field.call(this, config);
};
MyDateField.prototype = new jsGrid.Field({
sorter: function (date1, date2) {
return new Date(date1) - new Date(date2);
},
itemTemplate: function (value) {
return new Date(value).toDateString();
},
insertTemplate: function (value) {
return this._insertPicker = $("<input class='date-picker'>").datetimepicker();
},
editTemplate: function (value) {
return this._editPicker = $("<input class='date-picker'>").datetimepicker();
},
insertValue: function () {
return this._insertPicker.data("DateTimePicker").useCurrent();
},
editValue: function () {
return this._editPicker.data("DateTimePicker").useCurrent();
}
});
jsGrid.fields.date = MyDateField;
$('#grid_table').jsGrid({
width: "100%",
height: "600px",
filtering: true,
inserting:true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 9,
deleteConfirm: "Do you really want to delete data?",
controller: db,
fields: [
{
name: "id",
type: "hidden",
css: 'hide'
},
{
title:"Load Number",
name: "loadnumber",
type: "text",
width: 150,
validate: "required"
},
{
title:"Broker MC",
name: "brokermc",
type: "text",
width: 150,
validate: "required"
},
{
title:"Broker",
name: "brok3r",
type: "text",
width: 50,
validate: function(value)
{
if(value > 0)
{
return true;
}
}
},
{
title:"Driver",
name: "driver",
type: "text",
width: 150,
validate: "required"
},
{
title:"Load Date",
name: "loaddate",
type: "date"
},
{
type: "control"
}
]
});
i tried to rename to "MyDateField", the page loads but the item field disappears, how can i fix it?

Kendo Grid Date format validation not working

Why is that only the field name shows when i enter invalid formats. Eventhough ive tried different validation styles it still shows if the format is invalid. I've created custom validation already but it only works if the date is empty or null but if it is not it does not work it is because when i enter wrong format in the field the custom validation does not work .
image of the actual validation
here is the code
$('#lot-sched-grid').kendoGrid({
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "maintenance/sales/s-lot-sched/read-header/0",
dataType: "json"
},
update: {
url: "maintenance/sales/s-lot-sched/update",
type: "POST",
dataType: "json",
complete: function(jqXhr, textStatus) {
if (textStatus == 'success') {
/*var grid = vm.GRID.init();
grid.dataSource.read();*/
vm.GRID.init().dataSource.read();
swal("Success", "Lot Remarks is successfully updated!", "success");
} else {
vm.error(jqXhr);
}
}
}
},
pageSize: window.uiDefaults.pageSize,
// batch: true,
schema: {
model: {
id: "lot_id",
fields: {
lot_id: { editable: false, nullable: true },
lot_prod_grp_id: { type: "string" },
lot_year: { type: "string", editable: false },
lot_code: { type: "string", editable: false },
lot_start_date: {
type: "date",
parse: function(value) {
return kendo.toString(value, "yyyy-MM-dd");
},
validation: {
custom: function(input) {
if (input.is("[name='lot_start_date']") && input.val().length == 0) {
input.attr("data-custom-msg", "Start date is required.");
return false;
}
return true;
}
}
},
lot_remarks: {
type: "string",
validation: {
lotremarks_min_validate: function (input) {
if (input.is("[name='lot_remarks']") && input.val().length < 4 && input.val().length != 0) {
input.attr("data-lotremarks_min_validate-msg", "Lot Remarks minimum input value is 4.");
return false;
}
return true;
},
lotremarks_max_validate: function (input) {
if (input.is("[name='lot_remarks']") && input.val().length > 100 && input.val().length != 0 ) {
input.attr("data-lotremarks_max_validate-msg", "Lot Remarks maximum input value is 100.");
return false;
}
return true;
},
},
},
}
}
}
}),
scrollable: false,
filterable: window.uiDefaults.filterable,
pageable: window.uiDefaults.pageable,
sortable: window.uiDefaults.sortable,
noRecords: true,
messages: {
noRecords: window.uiDefaults.noRecordsMessage,
},
selectable: "row",
/*save: function(e){
console.log(e);
},*/
editable: true,
toolbar: [ 'save', 'cancel' ],
columns: [
{
field: "lot_code",
title: "Lot Code",
width: 120,
},
{
field: "lot_year",
title: "Year",
width: 100,
},
{
field: "lot_start_date",
title: "Start Date",
format: "{0:yyyy-MM-dd}",
width: 120,
},
{
field: "lot_remarks",
title: "Remarks",
template: kendo.template($('#lot-remarks-template').html()),
}],
});
Try changing the attribute name you're adding.
Change the following:
input.attr("data-custom-msg", "Start date is required.");
To:
input.attr("data-lot_start_date-msg", "Start date is required.");
So what i did is to change the custom validation to date validation , and create a condition inside the validation to determine if it is empty and if ever it is not in its proper format .

FancyGrid ajax success Variable is not defined

I'm having a little bit trouble about sending a database data to a client side table. I'am using fancy grid.
Client Side
$.ajax({
url:'function.php?what=listofbookings',
type:'post',
data:{user:user},
success: function(data) {
var clients = data;
}
});
});
$("#jsGrid").jsGrid({
width: "100%",
height: "400px",
inserting: true,
editing: true,
sorting: true,
paging: true,
data: clients,
fields: [
{ name: "people", type: "text", width: 150, validate: "required" },
{ name: "email", type: "number", width: 50 }
]
});
And here is the PHP Code
if(isset($_GET['what'])){
if($_GET['what'] === 'listofbookings'){
$selit = "SELECT * FROM dbdbdb_booking";
$queryit = mysqli_query($conn,$selit);
$arr = array();
while($row = mysqli_fetch_assoc($queryit)){
$arr[] = $row;
}
echo json_encode($arr);
}
}
For some reason the var client is not defined and the data is not passing to clients.
Any thoughts ?
You need to initialize jsGrid inside your AJAX's success :
$.ajax({
url:'function.php?what=listofbookings',
type:'post',
data:{user:user},
success: function(data) {
var clients = data;
$("#jsGrid").jsGrid({
width: "100%",
height: "400px",
inserting: true,
editing: true,
sorting: true,
paging: true,
data: clients,
fields: [
{ name: "people", type: "text", width: 150, validate: "required" },
{ name: "email", type: "number", width: 50 }
]
});
}
});

kendoui Grid with autocomplete on its toolbar?

Update:
I tried and spent alot of my time fixing the issue, and at last problem solved.
But initially Many Thanks to OnaBai and to my colleague who helped to come this far.
Now i am stuck here.
I type username and it show display on dropdown and after pressing TAB or ENTER it show the result in grid.
The result is only shown in grid if it is from page "1", but if it is from page "2" or any other further page the result is not shown.
Here is how it is working:
but when if i search for other user which is not on page 1 then it dont show display the other user in grid. instead i get empty grid.
FireBug screenShots:
Here is my Updated Code after i did some more changes in the code.:
<?php
/*foreach($users_list_data->result() as $row){
echo $row->Username."<br />";
}*/
?>
<div id="grid"></div>
<div id="details" />
<div class="second_column_content_container">
</div>
<script>
function create_user() {
var entryform = $("#insert_user_info");
$.ajax({
type : 'POST',
url : '<?php echo base_url(); ?>/index.php/user_management/manage_users/createUser',
data : entryform.serialize(),
success : function(response) {
$(".second_column").html(response);
}
});
}
function create_user_form() {
$.ajax({
type : 'POST',
url : '<?php echo base_url(); ?>/index.php/user_management/manage_users/load_user_form',
success : function(response) {
$(".second_column").html(response);
}
});
}
function onChange(arg) {
var selected = "";
var grid = this;
grid.select().each(function() {
var dataItem = grid.dataItem($(this));
selected = dataItem.Username;
});
$.ajax({
type: "POST",
url: "<?php echo base_url()?>index.php/user_management/manage_users/get_user_groups/"+selected,
beforeSend: function(){
$("#pre_image").attr("src","http://localhost/zorkif_new/images/pre.gif");
},
success: function(output_string) {
$('.data_column_a').html(output_string);
}
});
}
var wnd, detailsTemplate;
$(document).ready(function(){
var serverBaseUrl = "<?php echo base_url(); ?>";
$("#grid").kendoGrid({
dataSource:{
serverPaging: true,
transport: {
read: serverBaseUrl + "index.php/user_management/manage_users/list_view/",
update: {
url: serverBaseUrl + "index.php/user_management/manage_users/userUpdate/",
type: "POST"
}
// destroy: {
// url: serverBaseUrl + "index.php/user_management/manage_users/userDelete/",
// dataType: "jsonp"
// }
//update: "<?php echo base_url() ?>index.php/user_management/manage_users/list_view/"
},
error: function(e) {
alert(e.responseText);
},
schema:{
data: "data",
total: "total",
model: {
id: "UserID",
fields: {
FirstName: { editable: true },
LastName: { validation: { required: true} },
MiddleNames:{validation:{required:true}}
}
}
},
pageSize:5
},
toolbar: kendo.template($("#toolbarTemplate").html()),
scrollable: true,
selectable: "row",
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false
},
columns: [
{
field: "UserID",
hidden:true
},
{
field: "Username",
title:"Username"
},
{ field: "FirstName",
title:"First Name"
},
{field:"MiddleNames"},
{field:"LastName"},
{field:"City"},
{field:"Email"},
//{field:"Actions"},
//{command: { text: "Delete", click: showDetails }, title: " ", width: "140px"},
{command: { text: "Details", click: redirectToPage }, title: " ", width: "140px" },
{ command: { text: "Edit", click: redirectToEditPage }, title: " ", width: "140px" }
],
change: onChange,
editable: "popup"
});
$("#users").kendoAutoComplete({
minLength: 3,
dataTextField: "Username",
dataSource: {
serverFiltering: true,
transport: {
read: {
type: "GET",
dataType: "json",
contentType:'application/json; charset=utf-8',
url: serverBaseUrl + "index.php/user_management/manage_users/search_user/",
data: function (arg){
//alert(arg);
//alert({Username:autocompleteUsers.data("kendoAutoComplete").value});
return {Username : $("#users").data("kendoAutoComplete").value()};
//return $("#users").data("kendoAutoComplete").value();
}
}
}
},
change: onChangeAutoComplete
});
function onChangeAutoComplete(){
var value = this.value();
var grid = $('#grid');
if (value) {
grid.data("kendoGrid").dataSource.filter({ field: "Username", operator: "Contains", value: value });
} else {
grid.data("kendoGrid").dataSource.filter({});
}
}
/*$("#users").kendoAutoComplete({
minLength: 3,
dataTextField: "Title",
//JSON property name to use
dataSource: {
pageSize: 10,
//Limits result set
transport: {
read: {
url: "/echo/json/",
//using jsfiddle echo service to simulate JSON endpoint
dataType: "json",
type: "POST",
data: {
// /echo/json/ echoes the JSON which you pass as an argument
json: JSON.stringify([
{
"Title": "Doctor Who: The Trial of a Time Lord"},
{
"Title": "Doctor Who: The Key to Time"},
{
"Title": "Doctor Who: The Time Meddler"},
{
"Title": "Doctor Who: The End of Time"}
])
}
}
}
}
});*/
/*change: function () {
var value = this.value();
if (value) {
grid.data("kendoGrid").dataSource.filter({ field: "UserID", operator: "eq", value: value });
} else {
grid.data("kendoGrid").dataSource.filter({});
}
}
});*/
/*$("#users").blur(function() {
var data = $(this).data("kendoAutoComplete").dataSource._data,
nbData = data.length,
found = false;
for(var iData = 0; iData < nbData; iData++) {
if(this.value === data[iData].Title)
found = true;
}
console.log(found);
});*/
wnd = $("#details").kendoWindow({
title: "Customer Details",
modal: true,
visible: false,
resizable: false,
width: 300
}).data("kendoWindow");
detailsTemplate = kendo.template($("#template").html());
});
function redirectToPage(e){
e.preventDefault();
var row = $(e.target).closest("tr");
var item = $("#grid").data("kendoGrid").dataItem(row);
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/user_management/manage_users/ViewProfile/'?>"+JSON.parse(item.UserID),
success: function(output_string){
$('.second_column_content_container').html(output_string);
//$('.second_column_content_container').innerHTML("hello");
//alert(output_string);
},
error: function(data){
alert("error");
}
});
}
function redirectToEditPage(e){
e.preventDefault();
var row = $(e.target).closest("tr");
var item = $("#grid").data("kendoGrid").dataItem(row);
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/user_management/manage_users/edit_user/'?>"+JSON.parse(item.UserID),
success: function(output_string){
$('.second_column_content_container').html(output_string);
//$('.second_column_content_container').innerHTML("hello");
//alert(output_string);
},
error: function(data){
alert("error");
}
});
}
//show details on a popup
function showDetailsPopup(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
}
//This will redirect to Next Page
function showDetails(e) {
e.preventDefault();
var row = $(e.target).closest("tr");
var item = $("#grid").data("kendoGrid").dataItem(row);
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/user_management/manage_users/list_view/'?>"+JSON.parse(item.UserID),
success: function(data){
alert("done");
//$('.second_column_content_container').html(output_string);
//$('.second_column_content_container').innerHTML("hello");
//alert(output_string);
},
error: function(data){
alert("error");
}
});
//var grid = $("#grid").data("kendoGrid");
//alert(JSON.parse(item.UserID));
//window.location.href="http://www.google.com/";
}
</script>
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h2>#= FirstName #</h2>
<h2>City: #= City # </h2>
</div>
</script>
<script type="text/x-kendo-template" id="toolbarTemplate">
<div class="toolbar">
<label class="category-label" for="users">Search Users: </label>
<input type="text" id="users" style="width: 250px;" />
</div>
</script>
<div class="data_column_a">
<img src="" id="pre_image" >
</div>
Now how to solve this very extremely difficult problem O_o??
Update:
This Username is on Page 2 of the Grid as can be seen in ScreenShot.
But during Search, it sends the headers of page 1 when i search for username that is other than of page 1.
Banging my head to walls, How to Solve ?
The problem seems to be related to you autocomplete definition that is not sending any Username argument on read. Try defining transport.read as:
transport : {
read : {
url : "search_user.php",
data: function (arg) {
return {Username : autocompleteUsers.data("kendoAutoComplete").value()};
}
},
dataType: "json",
type : "POST"
},
EDIT: For applying selected value on autocomplete as filtering condition for the grid. You should do:
var autocompleteUsers = $("#users").kendoAutoComplete({
dataTextField: "Username",
dataSource : {
severFiltering: true,
transport : {
read : {
url : "search_user.php",
data: function (arg) {
return {Username: autocompleteUsers.data("kendoAutoComplete").value()};
}
},
dataType: "json",
type : "POST"
}
},
change : function () {
var username = autocompleteUsers.data("kendoAutoComplete").value();
var filter = {
logic : "and",
filters: [
{
ignoreCase: true,
field : "Username",
value : username,
operator : "startswith"
}
]
};
$("#grid").data("kendoGrid").dataSource.filter(filter);
}
});

Kendo Grid. How to display dataTextField in Grid's cell instead of dataValueField?

I want to display Text for my ForigenKey columns instead of numeric values. There are a lot of examples to retrieve TextMember by comparing ID but they are not working in my case. I just started to use Kendo ui so dont know much about it
Here is the code :
$(document).ready(function () {
dataSource1 = new kendo.data.DataSource({
transport: {
read: {
url: "Data/AttendanceCode/GridSelect.php",
dataType: "json",
},
update: {
url: "Data/AttendanceCode/GridUpdate.php",
dataType: "json",
type:"GET"
},
destroy: {
url: "Data/AttendanceCode/GridDelete.php",
dataType: "json",
type:"POST"
},
create: {
url: "Data/AttendanceCode/GridInsert.php",
dataType: "json",
type:"POST"
},
},
schema: {
data: "data",
model: {
id: "AttendenceID",
fields: {
AttendenceID : { editable: false, nullable: true },
TeacherID: { field: "TeacherID", defaultValue: "EIIT0002" },
}
}
},
});
$("#grid").kendoGrid({
dataSource: dataSource1,
pageSize: 10,
pageable: {
refresh: true,
pageSizes: true
},
editable:{ mode : "popup" },
height: 400,
filterable: true,
columnMenu: true,
sortable: true,
reorderable: true,
resizable: true,
toolbar: ["create"],
columns: [
{ field:"AttendenceID", title: "Attendence ID", width:"130px" },
{ field: "TeacherID", title:"Teacher", width: "100px" , editor: TeacherDropDownEditor, template: "#=getTeacherName(TeacherID)#" },
{ command: ["edit", "destroy"], title: "Action", width: "210px" }],
});
});
Teacher DropDown DataSource
teacher = new kendo.data.DataSource({
transport: {
read: {
url : "Data/Teacher.php",
dataType: "json" }
},
schema: {
data : "Teacher"
}
});
// Teacher Editor
function TeacherDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "TeacherName",
dataValueField: "Service_NO",
dataSource: teacher
});
}
Different approaches i found and tried to Get Teacher Name
1 -
function getTeacherName(value) {
var text = "";
$.each(teacher, function () {
if (this.Service_NO == value) {
text = this.Name;
return false;
}
});
return text;
}
2 -
function getTeacherName(teacherID) {
for (var idx = 0, length = teacher.length; idx < length; idx++)
{
if (teacher[idx].Service_NO === teacherID)
{t = teacher[idx].Name;}
}
return t;
}
3 -
function getTeacherName(teacherID) {
$.each(teacher, function(key, val) {
if(val.Service_NO == tID){
t = val.Name;
}
});
return t;
}
It seems like dataSource (teacher) is not having any value.
PHP code is working perfectly.
Please Help if you have any idea whats wrong with my code.
Thanks !!
You are right, teacher DataSource does not have any data because you are defining how to get the data (that's what you do with the DataSource) but you are not reading it.
Add:
teacher.read();
for manually forcing the data read.
NOTE: This is something that happens magically when you have a Grid, ListView,... because these widget do it for you but this time, for displaying your grid you need to read it in advance since it is invoked from a JavaScript function (KendoUI grid code doesn't know anything about what you have in the function getTeacherName other than the name).
you should config your field:
{ field: "nu_status", title: 'Status', values: [ { text: "Active", value: 1 }, { text: "Inactive", value: 0 }]},

Categories