Sweetalert2 : Unable to trigger the validation message - sweetalert2

I have created this sequence of popups with Sweetalert2
The user select an year, wait for generation of the report, and at the end can download the report.
This is the code (simplified)
var startYear = 2017;
$("#test").click(function(){
var _id = ....;
var listYears = {};
for (var i = parseInt(moment().format("YYYY")); i >= startYear; i--) listYears[" " + i] = i;
swal({
title: "Data export",
html : "Select a year and press the <strong>export</strong> button.",
reverseButtons : true,
showCancelButton: true,
cancelButtonText : "Cancel",
confirmButtonText: "Export",
validationMessage : "Select a year",
inputClass : "form-control", /* bootstrap 4 class */
input: "select",
inputOptions: listYears,
inputPlaceholder: "Select..",
}).then((result) => {
if (result.value) {
swal({
title: 'Wait',
text: 'Report generation in progress..',
allowOutsideClick : false,
showConfirmButton : false,
onOpen: () => {
swal.showLoading();
var dataGET = ".....&id=" + _id + "&year=" + parseInt(result.value);
var xhr = $.ajax({
type: "GET",
url: ".....php",
data : dataGET,
cache: false,
success : function(val){
var _this = this;
if(val == "OK_DOWNLOAD"){
var pathDownload = xhr.getResponseHeader(".....");
var nameDownload = xhr.getResponseHeader(".....");
swal({
type : "success",
title: 'Perfect',
html : 'Now you can download the report<br/><a class="btn btn-custom-secondary mt-3" href="......" target="_blank" id="tempBtnDownloadReport"><span class="icon-download1"></span></a>',
showConfirmButton : false,
});
$("#tempBtnDownloadReport").click(function(){
swal.close();
});
}else{
_this.error();
}
},
error : function(){
swal("Attention","Error creating report, please try again.","error");
},
complete : function(jqXHR,textStatus){
swal.hideLoading();
xhr = null;
}
});
}
});
}
});
My problem is when the user press the export button and the select it hasn't been "selected". I would like to trigger the error message ("Select a year"), something like these examples.

SOLVED
I used the preConfirm event.
swal({
title: "Data export",
html : "Select a year and press the <strong>export</strong> button.",
reverseButtons : true,
showCancelButton: true,
cancelButtonText : "Cancel",
confirmButtonText: "Export",
validationMessage : "Select a year",
inputClass : "form-control",
input: "select",
inputOptions: listYears,
inputPlaceholder: "Select..",
allowOutsideClick: () => !Swal.isLoading(),
preConfirm: (test) => {
if(test == "") Swal.showValidationMessage("Select a year");
}
}).then((result) => {
if (result.value) {
swal({
title: 'Wait',
text: 'Report generation in progress..',
allowOutsideClick : false,
showConfirmButton : false,
onOpen: () => {
swal.showLoading();
var dataGET = "category=download&cmd=do_excel_report&id=" + _id + "&year=" + parseInt(result.value);
var xhr = $.ajax({
type: "GET",
url: "/" + $("html").data("project") + "/home/command.php",
data : dataGET,
cache: false,
success : function(val){
var _this = this;
if(val == "OK_DOWNLOAD"){
var pathDownload = xhr.getResponseHeader("Custom-Success-Download-Path");
var nameDownload = xhr.getResponseHeader("Custom-Success-Download-Name");
swal({
type : "success",
title: 'Perfect',
html : 'Now you can download the report<br/><a class="btn btn-custom-secondary mt-3" href="/' + $("html").data("project") + "/home/command.php?category=download&cmd=download_excel_report&path=" + pathDownload + "&name=" + nameDownload + '" target="_blank" id="tempBtnDownloadReport"><span class="icon-download1"></span></a>',
showConfirmButton : false,
});
$("#tempBtnDownloadReport").click(function(){
swal.close();
});
}else{
_this.error();
}
},
error : function(){
swal("Attention","Error creating report, please try again.","error");
},
complete : function(jqXHR,textStatus){
swal.hideLoading();
xhr = null;
}
});
}
});
}
});

Related

fetch data on dropdown change event from database to dataTables using ajax in Codeigniter 4

fetch data from database to datatables using ajax on dropdown change.
controller and model is working fine when use simple dropdown change event using ajax, but when try to fetch data to dataTables then show an error
no data available
Controller:
public function getStudents()
{
$model = new ModelAjax();
$sessionid = $this->request->getVar('sessionid');
$classid = $this->request->getVar('classid');
$data = $model->getStudents($sessionid,$classid);
echo json_encode($data);
}
Model:
public function getStudents($sessionid,$classid)
{
$model = new ModelStudent();
$array = ['sessionid' => $sessionid, 'classid' => $classid];
$data = $model->select('tblstudent.studentname,tblstudent.fathername, tblstudent.rollno ,tblstudent.mobile1')
->join('tblenrollment','tblstudent.id = tblenrollment.studentid','left')
->where($array)
->findAll();
return $data;
}
Script:
$("#classid").change(function(){
var sessionid = $("#sessionid").val();
var classid = $(this).val();
$('#example').DataTable({
ajax: {
url: "<?php echo site_url('Ajax/getStudents'); ?>",
type: "POST",
data: function(d){
d.sessionid = $("#sessionid").val();
d.classid = $("#classid").val();
}
},
dom: 'Bfrtip',
iDisplayLength: 15,
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5',
'pageLength'
],
search: true
});
});
Finally succeeded to do it:
$("#classid").change(function(){
var sessionid = $("#sessionid").val();
var classid = $(this).val();
$.ajax({
url : "<?php echo site_url('Ajax/getStudents'); ?>",
method : "POST",
data : {sessionid: sessionid, classid: classid},
async : true,
dataType : 'json',
success: function(data)
{
$('#example').DataTable({
destroy: true,
data : data,
columns: [
{ data: 'studentname', title: "StudentName" },
{ data: 'fathername', title: "Father Name" },
{ data: 'rollno', title: "RollNo" },
{ data: 'mobile1', title: "Mobile" }
],
dom: 'Bfrtip',
iDisplayLength: 15,
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5',
'pageLength'
],
search: true
});
}
});
return false;
});

