Preserve record when InLineEditing JQGrid gives error when adding or changing - jqgrid

I am using InLineEditing JQGrid and when adding or changing a record, if it fails, the record disappears. I need to preserve these lines for the user to correct the wrong information and try to save the record again.
Below my snippet code
jQuery("#" + p_gridName).jqGrid('inlineNav', '#p' + p_gridName, {
edit : true, editicon : "ui-icon-pencil",
add : true, addicon : "ui-icon-plus",
save : true, saveicon : "ui-icon-disk", savetitle : "Salvar",
cancel : true, cancelicon : "ui-icon-cancel", canceltitle : "Cancelar",
editParams : {
keys : false, oneditfunc : null, successfunc : function (response) {
if (response != null && response.responseText != null) {
if (response.responseText.includes("OK")) {
alert(response.responseText);
reloadDataGrid(p_gridName, p_contentName, p_filtroGrid);
atualizaInfoStatusNavegacao('edit', valorChave, p_primaryKey, p_contentName);
return true;
} else {
alert(response.responseText);
return true;
}
}
}, afterrestorefunc: function (rowid) {
alert("after restore func");
return rowid;
}, restoreAfterError : false
},
addParams : {
useDefValues : true, addRowParams : {
successfunc : function (response) {
if (response.responseText.includes("OK")) {
alert(response.responseText);
reloadDataGrid(p_gridName, p_contentName, p_filtroGrid);
return true;
} else {
alert(response.responseText);
return true;
}
}
}
}
});

There is a option called restoreAfterError (see docs here), which by default is true. Set it to false in order to get the desired behavior.
This is a option (parameter) in editRow or saveRow.
EDIT
Your code should return true or better array with first value true/false and message like this
if (response != null && response.responseText != null) {
if (response.responseText.includes("OK")) {
alert(response.responseText);
reloadDataGrid(p_gridName, p_contentName, p_filtroGrid);
atualizaInfoStatusNavegacao('edit', valorChave, p_primaryKey, p_contentName);
return [true,''];
} else {
return [false, response.responseText];
}
} else {
return [false, 'no response from the server'];
}

Related

Laravel Datatable Data Display Issue

