/
form-wrapper.js
108 lines (104 loc) · 3.62 KB
/
form-wrapper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/** Generic form view */
import Form from "mvc/form/form-view";
import Ui from "mvc/ui/ui-misc";
var View = Backbone.View.extend({
initialize: function(options) {
this.model = new Backbone.Model(options);
this.url = this.model.get("url");
this.redirect = this.model.get("redirect");
if (options && options.active_tab) {
this.active_tab = options.active_tab;
}
this.setElement("<div/>");
this.render();
},
render: function() {
var self = this;
$.ajax({
url: Galaxy.root + this.url,
type: "GET"
})
.done(response => {
var options = $.extend({}, self.model.attributes, response);
var form = new Form({
title: options.title,
message: options.message,
status: options.status || "warning",
icon: options.icon,
initial_errors: true,
errors: options.errors,
inputs: options.inputs,
buttons: {
submit: new Ui.Button({
tooltip: options.submit_tooltip,
title: options.submit_title || "Save",
icon: options.submit_icon || "fa-save",
cls: "btn btn-primary ui-clear-float",
onclick: function() {
self._submit(form);
}
})
}
});
self.$el.empty().append(form.$el);
})
.fail(response => {
self.$el.empty().append(
new Ui.Message({
message: `Failed to load resource ${self.url}.`,
status: "danger",
persistent: true
}).$el
);
});
},
_submit: function(form) {
var self = this;
$.ajax({
url: Galaxy.root + self.url,
data: JSON.stringify(form.data.create()),
type: "PUT",
contentType: "application/json"
})
.done(response => {
var params = {};
if (response.id) {
params.id = response.id;
} else {
params = {
message: response.message,
status: "success",
persistent: false
};
}
if (self.redirect) {
window.location = `${Galaxy.root + self.redirect}?${$.param(params)}`;
} else {
form.data.matchModel(response, (input, input_id) => {
form.field_list[input_id].value(input.value);
});
self._showMessage(form, success_message);
}
})
.fail(response => {
self._showMessage(form, {
message: response.responseJSON.err_msg,
status: "danger",
persistent: false
});
});
},
_showMessage: function(form, options) {
var $panel = form.$el
.parents()
.filter(function() {
return ["auto", "scroll"].indexOf($(this).css("overflow")) != -1;
})
.first();
$panel.animate({ scrollTop: 0 }, 500);
form.message.update(options);
}
});
export default {
View: View
};