KendoDropDownList clear value

I use kendoDropDownList and have the following code:
<div id="memberNotInit-grid"></div>
<script>
$(document).ready(function () {
$("#memberNotInit-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("MemberNotInitList", "RandomPoolInit"))",
type: "POST",
dataType: "json",
data: function() {
var data = {
};
addAntiForgeryToken(data);
return data;
}
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: #(Model.PageSize),
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
pageSizes: [#(Model.AvailablePageSizes)],
#await Html.PartialAsync("_GridPagerMessages")
},
editable: {
confirmation: "#T("Common.DeleteConfirmation")",
mode: "inline"
},
scrollable: false,
columns: [
{
field: "FirstName",
title: "#T("PoolMemberList.Fields.FirstName")",
width: 150
},
{
field: "LastName",
title: "#T("PoolMemberList.Fields.LastName")",
width: 150
},
{
field: "Status",
template: columnTemplateFunction
},
{
field: "Reason",
width: 150,
template: "<input data-bind='value:Reason' class='reasonTemplate' />",
//hidden: true
}
],
dataBound: function (e) {
var grid = e.sender;
var items = e.sender.items();
items.each(function (e) {
var dataItem = grid.dataItem(this);
var ddt = $(this).find('.dropDownTemplate');
$(ddt).kendoDropDownList({
value: dataItem.value,
dataSource: ddlDataSource,
dataTextField: "displayValue",
dataValueField: "Status",
change: onDDLChange
});
var reason = $(this).find('.reasonTemplate');
$(reason).keydown(reasonChange);
reason.hide();
});
}
});
var ddlDataSource = [
{
Status: #((int)DriverRandomPoolStatus.Enrollment),
displayValue: "Enrollment"
},
{
Status: #((int)DriverRandomPoolStatus.Active),
displayValue: "Active"
},
{
Status: #((int)DriverRandomPoolStatus.Excused),
displayValue: "Excused"
}
];
function columnTemplateFunction(dataItem) {
var input = '<input class="dropDownTemplate"/>'
return input
};
function onDDLChange(e) {
var element = e.sender.element;
var row = element.closest("tr");
var grid = $("#memberNotInit-grid").data("kendoGrid");
var dataItem = grid.dataItem(row);
dataItem.set("Status", e.sender.value());
//alert(e.sender.value());
if (dataItem.Status == #((int)DriverRandomPoolStatus.Active)) {
$.ajax({
method: "POST",
url: "#Html.Raw(Url.Action("ChangeMemberStatus", "RandomPoolInit"))",
data: { id: dataItem.Id, status: dataItem.Status }
}).done(function () {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").hide();
grid.pager.refresh();
});
}
if (dataItem.Status == #((int)DriverRandomPoolStatus.Excused)) {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.reasonTemplate').show();
var ddl = grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.dropDownTemplate');
//ddl.value(dataItem.Status);
}
};
function reasonChange(event) {
if (event.keyCode === 13) {
var element = event.target;
var row = element.closest("tr");
var grid = $("#memberNotInit-grid").data("kendoGrid");
var dataItem = grid.dataItem(row);
var r = grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.reasonTemplate').val();
$.ajax({
method: "POST",
url: "#Html.Raw(Url.Action("ChangeMemberStatus", "RandomPoolInit"))",
data: { id: dataItem.Id, status: dataItem.Status, reason: r }
}).done(function () {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").hide();
grid.pager.refresh();
});
}
}
});
</script>
but when we select "Exclused" from dropdownlist value of dropdownlist is dumped to Enrollment (first value from dropdownlist). Why so and how to fix it?
I fixed it the following way:
$(ddt).kendoDropDownList({
value: dataItem.Status,
.....
});
not:
value: dataItem.value,