Below is my controller code. I have seen data in console and network tab ajax call but it is not displaying in view page table. Can someone please help me on this. Please tell me what i am doing wrong in this.
I have checked with static data passed directly on ajax call but also static data is not displaying too. but when i pass any string as static then it will display each character from string in different columns.
$finaldata = array();
foreach($reportDetails as $agentReportColumnKey => $agentReportColumnValue){
$tempfinaldata = array();
$tempfinaldata['Customer Name'] = isset($agentReportColumnValue->name) ? $agentReportColumnValue->name : '-';
$tempfinaldata['Number'] = isset($agentReportColumnValue->tel) ? $agentReportColumnValue->tel : '-';
$tempfinaldata['Email'] = isset($agentReportColumnValue->email) ? $agentReportColumnValue->email : '-';
$tempfinaldata['DOB'] = isset($agentReportColumnValue->signUpQuestionDetails->birthDay) ? $agentReportColumnValue->signUpQuestionDetails->birthDay : '-';
$tempfinaldata['Debt Level'] = $agentReportColumnValue->debtLevel->sum('amountOwned') ? $agentReportColumnValue->debtLevel->sum('amountOwned') : '-';
$tempfinaldata['Total Debt'] = isset($agentReportColumnValue->quickSolution[0]->totalDebts) ? $agentReportColumnValue->quickSolution[0]->totalDebts : '-';
$tempfinaldata['Employment'] = isset($agentReportColumnValue->signUpQuestionDetails->EmpStatus) ? $agentReportColumnValue->signUpQuestionDetails->EmpStatus : '-';
$tempfinaldata['Living Arrangements'] = isset($agentReportColumnValue->signUpQuestionDetails->rentOrOwnHome) ? $agentReportColumnValue->signUpQuestionDetails->rentOrOwnHome : '-';
$tempfinaldata['Downloaded Date'] = isset($agentReportColumnValue->userSignInDate) ? date('d-m-Y', strtotime($agentReportColumnValue->userSignInDate)) : '-';
if(strtolower($agentReportColumnValue->zCaseType) == 'completed') {
$tempfinaldata['Completed Date'] = isset($agentReportColumnValue->userStatusUpdatedDate) ? date('d-m-Y', strtotime($agentReportColumnValue->userStatusUpdatedDate)) : '-';
} else {
$tempfinaldata['Completed Date'] = '-';
}
$tempfinaldata['Case Status'] = isset($agentReportColumnValue->zCaseType) ? $agentReportColumnValue->zCaseType : '-';
$tempfinaldata['Solution Type'] = isset($agentReportColumnValue->UserSolution->solutionType) ? $agentReportColumnValue->UserSolution->solutionType : '-';
$finaldata[] = $tempfinaldata;
}
$totalRecords = UserNames::select('count(*) as allcount')->count();
$totalRecordswithFilter = UserNames::select('count(*) as allcount')->where('name', 'like', '%' .$searchValue . '%')->count();
return [
'aaData' => $finaldata,
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordswithFilter,
];
Below is my view file code.
$('document').ready(function()
{
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type : 'POST',
url : '{{ route('report.full_report_ajax_data') }}',
//dataType: 'json',
cache: false,
success : function(result) {
//pass data to datatable
console.log(result); // just to see I'm getting the correct data.
$('#full_report').DataTable({
"searching": false, //this is disabled because I have a custom search.
//"aaData": [result], //here we get the array data from the ajax call.
"aaData": [result], //here we get the array data from the ajax call.
//"bProcessing": true,
"aoColumns": [
{ "sTitle": "Customer Name" },
{ "sTitle": "Number" },
{ "sTitle": "Email" },
{ "sTitle": "DOB" },
{ "sTitle": "Debt Level" },
{ "sTitle": "Total Debt" },
{ "sTitle": "Employment" },
{ "sTitle": "Living Arrangements" },
{ "sTitle": "Downloaded Date" },
{ "sTitle": "Completed Date" },
{ "sTitle": "Case Status" },
{ "sTitle": "Solution Type" },
] //this isn't necessary unless you want modify the header
//names without changing it in your html code.
//I find it useful tho' to setup the headers this way.
});
}
});
});

how i make a condition with ajax and asp mvc

I want to put a condition if the user want to add a second appointment he receives an alert
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
this is my code in controller :
public JsonResult SaveEvent(Event e)
{
var status = false;
if (e.EventID > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.EventTitle = e.EventTitle;
v.StartDate = e.StartDate;
v.EndDate = e.EndDate;
v.EventDescription = e.EventDescription;
v.EventID = e.EventID;
v.ThemeColor = e.ThemeColor;
}
else
db.Events.Add(e);
db.SaveChanges();
status = true;
}
i want to make the user add one time his event and receive an alert i try but not work
I think i can help:
if(Session["appointment"] != "ok")<>
{
if (e.EventID > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.EventTitle = e.EventTitle;
v.StartDate = e.StartDate;
v.EndDate = e.EndDate;
v.EventDescription = e.EventDescription;
v.EventID = e.EventID;
v.ThemeColor = e.ThemeColor;
}
else
db.Events.Add(e);
db.SaveChanges();
Session["appointment"] = "ok";
return JSON(new{appointment="ok"});
}
}else
{
return JSON(new {appointment="no-good");
}
and controller:
function SaveEvent(data)
{
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function(data) {
if (data.appointment == "ok")
{
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
else { your msg error here }
},
error: function() {
alert('Failed');
}
})
}
})
dont not forget Session.Clear();
as the user logs out

How to stop Kendo UI dropdown from sorting alphabetically

