Newer
Older
/**
* @author Rafael Ostertag <rafael.ostertag@math.uzh.ch>
*/
/* global $ */

Rafael Ostertag
committed
/* global EventEmitter */
var QfqNS = QfqNS || {};
// TODO: This object is getting too big. Start refactoring.
n.QfqForm = function (formId, submitTo, deleteUrl, dataRefreshUrl, fileUploadTo) {
this.dataRefreshUrl = dataRefreshUrl;
this.fileUploadTo = fileUploadTo;
// This is required when displaying validation messages, in to activate the tab, which has validation issues

Rafael Ostertag
committed
this.eventEmitter = new EventEmitter();
this.getSaveButton().addClass("disabled").attr("disabled", "disabled");

Rafael Ostertag
committed
this.form.on('form.changed', this.changeHandler.bind(this));
this.form.on('form.reset', this.resetHandler.bind(this));
this.form.on('form.submit.successful', this.submitSuccessDispatcher.bind(this));
this.form.on('form.submit.failed', function (obj) {
n.Helper.showAjaxError(null, obj.textStatus, obj.errorThrown);
});
this.getSaveButton().click(this.handleSaveClick.bind(this));
this.getCloseButton().click(this.handleCloseClick.bind(this));
this.getNewButton().click(this.handleNewClick.bind(this));
this.getDeleteButton().click(this.handleDeleteClick.bind(this));

Rafael Ostertag
committed
this.setupFormUpdateHandler();
this.fileUploader = new n.FileUpload('#' + this.formId, this.fileUploadTo, this.getSip());

Rafael Ostertag
committed
this.fileUploader.on('fileupload.started', this.startUploadHandler);
this.fileUploader.on('fileupload.upload.success', this.fileUploadSuccessHandler);

Rafael Ostertag
committed
this.fileUploader.on('fileupload.upload.failed',
function (obj) {
n.Helper.showAjaxError(null, obj.textStatus, obj.errorThrown);

Rafael Ostertag
committed
this.fileUploader.on('fileupload.ended', this.endUploadHandler);

Rafael Ostertag
committed
n.QfqForm.prototype.on = n.EventEmitter.onMixin;
n.QfqForm.prototype.setBsTabs = function (bsTabs) {
this.bsTabs = bsTabs;
};
n.QfqForm.prototype.fileUploadSuccessHandler = function (obj) {
if (!obj.data.status) {
throw Error("Response on file upload missing status");
}
if (obj.data.status === "error") {
var alert = new n.Alert(obj.data.message, "error");

Rafael Ostertag
committed
/**
*
* @param $button
* @param enabled {boolean}
*
* @private
*/
n.QfqForm.prototype.setButtonEnabled = function ($button, enabled) {
if (!$button) {
n.Log.error("QfqForm#setButtonEnabled(): no button provided.");
return;
}
if (!enabled) {
$button.addClass("disabled");
$button.attr("disabled", "disabled");
} else {
$button.removeClass("disabled");
$button.removeAttr("disabled");
}
};

Rafael Ostertag
committed
n.QfqForm.prototype.setupFormUpdateHandler = function () {
$('input[data-load],select[data-load]').on('change', this.formUpdateHandler.bind(this));

Rafael Ostertag
committed
n.QfqForm.prototype.formUpdateHandler = function () {
var that = this;
$.post(this.dataRefreshUrl, this.form.serialize(), "json")
.fail(n.Helper.showAjaxError)
.done(function (data) {

Rafael Ostertag
committed
this.handleFormUpdate(data);
}.bind(that));
};

Rafael Ostertag
committed
n.QfqForm.prototype.handleFormUpdate = function (data) {
if (!data.status) {
throw new Error("Expected 'status' attribute to be present.");
}
if (data.status === "error") {
var alert = new n.Alert("Error while updating form:<br>" + (data.message ? data.message : "No reason" +

Rafael Ostertag
committed
" given"), "error");
alert.show();
return;
}
if (data.status === "success") {
if (!data['form-update']) {
throw new Error("'form-update' attribute missing in form update data");
}
this.applyElementConfiguration(data['form-update']);
return;
}
throw new Error("Unexpected status: '" + data.status + "'");
};

Rafael Ostertag
committed
/**
* @private
*/
n.QfqForm.prototype.destroyFormAndSetText = function (text) {
this.form = null;
$('#' + this.formId).replaceWith($("<p>").append(text));

Rafael Ostertag
committed
this.eventEmitter.emitEvent('qfqform.destroyed', n.EventEmitter.makePayload(this, null));

Rafael Ostertag
committed
};
/**
* @private
*/
n.QfqForm.prototype.handleSaveClick = function () {
// First, remove all validation states, in case a previous submit has set a validation state, thus we're not
// stockpiling them.
this.clearAllValidationStates();
this.form.submitTo(this.submitTo);
};
/**
* @private
*/
n.QfqForm.prototype.handleCloseClick = function () {
var alert = new n.Alert("You have unsaved changes. Do you want to close?", "warning", "yesnosave");

Rafael Ostertag
committed
alert.on('alert.save', function () {

Rafael Ostertag
committed
alert.on('alert.ok', function () {
window.history.back();
});
alert.show();
} else {
window.history.back();
}
};
/**
* @private
*/

Rafael Ostertag
committed
n.QfqForm.prototype.handleNewClick = function (event) {
event.preventDefault();
var anchorTarget = event.target.getAttribute("href");

Rafael Ostertag
committed
if (this.form.getFormChanged()) {
var alert = new n.Alert("You have unsaved changes. Do you want to close?", "warning", "yesnosave");
var that = this;
alert.on('alert.save', function () {
that.form.submitTo(that.submitTo);
window.location = anchorTarget;
});
alert.on('alert.ok', function () {
window.location = anchorTarget;
});
alert.show();
}
};
/**
* @private
*/
n.QfqForm.prototype.handleDeleteClick = function () {
n.Log.debug("delete click");
var alert = new n.Alert("Do you really want to delete the record?", "warning", "yesno");

Rafael Ostertag
committed
alert.on('alert.ok', function () {
$.post(that.deleteUrl)
.done(that.ajaxDeleteSuccessDispatcher.bind(that))
.fail(n.Helper.showAjaxError);
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/**
*
* @param data
* @param textStatus
* @param jqXHR
*
* @private
*/
n.QfqForm.prototype.ajaxDeleteSuccessDispatcher = function (data, textStatus, jqXHR) {
if (!data.status) {
throw new Error("No 'status' property 'data'");
}
switch (data.status) {
case "error":
this.handleLogicDeleteError(data);
break;
case "success":
this.handleDeleteSuccess(data);
break;
default:
throw new Error("Status '" + data.status + "' unknown.");
}
};
/**
*
* @param data
*
* @private
*/
n.QfqForm.prototype.handleDeleteSuccess = function (data) {

Rafael Ostertag
committed
this.setButtonEnabled(this.getCloseButton(), false);
this.setButtonEnabled(this.getDeleteButton(), false);
this.setButtonEnabled(this.getSaveButton(), false);
this.setButtonEnabled(this.getNewButton(), false);
this.destroyFormAndSetText("Record has been deleted!");
if (!data.redirect || data.redirect === "client") {
window.history.back();
return;
}
if (data.redirect === "no") {
var alert = new n.Alert("redirect=='no' not allowed", "error");
alert.show();
return;
}
if (data.redirect === "url" || data['redirect-url']) {
window.location = data['redirect-url'];
return;
}
};
/**
*
* @param data
*
* @private
*/
n.QfqForm.prototype.handleLogicDeleteError = function (data) {
if (!data.message) {
throw Error("Status is 'error' but required 'message' attribute is missing.");
}
n.QfqForm.prototype.changeHandler = function (obj) {
this.getSaveButton().removeClass("disabled");
this.getSaveButton().addClass("alert-warning");
this.getSaveButton().removeAttr("disabled");
};
/**
*
n.QfqForm.prototype.resetHandler = function (obj) {
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
this.getSaveButton().removeClass("alert-warning");
this.getSaveButton().addClass("disabled");
this.getSaveButton().attr("disabled", "disabled");
};
/**
*
* @returns {jQuery|HTMLElement}
*
* @private
*/
n.QfqForm.prototype.getSaveButton = function () {
return $("#save-button");
};
/**
*
* @returns {jQuery|HTMLElement}
*
* @private
*/
n.QfqForm.prototype.getCloseButton = function () {
return $("#close-button");
};
/**
*
* @returns {jQuery|HTMLElement}
*
* @private
*/
n.QfqForm.prototype.getDeleteButton = function () {
return $("#delete-button");
};
/**
*
* @returns {jQuery|HTMLElement}
*
* @private
*/
n.QfqForm.prototype.getNewButton = function () {

Rafael Ostertag
committed
return $("#form-new-button");
n.QfqForm.prototype.submitSuccessDispatcher = function (obj) {
if (!obj.data.status) {
throw new Error("No 'status' property in 'data'");
this.handleLogicSubmitError(obj.target, obj.data);
this.handleSubmitSuccess(obj.target, obj.data);
throw new Error("Status '" + obj.data.status + "' unknown.");
/**
*
* @param form
* @param data
*
* @private
*/
n.QfqForm.prototype.handleLogicSubmitError = function (form, data) {
if (!data.message) {
throw Error("Status is 'error' but required 'message' attribute is missing.");
}
if (data["field-name"] && this.bsTabs) {
var tabId = this.bsTabs.getContainingTabIdForFormControl(data["field-name"]);
if (tabId) {
this.bsTabs.activateTab(tabId);
}
this.setValidationState(data["field-name"], "error");
this.setHelpBlockValidationMessage(data["field-name"], data["field-message"]);
}
};
/**
*
* @param form
* @param data
*
* @private
*/
n.QfqForm.prototype.handleSubmitSuccess = function (form, data) {
if (this.lastButtonPress === 'save' || !data.redirect || data.redirect === "no") {

Rafael Ostertag
committed
// do we have to update the HTML Form?
if (data['form-update']) {
this.applyElementConfiguration(data['form-update']);
}
return;
}
if (data.redirect === "client") {
window.history.back();
return;
}
if (data.redirect === "url" || data['redirect-url']) {
window.location = data['redirect-url'];
return;
}
};
n.QfqForm.prototype.getFormGroupByControlName = function (formControlName) {
var $formControl = $("[name='" + formControlName + "']");
n.Log.debug("QfqForm.setValidationState(): unable to find form control with name '" + formControlName + "'");
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
return null;
}
var iterator = $formControl[0];
while (iterator !== null) {
var $iterator = $(iterator);
if ($iterator.hasClass('form-group')) {
return $iterator;
}
iterator = iterator.parentElement;
}
return null;
};
n.QfqForm.prototype.setValidationState = function (formControlName, state) {
var $formGroup = this.getFormGroupByControlName(formControlName);
if ($formGroup) {
$formGroup.addClass("has-" + state);
}
};
n.QfqForm.prototype.resetValidationState = function (formControlName) {
var $formGroup = this.getFormGroupByControlName(formControlName);
$formGroup.removeClass("has-warning");
$formGroup.removeClass("has-error");
$formGroup.removeClass("has-success");
};
n.QfqForm.prototype.clearAllValidationStates = function () {
$('.has-warning,.has-error,.has-success').removeClass("has-warning has-error has-success");
$('[data-qfq=validation-message]').remove();
};
/**
*
* @param formControlName
* @param text
*/
n.QfqForm.prototype.setHelpBlockValidationMessage = function (formControlName, text) {
* Why is this method here and not in FormGroup? Adding this particular method to FormGroup is easy, however
* QfqForm.clearAllValidationStates() would not find its proper place in FormGroup, since FormGroup operates
* on one element. We would end up having the responsibilities spread across several classes, which would be
* confusing.
*/
var $formGroup = this.getFormGroupByControlName(formControlName);
if (!$formGroup) {
return;
}
var $helpBlockColumn;
var $formGroupSubDivs = $formGroup.find("div");
if ($formGroupSubDivs.length < 3) {
$helpBlockColumn = $("<div>").addClass("col-md-4");
$formGroup.append($helpBlockColumn);
} else {
$helpBlockColumn = $($formGroupSubDivs[2]);
}
$helpBlockColumn.append(
$("<p>")
.addClass("help-block")
.attr("data-qfq", "validation-message")
.append(text)
);

Rafael Ostertag
committed
/**
*
* @param configuration {array} array of objects.
*/
n.QfqForm.prototype.applyElementConfiguration = function (configuration) {

Rafael Ostertag
committed
var arrayLength = configuration.length;
for (var i = 0; i < arrayLength; i++) {
var configurationItem = configuration[i];
var formElementName = configurationItem["form-element"];
if (formElementName === undefined) {
n.Log.error("configuration lacks 'form-element' attribute. Skipping.");

Rafael Ostertag
committed
continue;
}

Rafael Ostertag
committed
var element = n.Element.getElement(formElementName);

Rafael Ostertag
committed
if (configurationItem.value !== undefined) {
element.setValue(configurationItem.value);

Rafael Ostertag
committed
if (configurationItem.readonly !== undefined) {
element.setReadOnly(configurationItem.readonly);

Rafael Ostertag
committed
if (configurationItem.disabled !== undefined) {
element.setEnabled(!configurationItem.disabled);

Rafael Ostertag
committed
/**
* @private
* @param triggeredBy

Rafael Ostertag
committed
*/
n.QfqForm.prototype.startUploadHandler = function (obj) {
$(obj.target).after(

Rafael Ostertag
committed
$('<i>').addClass('spinner')
);
};
/**
* @private
* @param triggeredBy

Rafael Ostertag
committed
*/
n.QfqForm.prototype.endUploadHandler = function (obj) {
var $siblings = $(obj.target).siblings();

Rafael Ostertag
committed
$siblings.filter("i").remove();
};
/**
* Retrieve SIP as stored in hidden input field.
*
* @returns {string} sip
*/
n.QfqForm.prototype.getSip = function () {
return $('#' + this.formId + ' input[name=s]').val();
};