File: /var/www/ivs.kaunokolegija.lt/laravel/resources/views/layouts/form_modal.blade.php
<div id="create{{ $compName }}Modal" title="{{ $title }}" style="display:none;">
<div class="modal-body">
<div class="form-group">
@include($fieldsLink)
</div>
</div>
</div>
@php
$upload_url = isset($upload_url) ? $upload_url : null;
@endphp
<script>
$(document).ready(function () {
const modalId = "#create{{ $compName }}Modal";
const saveButtonId = "#save{{ $compName }}ModalButton";
const openButtonId = "#open{{ $compName }}Modal";
let selectId = null;
$(modalId).dialog({
autoOpen: false,
modal: true,
width: 800,
height: 600,
maxWidth: 1200,
maxHeight: 800,
draggable: true,
resizable: true,
containment: "window",
position: { my: "center", at: "center", of: window },
show: { effect: "slide", duration: 500 },
hide: { effect: "fold", duration: 500 },
dialogClass: "rounded-dialog",
buttons: [
{
text: "{{ trans('global.save') }}",
class: "btn btn-primary",
id: "save{{ $compName }}ModalButton",
click: function () {
}
},
{
text: "{{ trans('global.close') }}",
class: "btn btn-secondary",
click: function () {
$(this).dialog("close");
}
}
],
close: function () {
$(modalId).find("input").val('');
$(modalId).find(".invalid-feedback").hide();
}
});
$(document).on("click", openButtonId, function () {
$(modalId).dialog("open");
selectId = `#${$(this).data("select-id")}`;
currentMode = $(this).hasClass("modal-update") ? "update" : "create";
const dropzoneElement = $(modalId).find("#attachments-dropzone");
// Clear any existing hidden input fields related to attachments
$(modalId).find('input[name="attachments[]"]').remove();
// Clear all files from the Dropzone (if Dropzone instance exists)
if (window.myDropzone) {
window.myDropzone.destroy();
window.myDropzone = null;
}
dropzoneElement.html(`
<div class="dz-default dz-message">
<span>Drop files here to upload</span>
</div>
`).removeClass('dz-started');
let uploadUrl = $(this).data("upload-url") ?? '{{ $upload_url }}';
let fileSize = $(this).data("file-size") || 20;
if (dropzoneElement.length > 0) {
// Reset Dropzone before reinitialization
dropzoneElement.removeClass("dz-started"); // Reset Dropzone element class
dropzoneElement.removeClass("dz-clickable");
Dropzone.instances.forEach(dz => dz.destroy());
var uploadedAttachmentsMap = {};
window.myDropzone = new Dropzone(dropzoneElement[0], {
// url: '{{ route('admin.coop-agreements.storeMedia') }}',
url: uploadUrl,
maxFilesize: 20, // MB
addRemoveLinks: true,
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
params: {
size: 20
},
success: function(file, response) {
$(modalId).append('<input type="hidden" name="attachments[]" value="' + response.name + '">');
uploadedAttachmentsMap[file.name] = response.name;
},
removedfile: function(file) {
file.previewElement.remove();
var name = '';
if (file.file_name) {
name = file.file_name;
} else if (uploadedAttachmentsMap[file.name]) {
name = uploadedAttachmentsMap[file.name];
} else {
name = file.upload ? file.upload.filename : file.name;
}
$(modalId).find('input[name="attachments[]"]').each(function() {
if ($(this).val() === name) {
$(this).remove();
}
});
delete uploadedAttachmentsMap[file.name];
},
init: function() {
@if(isset($coopAgreement) && $coopAgreement->attachments)
var files = {!! json_encode($coopAgreement->attachments) !!};
for (var i in files) {
var file = files[i];
this.options.addedfile.call(this, file);
file.previewElement.classList.add('dz-complete');
$(modalId).append('<input type="hidden" name="attachments[]" value="' + file.file_name + '">');
}
@endif
},
error: function(file, response) {
var message = $.type(response) === 'string' ? response : response.errors.file;
file.previewElement.classList.add('dz-error');
var nodes = file.previewElement.querySelectorAll('[data-dz-errormessage]');
for (var node of nodes) {
node.textContent = message;
}
}
});
}
});
$(document).on("click", saveButtonId, function () {
const inputData = $(modalId).find("input").val();
let currentSelectId = selectId;
let formData = $("#create{{ $compName }}Modal").find(":input").serialize();
let dataToSend = {};
// dataToSend[dynamicKey] = inputData;
$.ajax({
url: "{{ $route }}",
type: "POST",
headers: { 'x-csrf-token': _token },
data: formData,
success: function (response) {
if (response.success) {
if (currentSelectId) {
console.log(response.data);
const displayValue = (response.data['name'] ?? response.data['title']) ?? '';
const option = new Option(displayValue, response.data.id, true, true);
const selectName = $(currentSelectId).attr('name');
$(currentSelectId).append(option).trigger('change');
// console.log('cia:', $(`select[name='${selectName}']`));
// $(`select[name='${selectName}']`).each(function () {
// const select = $(this);
// if (select.is(currentSelectId)) return;
// if (!select.find(`option[value="${response.data.id}"]`).length) {
// select.append(newOption.clone()).trigger('change');
// }
// });
// $(`select[name='${selectName}']`).val(function() {
// return $(this).val().concat([response.data.id]);
// }).trigger('change');
}
$.fn.dataTable.tables({ visible: true, api: true }).ajax.reload(null, false);
Swal.fire({
title: '{{ trans('global.create_success')}}',
icon: 'success',
timer: 1500,
showConfirmButton: false
}).then(() => {
$(modalId).dialog("close");
});
}
},
error: function (xhr) {
$('.is-invalid').removeClass('is-invalid');
$('.invalid-feedback').remove();
if (xhr.status === 422) {
const errors = xhr.responseJSON.errors;
$.each(errors, function(fieldName, errorMessages) {
const field = $(modalId).find(`[name="${fieldName}[]"], [name="${fieldName}"]`);
field.addClass('is-invalid');
const errorMessage = errorMessages[0];
const errorDiv = `<div class="invalid-feedback">${errorMessage}</div>`;
if (field.hasClass('select2')) {
field.closest('.form-group').append(errorDiv);
} else {
field.after(errorDiv);
}
});
setTimeout(() => {
$('select.select2').each(function() {
if (!$(this).data('select2')) {
$(this).select2();
}
});
}, 100);
} else {
Swal.fire({
title: 'Error!',
text: 'There was an error processing your request.',
icon: 'error',
confirmButtonText: 'OK'
});
}
},
});
});
});
</script>
<style>
.ui-dialog {
border-radius: 15px;
overflow: hidden;
/* top: 10% !important; */
}
.ui-dialog-titlebar {
border-top-left-radius: 15px;
border-top-right-radius: 15px;
}
.swal2-popup {
position: fixed;
top: 10px;
right: 10px;
width: auto;
max-width: 300px;
padding: 10px;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
.swal2-title {
font-size: 18px;
font-weight: bold;
}
.swal2-content {
font-size: 14px;
}
</style>