I have been given the fun job on taking on someone elses code and trying to figure it out...
I have been tearing my hair out trying to figure out how to to stop a Kendo UI dropdown from sorting alphabetically ?
<select id="ddlArtworkStatuses" onlyPreparedValues="true"
readOnlyInput="true" data-bind="idNameOptions: artworkStatuses,
comboboxSelectedValue: artworkStatusId"></select>
For some reason this sorts althabetically but I want it to keep the order in the datasource. I have double checked to make sure it is in the order I want.
It doesn't use the standard way of using Kendo UI and I can't find any examples anywhere of using it this way?
It binds the view to the model with this line at the top of the view I believe?
<!-- ko with: fabricationModel -->
The vm.fabrication file is this:
(function (app) {
app.namespace("models");
var resources = {
unableToDeleteArtworkMessage: "This artwork cannot be deleted because it is linked to one or more of the following: Movements, Shows, POs. Or it has Imported Costs, Sales or Restoration Cases.",
unableToBlankArtworkFullyMessage: "This artwork has some data that will not be blanked if you continue. This could be one or more of the following: Movements, Shows, POs, Imported Costs, Sales or Restoration Cases. Do you want to continue?",
deleteArtworkTitle: "Delete artwork",
blankArtworkTitle: "Blank Artwork",
duplicateTitle: "New artwork form is pre-populated",
duplicateMessage: "You can make changes to Fabrication form fields. Record will be created after you press save button",
saveError: 'An error occured during artwork saving. Changes were not saved.'
};
app.models.FabricationModel = function (datasource) {
var emitter = new app.events.EventEmitter(),
self = this,
duplicateArtwork = ko.observable(false);
this.isNewArtwork = ko.observable(false);
this.isActivated = ko.observable(false);
this.showCreationInformation = ko.observable(true);
this.wipeArtworkModel = new app.models.WipeArtworkDialogModel(datasource);
this.internalArtworkModel = ko.observable();
this.editCategoryModel = new app.models.EditDhCategoryModel();
// alert("data=" + this.artworkStatuses);
this.isReadOnly = ko.computed(function () {
if (!self.internalArtworkModel()) {
return true;
}
return self.internalArtworkModel().isReadOnly();
});
this.canSaveStudioStatusOnly = ko.computed(function () {
if (!self.internalArtworkModel()) {
return false;
}
return self.internalArtworkModel().isUnblockStatusActive()
&& self.internalArtworkModel().isReadOnly()
&& self.internalArtworkModel().isStudioStatusVisible();
});
this.canSaveCatRaisOnly = ko.computed(function () {
if (!self.internalArtworkModel()) {
return false;
}
return self.internalArtworkModel().isReadOnly()
&& self.internalArtworkModel().isArchiveProvenanceWriter();
});
this.isNewOrDuplicating = ko.computed(function () {
return self.isNewArtwork() || duplicateArtwork();
});
this.activate = function (params) {
var id = params.id || 0;
self.isNewArtwork(!id);
return self.loadArtworkDetails(id);
};
this.isValid = function () {
return self.internalArtworkModel() && self.internalArtworkModel().errors().length == 0;
};
this.loadArtworkDetails = function (id) {
var action = self.isNewArtwork() ? datasource.artworks.getEmpty : datasource.artworks.getById;
return action(id)
.done(function (result) {
var mapper = app.mappers["fabrication"],
model = mapper.map(result.data);
self.internalArtworkModel(model);
self.editCategoryModel.categoryId(model.defaultDhCategoryId);
self.editCategoryModel.setModeAsCategoryChanging();
if (self.isNewArtwork()) {
self.editCategoryModel.setModeAsCreation();
self.editCategoryModel.show();
}
self.isActivated(true);
duplicateArtwork(false);
$("a#science-link").attr("href", window.location.href);
triggerLoadEvent();
});
};
this.saveArtwork = function () {
if (self.isValid()) {
return saveInternal($.noop);
}
};
this.editCategory = function () {
self.editCategoryModel.show();
};
this.onLoad = function (callback) {
emitter.subscribe("load", callback);
};
this.onCategoryChanged = function (callback) {
emitter.subscribe("category-changed", callback);
};
this.onDelete = function (callback) {
emitter.subscribe("delete", callback);
};
this.onCreated = function (callback) {
emitter.subscribe("artwork-created", callback);
};
this.onUpdated = function (callback) {
emitter.subscribe("artwork-updated", callback);
};
this.onBlanked = function (callback) {
emitter.subscribe("blanked", callback);
};
this.saveStudioStatusInt = function () {
return saveStudioStatusInternal($.noop);
};
this.saveCatRaisInt = function () {
return saveCatRaisInternal($.noop);
};
this.saveStudioStatus = ko.asyncCommand({
execute: function (complete) {
saveStudioStatusInternal(complete);
},
canExecute: function (isExecuting) {
return !isExecuting && self.canSaveStudioStatusOnly();
}
});
this.saveCatRais = ko.asyncCommand({
execute: function (complete) {
saveCatRaisInternal(complete);
},
canExecute: function (isExecuting) {
return !isExecuting && self.canSaveCatRaisOnly();
}
});
this.save = ko.asyncCommand({
execute: function (complete) {
return saveInternal(complete);
},
canExecute: function (isExecuting) {
if (!self.isValid()) {
showErrors();
}
return !isExecuting && self.isValid();
}
});
function saveStudioStatusInternal(completeCallback) {
var model = self.internalArtworkModel();
triggerSaveStudioStatusEvent();
datasource.artworks.saveStudioStatus(model.artworkId(), model.artworkStatusId(), model.studioStatusId).always(completeCallback);
}
function saveCatRaisInternal(completeCallback) {
var model = self.internalArtworkModel();
triggerSaveStudioStatusEvent();
datasource.artworks.saveCatRais(model.artworkId(), model.inclusion(), model.image(), model.details(), model.crReady(), model.selectedVolume.selected.value).always(completeCallback);
}
this.onSaveStudioStatus = function (callback) {
emitter.subscribe("saveStudioStatus", callback);
};
function triggerSaveStudioStatusEvent() {
emitter.publish("saveStudioStatus");
}
this.beginArtworkDeletion = function () {
if (!self.internalArtworkModel().canBeBlanked) {
jAlert(resources.unableToDeleteArtworkMessage, resources.deleteArtworkTitle);
return;
}
self.wipeArtworkModel.beginArtworkDeletion(self.internalArtworkModel().artworkId());
};
this.beginArtworkBlanking = function () {
if (!self.internalArtworkModel().canBeBlanked) {
//jAlert(resources.unableToBlankArtworkMessage, resources.blankArtworkTitle);
app.alerts.appConfirm(resources.unableToBlankArtworkFullyMessage, resources.blankArtworkTitle, function (ok) {
if (ok) {
self.wipeArtworkModel.beginArtworkBlanking(self.internalArtworkModel().artworkId());
}
});
return;
}
self.wipeArtworkModel.beginArtworkBlanking(self.internalArtworkModel().artworkId());
};
this.duplicateArtwork = function () {
if (!self.internalArtworkModel()) {
return;
}
duplicateArtwork(true);
resetModelBeforeDuplication();
if (self.isValid()) {
showErrors();
}
jAlert(resources.duplicateMessage, resources.duplicateTitle);
};
function saveInternal(completeCallback) {
var mapper = app.mappers["fabrication"];
//alert("saving now...");
var unmappedModel = mapper.toJS(self.internalArtworkModel());
if (duplicateArtwork()) {
return saveDuplicatedArtwork(unmappedModel, completeCallback);
}
if (unmappedModel.artworkId) {
return updateArtwork(unmappedModel, completeCallback);
}
return createArtwork(unmappedModel, completeCallback);
}
function saveDuplicatedArtwork(model, completeCallback) {
return datasource.artworks.duplicate(model)
.always(completeCallback)
.fail(function (response) {
jAlert(resources.saveError);
})
.done(function (id) {
triggerArtworkCreatedEvent(id);
duplicateArtwork(false);
self.showCreationInformation(true);
});
}
function updateArtwork(model, completeCallback) {
return datasource.artworks.save(model)
.always(completeCallback)
.fail(function (response) {
jAlert(resources.saveError);
})
.done(function (result) {
if (!result) {
return;
}
var mapper = app.mappers["fabrication"],
mappedModel = mapper.map(result.data);
triggerUpdateEvent(
{
dhCategory: mappedModel.dhCategory(),
refNumber: mappedModel.refNumber(),
computedTitle: mappedModel.computedTitle()
});
self.internalArtworkModel(mappedModel);
});
}
function createArtwork(model, completeCallback) {
return datasource.artworks.save(model)
.always(completeCallback)
.fail(function (response) {
jAlert(resources.saveError);
})
.done(function (id) {
if (id) {
triggerArtworkCreatedEvent(id);
}
});
}
function triggerLoadEvent() {
var model = self.internalArtworkModel();
emitter.publish("load", {
artworkId: model.artworkId() || 0,
dhCategory: model.dhCategory() || "",
refNumber: model.refNumber() || "",
computedTitle: model.computedTitle() || "",
isForSale: model.isForSale
});
}
function triggerArtworkCreatedEvent(artworkId) {
emitter.publish("artwork-created", artworkId);
}
function triggerCategoryChangedEvent() {
emitter.publish("category-changed", {
name: self.internalArtworkModel().dhCategoryName(),
id: self.internalArtworkModel().dhCategoryId()
});
}
function triggerDeleteEvent(e, artworkId) {
emitter.publish("delete", artworkId);
}
function triggerUpdateEvent(data) {
var model = self.internalArtworkModel();
data.isCategoryChanged = model.initialCategoryId !== model.dhCategoryId();
emitter.publish("artwork-updated", data);
}
function showErrors() {
var model = self.internalArtworkModel();
if (model) {
model.errors.showAllMessages();
}
}
function resetModelBeforeDuplication() {
var model = self.internalArtworkModel();
model.refNumber("");
model.computedTitle("");
model.isOnDisplay(false);
model.isOnRestoration(false);
model.salesStatus("Not set");
model.creationDate("");
model.creatorName("");
model.isFramed(false);
model.framedDate("");
model.framedUserName("");
model.framedUserInitials("");
model.framedUserId(null);
model.locations(null);
model.isInsuranceComponent(false);
model.dateWebsiteWork("");
model.dateWebsiteReady("");
model.dateWebsiteUploaded("");
model.dateRemovedFromWebsite("");
model.collectionListing("");
model.salesStatusChangedDate("");
model.salesStatusChangerUserInitials("");
model.salesStatusChangerUserName("");
self.showCreationInformation(false);
}
function triggerBlanked(artworkId) {
emitter.publish("blanked", { artworkId: artworkId, flag: true });
}
(function () {
self.editCategoryModel.onChanged(function (e, categoryId) {
self.internalArtworkModel().dhCategoryId(categoryId);
triggerCategoryChangedEvent();
});
self.editCategoryModel.onCancel(function () {
if (self.isNewArtwork()) {
self.isNewArtwork(false);
app.router.back();
}
});
self.wipeArtworkModel.onDelete(triggerDeleteEvent);
self.wipeArtworkModel.onBlank(function (e, artworkId) {
self.loadArtworkDetails(artworkId);
triggerBlanked(artworkId);
});
})();
};
})(app);
It also uses a mapper:
(function (app, ko) {
app.namespace("mappers");
var s = app.urls.shared,
datasource = app.datasource;
var mapSettings = {
selectedMedium: {
create: function (options) {
return new ListModel({
isRemoteSource: true,
url: s.get('dictionaryUrl'),
listType: datasource.dictionaryTypes.get("medium"),
currentValue: options.data,
nobutton: true,
templateName: "textAreaTemplate"
});
}
},
artist: {
create: function (options) {
return new ListModel({
isRemoteSource: true,
url: s.get('dictionaryUrl'),
listType: datasource.dictionaryTypes.get("artist"),
currentValue: options.data,
onlyPreparedValues: false
});
}
},
manager: {
create: function (options) {
return new ListModel({
isRemoteSource: true,
url: s.get('dictionaryUrl'),
listType: datasource.dictionaryTypes.get("manager"),
currentValue: options.data,
onlyPreparedValues: false
});
}
},
managerStatus: {
create: function (options) {
return new ListModel({
isRemoteSource: true,
url: s.get('dictionaryUrl'),
listType: datasource.dictionaryTypes.get("managerStatus"),
currentValue: options.data,
onlyPreparedValues: false
});
}
},
selectedVolume: {
create: function (options) {
return new ListModel({
isRemoteSource: true,
url: s.get('dictionaryUrl'),
listType: datasource.dictionaryTypes.get("volume"),
currentValue: options.data,
onlyPreparedValues: false,
readonly: !options.parent.isArchiveProvenanceWriter(),
editable: options.parent.isArchiveProvenanceWriter()
});
}
},
salesStatus: {
create: function (options) {
var value = options.data || "Not set";
return ko.observable(value);
}
},
oldReferences: {
create: function (options) {
return ko.observable(options.data);
}
},
copy: ['defaultDhCategoryId', "canBeDeleted", "canBeBlanked", "isForSale"],
ignore: ["dimensions", "dimensionUnits", "selectedMediumTypes", "selectedSeries", "selectedSubSeries", "selectedAkaNames", "selectedWebSiteMediumTypes", 'selectedWebSiteCategoryIds', "locations", "hasInTransitLocations"]
},
unmapSettings = {
ignore: ["selectedMedium", "artist", "manager", "managerStatus", "mediumTypesModel", "dimensionModel", "seriesModel", "subSeriesModel", "akaModel", "webSiteMediumTypesModel", "webSiteCategoriesModel", "selectedVolume"]
},
map = function (json) {
var convertedObject = ko.utils.parseJson(json);
var model = ko.mapping.fromJS(convertedObject, mapSettings);
model.artworkStatusesModel = new ListModel({
isRemoteSource: false,
currentValue: convertedObject.selectedArtworkStatus,
data: convertedObject.artworkStatuses,
//data: filteredSalesStatuses,
onlyPreparedValues: true,
allowNull: false,
readonly: true
});
alert("mooo=" + model.artworkStatuses()[0].name());
alert("mooo=" + model.artworkStatuses()[1].name());
alert("mooo=" + model.artworkStatuses()[2].name());
//alert("mooo=" + model.artworkStatuses()[3].name());
//alert("mooo=" + model.artworkStatuses()[4].name());
model.dhCategoryName = ko.computed(function () {
var categories = model.dhCategories();
for (var i = 0; i < categories.length; i++) {
var category = categories[i];
if (category.id() == model.dhCategoryId()) {
return category.name();
}
}
return "";
});
model.initialCategoryId = convertedObject.dhCategoryId;
model.dimensionModel = new app.models.DimensionModel(convertedObject.dimensions);
ko.utils.arrayForEach(convertedObject.dimensionUnits, function (unit) {
model.dimensionModel.units.push(unit);
});
model.locations = ko.observable(convertedObject.locations ? {
archivedLocations: $.map(convertedObject.locations, function (elem) {
return elem.isArchived ? elem : null;
}),
activeLocations: $.map(convertedObject.locations, function (elem) {
return elem.isArchived ? null : elem;
}),
hasInTransitLocations: convertedObject.hasInTransitLocations
} : convertedObject.locations);
model.mediumTypesModel = new app.models.MultilistModel(convertedObject.selectedMediumTypes, { url: s.get("mediumTypesUrl") });
model.seriesModel = new app.models.MultilistModel(convertedObject.selectedSeries, { url: s.get("seriesUrl") });
model.subSeriesModel = new app.models.MultilistModel(convertedObject.selectedSubSeries, { url: s.get("subSeriesUrl") });
model.akaModel = new app.models.MultilistModel(convertedObject.selectedAkaNames, { url: s.get("akaUrl") });
model.webSiteMediumTypesModel = new app.models.MultilistModel(convertedObject.selectedWebSiteMediumTypes, { url: s.get("webSiteMediumTypeUrl") });
model.webSiteCategoriesModel = new app.models.MultilistModel(convertedObject.selectedWebSiteCategories, { url: s.get("webSiteCategoryUrl") });
model.isStudioStatusVisible = ko.computed(function () {
var foundStatuses = ko.utils.arrayFilter(model.artworkStatuses(), function (status) {
return status.id() == model.artworkStatusId();
});
var currentStatus = foundStatuses[0];
if (currentStatus) {
return currentStatus.name().toLowerCase() == "in progress";
}
return false;
});
addValidationOptions(model);
return model;
},
toJS = function (artwork) {
var result = ko.mapping.toJS(artwork, unmapSettings);
result.artist = artwork.artist.toJS();
result.manager = artwork.manager.toJS();
result.managerStatus = artwork.managerStatus.toJS();
result.selectedMedium = artwork.selectedMedium.toJS();
result.selectedVolume = artwork.selectedVolume.toJS();
result.dimensions = artwork.dimensionModel.toJS();
result.selectedMediumTypes = artwork.mediumTypesModel.toJS();
result.selectedSeries = artwork.seriesModel.toJS();
result.selectedSubSeries = artwork.subSeriesModel.toJS();
result.selectedAkaNames = artwork.akaModel.toJS();
result.selectedWebSiteMediumTypes = artwork.webSiteMediumTypesModel.toJS();
result.selectedWebSiteCategories = artwork.webSiteCategoriesModel.toJS();
return result;
};
function isValidationRequired(model) {
var artworkStatus = ko.utils.unwrapObservable(model.artworkStatusId);
var dhCategory = ko.utils.unwrapObservable(model.dhCategoryId);
return artworkStatus == app.global.dictionary.get("compiteArtworkStatus")
&& dhCategory != app.global.dictionary.get("ignoreDHCatigory");
}
function addValidationOptions(model) {
model.artworkStatusId.extend({ required: true });
model.title.extend({ required: true });
model.artist.selected.value.extend({ required: true });
model.startYear.extend({
lessEqualThan: {
params: model.endYear,
onlyIf: function () {
return (model.endYear() != undefined && model.endYear() != null);
},
message: 'From Date should be less or equal than a To Date'
}
});
model.endYear.extend({
required: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "To Date field is required"
}
});
model.selectedMedium.selected.value.extend({
required: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "Medium is required"
}
});
model.mediumTypesModel.hasValue.extend({
equal: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "Medium Type is required"
}
});
model.akaModel.hasValue.extend({
equal: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "Aka is required"
}
});
model.isInsuranceComponent.extend({
equal: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "At least 1 Insurance component should be chosen"
}
});
model.dimensionModel.hasDimensions.extend({
equal: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "The Dimension fields should be filled"
}
});
model.errors = ko.validation.group(model, { deep: true });
}
app.mappers.fabrication = {
settings: mapSettings,
map: map,
toJS: toJS
};
})(app, ko);
Where I have the alerts, the items are in the right order, so somewhere they are getting sorted but cant find out where?!
I hope someone can help?
It would be really appreciated.
Many thanks,
David.

