define(['jquery', 'core/templates'], function($, templates) {
var Form = function() {
this._fieldsets = {};
this.elements = {};
this.formPage = ;
};
// These two methods would actually be using classes for the form.
Form.prototype.add_top = function() {
this.formPage += '<form action="">';
};
Form.prototype.add_bottom = function() {
this.formPage += '
<button type="button" id="mod_lesson_editor_save_btn">Save</button>';
this.formPage += '<button type="button" id="mod_lesson_editor_cancel_btn">Cancel</button>
</form>
';
};
Form.prototype.addFieldset = function(key, title) {
this._fieldsets[key] = title;
};
Form.prototype.handleError = function(errorname, errorelement, elementtype, errormessage) {
var index = elementtype + "-" + errorname;
this.elements[index].set_error(errormessage);
var htmlpromise = templates.render(this.elements[index].template, this.elements[index]);
$.when(htmlpromise).then(function(newhtml) {
templates.replaceNode(errorelement, newhtml);
});
}
Form.prototype.handleErrors = function(errors) {
// Need to loop through all potential errors.
var errorname = errors.errors.name;
var errorelementid = $(":input[name=" + errorname + "]").attr("id");
// console.log(errorelementid);
var errorelement = $("#fitem_" + errorelementid);
// console.log(errorelement);
// Get the form element type.
var elementtype = errorelement.attr("data-field-type");
Form.prototype.handleError.call(this, errorname, errorelement, elementtype, errors.errors.message);
}
Form.prototype.addElement = function(element) {
var index = element.type + "-" + element.name;
this.elements[index] = element;
};
Form.prototype.showElements = function() {
console.log(this.elements);
};
Form.prototype.printForm = function() {
var allpromises = [];
for (index in this.elements) {
allpromises.push(this.elements[index].show());
}
return $.when.apply($.when, allpromises).then(function() {
Form.prototype.add_top.call(this);
var schema = arguments;
for (index in schema) {
this.formPage += schema[index][0];
}
Form.prototype.add_bottom.call(this);
return this.formPage;
}, function() {
return 'default html';
});
}
return Form;