Kendo Grid Date format validation not working - php

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 .

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?

Preventing Jqueryvalidation from validate remote on modals open

I have script like this:
const add_modal = $('#add_modal');
const add_form = $('#add_form');
const add_button = $('#add_button');
const save_button = $('#save_button');
let add_validator = add_form.validate({
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-invalid-label',
highlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
// Different components require proper error label placement
errorPlacement: function(error, element) {
// Unstyled checkboxes, radios
if (element.parents().hasClass('form-check')) {
error.appendTo( element.parents('.form-check').parent() );
}
// Input with icons and Select2
else if (element.parents().hasClass('form-group-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo( element.parent() );
}
// Input group, styled file input
else if (element.parent().is('.uniform-uploader, .uniform-select') || element.parents().hasClass('input-group')) {
error.appendTo( element.parent().parent() );
}
// Other elements
else {
error.insertAfter(element);
}
},
rules: {
name: {
required: true,
minlength: 2,
maxlength: 20
},
email: {
required: true,
email: true,
remote: "/admin/users/check-email",
},
role: {
required: true,
},
password: {
required: true,
minlength: 12,
},
password_verification: {
required: true,
minlength: 12,
equalTo: '#password'
},
},
messages:{
email:{
remote: "Email is already taken."
}
}
});
add_button.click(function (e) {
e.preventDefault();
add_modal.modal("show");
add_validator.resetForm();
$(':input').val("");
$("#csrf").val($csrf);
});
save_button.click(function (e) {
e.preventDefault();
let form = $(this).closest('form');
let $action = form.attr('action');
let $method = form.attr('method');
let $data = form.serialize();
if (add_form.valid()) {
$.ajax({
url: $action,
type: $method,
data:$data,
success: function (result) {
if (result.type === 'success') {
add_modal.modal("hide");
add_validator.resetForm();
swalInit({
title: 'Success!',
text: result.text,
type: 'success',
timer: 3000,
}).then((reload) => {
datatables.ajax.reload();
});
} else {
swalInit({
title: 'Oops...',
text: result.text,
type: 'error',
timer: 3000,
});
}
},
})
}
});
it seems like the jqueryvalidation plugin is checking mail availability on modals open. since when I see at web inspector it sends a post request to /admin/users/check-email. how can i prevent this behaviour and make it only check when i press save_button? save_button is a button inside the modal.
Try this:
let update_validator = update_form.validate({
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-invalid-label',
highlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
// Different components require proper error label placement
errorPlacement: function(error, element) {
// Unstyled checkboxes, radios
if (element.parents().hasClass('form-check')) {
error.appendTo( element.parents('.form-check').parent() );
}
// Input with icons and Select2
else if (element.parents().hasClass('form-group-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo( element.parent() );
}
// Input group, styled file input
else if (element.parent().is('.uniform-uploader, .uniform-select') || element.parents().hasClass('input-group')) {
error.appendTo( element.parent().parent() );
}
// Other elements
else {
error.insertAfter(element);
}
},
rules: {
name: {
required: true,
minlength: 2,
maxlength: 20
},
email: {
required: true,
email: true,
remote: {
url: "/admin/users/email-available",
type: "post",
data: {
user_id: function () {
return $("#id").val();
}
}
}
},
role: {
required: true,
},
password: {
minlength: 12
},
password_verification: {
required: isPasswordPresent,
minlength: 12,
equalTo: "#update_password"
},
},
messages:{
email:{
remote: "Email is already taken."
}
},
submitHandler: function(form, event) {
event.preventDefault();
let $action = $(form).attr('action');
let $method = $(form).attr('method');
let $data = $(form).serialize();
$.ajax({
url: $action,
type: $method,
data: $data,
success: function (result) {
if (result.type === 'success') {
update_modal.modal("hide");
update_validator.resetForm();
swalInit({
title: 'Success!',
text: result.text,
type: 'success',
timer: 3000,
showCloseButton: true
}).then((reload) => {
datatables.ajax.reload();
});
} else {
swalInit({
title: 'Oops...',
text: result.text,
type: 'error',
timer: 3000,
});
}
},
})
}
});

Kendo Template cannot read/refresh grid

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: " " }],
]
});

jQuery Validation Plugin 1.9.0 .. I want submit won't reload the page when it's valid

$("#da-ex-validate2").validate({
rules: {
details: {
required: true,
rangelength: [1, 500]
},
editor1: {
required: true,
minlength: 1
},
title: {
required: true,
rangelength: [1, 100]
},
SlideDeckPhoto: {
required: "#iButton:checked",
accept: ['.jpeg', '.png', '.jpg', '.gif']
},
min1: {
required: true,
digits: true,
min: 5
},
max1: {
required: true,
digits: true,
max: 5
},
submitHandler: function(form) {
$(form).ajaxSubmit();
},
range1: {
required: true,
digits: true,
range: [5, 10]
}
},
invalidHandler: function (form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("#da-ex-val2-error").html(message).show();
} else {
$("#da-ex-val2-error").hide(); // it's not work !!! and the page is reload !!
}
}
});
I would also would like to save my form values to MySql without reload the page .
Please help ! I read so many post and tried so many thing !
If you put a code please tell where to put it ..
BTW my form has few input fields and also an file input field .
PLEASE HELP !
return false from the submit handler
submitHandler: function(form) {
$(form).ajaxSubmit();
return false;
}
This is my solution, put it after invalidHandler :
submitHandler: function(form) {
var dataString = $('#YourFormID').serialize();
$.ajax({
type: 'POST',
url: 'yourpage.php',
data: dataString,
success: function() {
$('#YourErrorDivID').hide();
$('#YourSuccessDivID').html("Your Message").show();
}
});
}

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