Semantic UI custom form validation with Ajax

I am trying to implement custom form validation rules for my username field, which should check the database for duplicated or not.
After Searching on the internet, I had write out some code, and it successful getting the response "true / false" from my server. But the fields in the form doesn't update as it should. Below was my javascript code.
$.fn.form.settings.rules.checkUsername = function(value) {
var res = true;
$.ajax({
async : false,
url: '<?= Yii::app()->createAbsoluteUrl('home/doCheckUsername') ?>',
type : "POST",
data : {
username : value
},
dataType: "json",
success: function(data) {
if (data.result == true) {
console.log(data.result);
return false;
} else {
console.log(data.result);
return true;
}
}
});
};
$('.ui.form').form({
username: {
identifier : 'username',
rules: [{
type : 'checkUsername',
prompt : 'Username Already Exists'
}]
}
// some other rules
}, {
inline : true,
on : 'blur',
onSuccess : function(){
//post to controller
}
});
The console.log showing me the correct result as I want, but I keep getting "Username Is Exist" as show at the picture
Semantic UI form Validation result
May I know where are the place I doing it wrong ?
Somehow, Added Async at the ajax solve the problem.
$.ajax({
async : false,
url: '<?= Yii::app()->createAbsoluteUrl('home/doCheckUsername') ?>',
type : "POST",
async: false,
data : {
username : value
},
dataType: "json",
success: function(data) {
if (data.result == true) {
console.log(data.result);
res = false;
}
}
});
Put result in the res variable and return the res variable after the ajax call !
Work for me :
$.fn.form.settings.rules.checkemail = function(value) {
var res = true;
$.ajax({
async : false,
url: '../php/email_exist.php',
type : "POST",
async: false,
data : {
email : value
},
success: function(data) {
console.log(data);
if (data == "0") {
console.log("OK");
res = true;
} else {
console.log("KO");
res = false;
}
}
});
return res;
};
$.fn.form.settings.rules.checkUsername = function(value) {
var res = true;
$.ajax({
async : false,
url: '<?= Yii::app()->createAbsoluteUrl('home/doCheckUsername') ?>',
type : "POST",
data : {
username : value
},
dataType: "json",
success: function(data) {
if (data.result == true) {
//console.log(data.result);
//return false;
**value = 0;**
} else {
//console.log(data.result);
//return true;
**value = 1;**
}
}
});
**return (value == 1 )? true : false;**
};
$('.ui.form').form({
username: {
identifier : 'username',
rules: [{
type : '**checkUsername[value]**',
prompt : 'Username Already Exists'
}]
}
// some other rules
}, {
inline : true,
on : 'blur',
onSuccess : function(){
//post to controller
}
});

