test_form.pt
3.35 KB
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
<html metal:use-macro="load: ./base3.1.pt" tal:define="
scripts scripts|scripts;
readonly readonly|readonly;">
<div metal:fill-slot="content">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-fw fa-plus"></i> ${request.title}</h3>
</div>
<div class="panel-body">
<div tal:content="structure form"></div>
</div>
</div>
</div>
<div metal:fill-slot="scripts">
<script>
$(document).ready(function () {
$(".readonly").attr("readonly", true);
$(".date").attr("readonly", true);
function convertFormToJSON(form) {
const array = $(form).serializeArray(); // Encodes form elements as an array of names and values.
const json = {};
$.each(array, function () {
// Handle multiple inputs with the same name (e.g., checkboxes)
if (json[this.name]) {
if (!json[this.name].push) {
json[this.name] = [json[this.name]];
}
json[this.name].push(this.value || '');
} else {
json[this.name] = this.value || '';
}
});
return json;
}
var submitType = 'POST';
$('form button[type="submit"]').on('click', function () {
// Remove any previously added hidden inputs for this form
if ($(this).val() === 'cancel') {
location.href = "${request.route_url('base-xhr-test')}";
return false;
} else if ($(this).val() === 'delete') {
submitType = 'DELETE';
}
});
$('form').on('submit', function (event) {
event.preventDefault();
console.log('Form submitted!');
var id = "${request.matchdict.get('id', '')}";
const formObject = convertFormToJSON(this);
if (id) {
formObject['id'] = id;
}
var message = '';
if (submitType == 'POST' && id) {
submitType = 'PUT';
message = 'Mengubah';
} else if (submitType === 'DELETE') {
message = 'Menghapus';
} else {
message = 'Menambah';
}
// Convert the JavaScript object to a JSON string
const formData = JSON.stringify(formObject);
var url = "${request.route_url('base-xhr-test-api')}";
$.ajax({
url: url,
type: submitType,
data: formData,
contentType: 'application/json',
success: function (response) {
console.log('Success:', response);
if (submitType === 'DELETE') {
location.href = "${request.route_url('base-xhr-test')}";
return;
}
data = response.data;
if (Array.isArray(data)) {
data = data[0];
}
id = data.id;
$("#success").html('Sukses: ' + message + ' data ID ' + id);
$("#success").show();
},
error: function (error) {
if (error.code === 404) {
location.href = "${request.route_url('base-xhr-test')}";
return;
}
console.error('Error:', error);
$("#errors").html('Error: ' + message + ' ' + error.responseText);
$("#errors").show();
}
});
});
${structure:scripts}
});
</script>
<div metal:define-slot="scripts"></div>
</div>
</html>