Grid is not loading as a item of penal.

I am trying to load grid in as a item panel with ajax call. My grid is not loading. Can you please help me. This is I am trying because I was not getting scope in ext ajax call.
My code is
{
xtype: 'panel',
title: "Search Result",
height:500,
items: [
Ext.Ajax.request({
url: 'XML/1Cohart.xml',
scope: this,
timeout: global_constants.TIMEOUT,
method: "GET",
disableCaching: true,
failure: function(response) {
utils.showOKErrorMsg(sdisMsg.ajaxRequestFailed);
},
success: function(response) {
debugger;
var datas = response.responseXML;
Ext.each(datas.getElementsByTagName("HEADER"), function(header) {
this.buildField(header);
this.buildColumn(header);
}, this);
Ext.each(datas.getElementsByTagName("G"), function (columnData) {
//debugger;
//this.buildData(columnData);
this.fieldLength = this.fields.length;
this.record = [];
for (i = 0; i < this.fieldLength; i++) {
//debugger;
var fieldName = this.fields[i].name
this.record[i] = columnData.getAttribute(fieldName);
}
this.data.push(this.record);
}, this);
this.store = new Ext.data.ArrayStore({
fields : this.fields
});
this.store.loadData(this.data);
var grid = new Ext.grid.GridPanel({
store: this.store,
flex: 1,
columns: this.columns,
stripeRows: true,
id: 'RID',
autoHeight: true,
//sm: new Ext.grid.Checkbo;xSelectionModel({singleSelect:true}),
frame: true,
});
}
})
]
}]
Actually I was not getting scope so I placed here.
{
xtype: 'panel',
title: "Search Result",
height:500,
items: [{
xtype : 'GridPanel',
store: new Ext.data.ArrayStore({
fields : this.fields
}),
flex: 1,
columns: this.columns,
stripeRows: true,
id: 'RID',
autoHeight: true,
//sm: new Ext.grid.Checkbo;xSelectionModel({singleSelect:true}),
frame: true,
listeners {
afterRenderer : function(){
Ext.Ajax.request({
url: 'XML/1Cohart.xml',
scope: this,
timeout: global_constants.TIMEOUT,
method: "GET",
disableCaching: true,
failure: function(response) {
utils.showOKErrorMsg(sdisMsg.ajaxRequestFailed);
},
success: function(response) {
debugger;
var datas = response.responseXML;
Ext.each(datas.getElementsByTagName("HEADER"), function(header) {
this.buildField(header);
this.buildColumn(header);
}, this);
Ext.each(datas.getElementsByTagName("G"), function (columnData) {
//debugger;
//this.buildData(columnData);
this.fieldLength = this.fields.length;
this.record = [];
for (i = 0; i < this.fieldLength; i++) {
//debugger;
var fieldName = this.fields[i].name
this.record[i] = columnData.getAttribute(fieldName);
}
this.data.push(this.record);
}, this);
});
}
})
}
}
]
}

Cancel edit event in jqGrid inline edit