using jquery to validate postal code based on country

Working on site where we currently accept US zip codes. I already have jquery validate working for that. What i want to do now is add a drop down for the user to select country, and then based on the country they selected, it will validate the postal code to make sure it matches.
Can someone give me some pointers on how i can do this? Basically, i just need to change the regex the validator function is using based on the country drop down. The (what i assume is) relevant section of the jquery validator function is this:
(function ($) {
$.fn.validate = function (options) {
var defaults = {
invalidClass: 'error',
rules: {
req: /.{1,}/g,
email: /[\w\.=-]+#[\w\.-]+\.[\w]{2,3}/g,
phone: /\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/g,
zip: /\d{5}$|^\d{5}-\d{4}/g,
//password: /^(?=.*\d)(?=.*[a-zA-Z]).{8,20}$/g,
password: /^(?=.{8,20}$)(?=.*\d)(?=.*[a-zA-Z]).*/g,
//nospecialchars: /[^<>?,\/\\\[\]\{\}\|!##$%^&*()_+;:"]{1,}/g
nospecialchars: /^(?!.*[?<>;]).+$/g
},
error_messages: {
req: 'Oops..',
email: 'Please enter your email address.',
phone: '',
zip: 'Please give me a valid zip.',
max: 'too many characters.',
password: '',
nospecialchars: ''
},
success: null,
failure: null
},
errors = [],
opts = $.extend(true, defaults, options);
return this.each(function () {
var $this = $(this);
$(this).find('input[type="submit"]:not(.cancel), button').click(function () {
errors = [];
validate_fields($this);
if ($this.find('.error').length === 0) {
if (typeof opts.success == 'function')
return opts.success();
}
else {
if (typeof opts.failure == 'function')
return opts.failure(errors);
}
});
});
I'm not very familiar with jquery so i don't know what the syntax is here for me to create an if-else or case statement to set the regex.
Thanks if advance for any help.
edit: Here's the bit of code that actually calls the validation
<script type="text/javascript">
$(function () {
setForm();
$('form').validate({
error_messages: {
req: null
},
failure: function (errors) {
var sel = '';
$(".errMsg").hide();
for (x in errors) {
sel += ',#' + errors[x][0];
}
if (sel.length > 0) {
sel = sel.substring(1);
$(sel).parent().find(".errMsg").show(0, function () {
$('#home .orange_box, #home .HomeRight').height('auto');
$('#infov .white_box, #infov .orangeRight').height('auto');
$('#findt .orange_box, #findt .HomeRight').height('auto');
if ($.browser.msie && $.browser.version == 8) {
evenColumns('#home .orange_box', '#home .HomeRight', -16);
evenColumns('#infov .white_box', '#infov .orangeRight', -16);
evenColumns('#findt .orange_box', '#findt .HomeRight', -16);
}
else {
evenColumns('#home .orange_box', '#home .HomeRight', -15);
evenColumns('#infov .white_box', '#infoforv .orangeRight', -15);
evenColumns('#findt .orange_box', '#findt .HomeRight', -15);
}
});
}
return false;
},
success: function () {
$(".errMsg").hide();
return true;
}
});
I would create an object, witch has:
function for the validation
object for all other countries
object for default rules
validation = {
validate : function( sCountryName, sToValidate ){
return ( null != sToValidate.match( this.countries[ sCountryName ] ? this.countries[ sCountryName ].zip : this.defaultRules.zip ))
},
countries : {
england : {
zip : /\d{5}$|^\d{5}-\d{4}/g
}
},
defaultRules : {
zip : /\d{5}$|^\d{5}-\d{4}/g
}
}

Resources