I'm using jqgrid inline edit in which i have a scenario to invoke the "cancel edit" button event and throw a message "Are you sure to cancel?".
//Code:
//Unload the grid.
$('#CommentsData').jqGrid('GridUnload');
//Comments grid start.
$("#CommentsData").jqGrid({
datastr: tableSrc,
hoverrows: false,
datatype: "jsonstring",
jsonReader: {
id: 'CommentId',
repeatitems: false
},
height: 'auto',
width: 'auto',
hidegrid: false,
gridview: true,
sortorder: 'desc',
sortname: 'DateTime',
pager: '#CommentsPager',
rowList: [], // disable page size dropdown
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: false, // disable current view record text like 'View 1-10 of 100'
caption: "Comments",
colNames: ['DateTime', 'UserName', 'Comments'],
colModel: [
{
name: 'DateTime', index: 'DateTime', width: 120, formatter: "date", sorttype: "date",
formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i A" }
},
{ name: 'UserName', index: 'UserName' },
{ name: 'CommentText', index: 'CommentText', editable: true }],
//Events to add and edit comments.
serializeRowData: function (postdata) {
var filterResult;
var jsonResult;
if (tableSrc == "")
jsonResult = $.parseJSON(commentDetails);
else
//Parse values bind to the comments.
jsonResult = $.parseJSON(tableSrc);
var newResult = new Object();
//Check if operation is edit.
if (postdata.oper == "edit") {
//Filter the edited comments from main source.
newResult = Enumerable.From(jsonResult).Where(function (s) { return s.CommentId = postdata.id }).First();
newResult.CommentText = postdata.CommentText;
}
else {
filterResult = Enumerable.From(jsonResult).First();
newResult.CommentText = postdata.CommentText;
newResult.TransactionId = filterResult.TransactionId;
newResult.TaskId = filterResult.TaskId;
}
filterResult = JSON.stringify(newResult);
$.ajax({
url: '#Url.Action("UpdateComments", "Home")',
datatype: 'json',
data: { 'resultData': filterResult, 'action': postdata.oper },
type: 'POST',
success: OnCompleteComments,
error: function (xhr, status, error) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
alert(xhr.statusText);
window.location.href = '#Url.Action("LogOut", "Account")';
}
else
alert(xhr.responseText);
}
});
//After update Load the grid.
function OnCompleteComments(result) {
selectTaskComment = false;
$('#dialog').dialog("close");
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
rowList = $('.ui-pg-selbox').val();
Loadgrid($("#TransactionsGrid").getGridParam('page'));
}
},
onSelectRow: function (id) {
selectTaskComment = true;
var thisId = $.jgrid.jqID(this.id);
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
var selectValues = jQuery('#CommentsData').jqGrid('getRowData', id);
thisId = $.jgrid.jqID(this.id);
if (selectValues.UserName == '#ViewBag.UserName' || '#ViewBag.IsAdmin' == 'True') {
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
}
else {
$("#" + thisId + "_iledit").addClass('ui-state-disabled');
$("#del_" + thisId).addClass('ui-state-disabled');
}
}
});
jQuery("#CommentsData").jqGrid('navGrid', '#CommentsPager', { edit: false, add: false, del: true, search: false, refresh: false }, {}, {},
{
//Delete event for comments
url: '#Url.Action("UpdateComments", "Home")',
serializeDelData: function (postData) {
return {
resultData: JSON.stringify(postData.id),
action: JSON.stringify(postData.oper),
}
},
errorTextFormat: function (xhr) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
window.location.href = '#Url.Action("LogOut", "Account")';
} else {
return xhr.responseText;
}
},
beforeSubmit: function () {
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
return [true, '', ''];
},
afterSubmit: function (response, postdata) {
selectTaskComment = false;
Loadgrid($("#TransactionsGrid").getGridParam('page'));
return [true, '', ''];
}
});
$('#CommentsData').jqGrid('inlineNav', '#CommentsPager', { edit: true, add: true, save: true, del: false, cancel: true });
$("#CommentsData_iledit").addClass('ui-state-disabled');
$("#del_CommentsData").addClass('ui-state-disabled');
In which event i have to write the code and throw the alert message?
Also if possible, need to know if the above code could be optimized. Because the delete event is written in a separate place comparing edit and add. I'm bit confused if this is right method.
The easiest way to invoke the "cancel edit" button would be executing the code
$("#CommentsData_ilcancel").click(); // trigger click event on Cancel button
where CommentsData is the id of the grid.

Kendo UI toolbar buttons

I am using a Kendo UI grid, which looks like this:
function refreshGrid()
{
$(".k-pager-refresh.k-link").click();
}
var editWindow;
var fields= {FullName: {type: "string"}, Email: {type: "string"}, LogCreateDate: {type: "date"}};
var gridColumns =
[{
width: 90,
command: {
name: "edit",
text: "Edit",
click: function(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
editWindow = $("#edit").kendoWindow({
title: "Edit User",
modal: true,
visible: false,
resizable: false,
width: 800,
height: 400,
content: 'myediturl' + dataItem.ID
});
editWindow.data("kendoWindow").center().open();
return false;
}
}
},
{
width: 90,
command: {
name: "delete",
text: "Delete",
click: function(e) {
//alert(this.dataItem($(e.currentTarget).closest("tr")).ID);
var id = this.dataItem($(e.currentTarget).closest("tr")).ID;
if (confirm("Are you sure you want to delete this user?"))
{
$.ajax({
type: 'POST',
url: '#Url.Action("deleteuser","admin",null, "http")' + "/" + this.dataItem($(e.currentTarget).closest("tr")).ID,
success: function (param) { refreshGrid(); },
async: false
});
}
return false;
}
}
},
{
field: "FullName",
title: "Full Name",
type: "string"
},
{
field: "Email",
title: "Email",
type: "string"
},
{
field: "LogCreateDate",
title: "Created",
type: "date",
template: '#= kendo.toString(LogCreateDate,"MM/dd/yyyy") #'
}];
//getSorts the columns of the grid
function getColumns() {
//Parsing the set of columns into a more digestable form
var columns = "";
for (var col in gridColumns) {
if (!!gridColumns[col].field)
{
if (columns.length > 0) {
columns += ";";
}
columns += gridColumns[col].field + "," + gridColumns[col].type;
}
}
return columns;
}
function getSorts(sortObject) {
if (!(sortObject)) {
return "";
}
//Getting the row sort object
var arr = sortObject;
if ((arr) && (arr.length == 0)) {
return "";
}
//Parsing the sort object into a more digestable form
var columnSet = getColumns();
var returnValue = "";
for (var index in arr) {
var type = "";
for (var col in gridColumns) {
if (gridColumns[col].field === arr[index].field) {
type = gridColumns[col].type;
}
}
returnValue += ((returnValue.length > 0) ? (";") : ("")) + arr[index].field + "," + (arr[index].dir === "asc") + "," + type;
}
return returnValue;
}
var grid;
$(function () {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "mydatasourceurl",
type: "POST",
},
parameterMap: function (data, type) {
data.filters = JSON.stringify(data.filter);
data.columns = JSON.stringify(getColumns());
data.sorts = JSON.stringify(getSorts(data.sort));
console.log(data);
return data;
}
},
schema: {
fields: fields,
data: "Data",
total: "Total"
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
toolbar: [{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}],
height: 392,
groupable: false,
sortable: true,
filterable: true,
pageable: {
refresh: true,
pageSizes: true
},
columns: gridColumns
});
grid = $("#grid").data("kendoGrid");
});
My create toolbar action is not triggered on click. How can I resolve this problem, is Kendo UI able to handle toolbar click events? The best solution I came up with looks like this:
$(".k-button.k-button-icontext.k-grid-add").click(function () {
//If the window doesn't exist yet, we create and initialize it
if (!grids[gridContainerID].addWindow.data("kendoWindow")) {
grids[gridContainerID].addWindow.kendoWindow({
title: "Add " + entityName,
width: "60%",
height: "60%",
close: onClose,
open: onAddOpen,
content: addUrl
});
}
//Otherwise we just open it
else {
grids[gridContainerID].addWindow.data("kendoWindow").open();
}
//Centralizing and refreshing to prepare the layout
grids[gridContainerID].addWindow.data("kendoWindow").center();
grids[gridContainerID].addWindow.data("kendoWindow").refresh();
return false;
});
Thanks in advance.
Instead of using that complex selector use the one that Kendo UI creates from name:
toolbar: [
{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}
],
and then:
$(".k-grid-Add", "#grid").bind("click", function (ev) {
// your code
alert("Hello");
});
In kendogrid docs here shows that there is no click configuration for grid toolbar buttons like grid.colums.commands.
To solve this problem you can reference following steps:
create a template for toolbar
<script id="grid_toolbar" type="text/x-kendo-template">
<button class="k-button" id="grid_toolbar_queryBtn">Query</button>
</script>
apply tempate to toolbar
toolbar:[{text:"",template: kendo.template($("#grid_toolbar").html())}]
add event listener to button
$("#grid_toolbar_queryBtn").click(function(e) {
console.log("[DEBUG MESSAGE] ", "query button clicked!");
});

Resources