HEX
Server: Apache
System: Linux WWW 6.1.0-40-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.153-1 (2025-09-20) x86_64
User: web11 (1011)
PHP: 8.2.29
Disabled: NONE
Upload Files
File: /var/www/ivs.kaunokolegija.lt/laravel/resources/views/layouts/universal_modal.blade.php
<div id="{{ $compName }}Modal" title="{{ $title }}" style="display:none;" class="universal-modal">
    <div class="modal-body">
        <div class="form-group">
            @include($fieldsLink)
        </div>
        <div style="padding-top: 60px"></div>
    </div>
</div>
@php
    $upload_url = isset($upload_url) ? $upload_url : null;
@endphp

<script>
  $(document).ready(function () {
    let modalId = "#{{ $compName }}Modal";
    let isAjax = false;
    let modal = null;
    // console.log('targetTable', datatable);
    const saveButtonId = "#save{{ $compName }}ModalButton";
    let currentMode = "create";
    let recordData = null;
    let updateUrl = "{{ $updateRoute }}";
    let createUrl = "{{ $createRoute }}";

    $(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",
        classes: {
            "ui-dialog": "custom-dialog",
            "ui-dialog-titlebar": "custom-titlebar",
            "ui-dialog-content": "custom-content"
        },
        buttons: [
            {
                text: currentMode === "create" ? "{{ trans('global.save') }}" : "{{ trans('global.update') }}",
                class: "btn btn-primary",
                id: saveButtonId.replace("#", ""),
                click: function () {

                    const modalId = "#{{ $compName }}Modal";
                    $(modalId).find('.ckeditor').each(function () {
                        if (this.ckeditorInstance) {
                            this.ckeditorInstance.updateSourceElement();
                        }
                    });

                    const formData = $(modalId).find(":input").serializeArray();   

                    if (currentMode === "update") {
                        formData.push({ name: "_method", value: "PUT" });
                    }

                    const url = currentMode === "create" ? createUrl : updateUrl;

                    $.ajax({
                        url: url,
                        type: "POST",
                        headers: { "x-csrf-token": _token },
                        data: formData,
                        beforeSend: function() {
                            Swal.fire({
                                // title: "{{ trans('global.processing') }}",
                                html: "{{ trans('global.please_wait') }}",
                                timerProgressBar: false,
                                allowOutsideClick: false,
                                didOpen: () => {
                                    Swal.showLoading();
                                }
                            });
                        },
                        success: function (response) {
                            Swal.close();
                            if (response.success) {                              
                                $.fn.dataTable.tables({ visible: true, api: true }).ajax.reload(null, false);

                                Swal.fire({
                                    title: "{{ trans('global.update_success') }}",
                                    text: currentMode === "create" ? "{{ trans('global.create_success') }}" : "{{ trans('global.update_success') }}",
                                    icon: "success",
                                    timer: 1500,
                                    showConfirmButton: false,
                                }).then(() => {
                                    $(modalId).dialog("close");
                                });
                            }
                        },
                        error: function (xhr) {
                            Swal.close();
                            $('.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}"]`);

                                    const errorMessage = errorMessages[0];
                                    const errorDiv = `<div class="invalid-feedback">${errorMessage}</div>`;

                                    if (field.hasClass('select2')) {
                                        const parent = field.closest('.form-group');
                                        if (!parent.find('.invalid-feedback').length) {
                                            parent.append(errorDiv);
                                        }
                                        field.closest('.form-group').find('.select2').addClass('is-invalid');
                                    } else {
                                        // Handle normal input fields
                                        field.addClass('is-invalid');
                                        if (field.is(':checkbox') || field.is(':radio')) {
                                            field.closest('.form-group').append(errorDiv);
                                        } else {
                                            field.after(errorDiv);
                                        }
                                    }
                                });

                                setTimeout(() => {
                                    $('select.select2').each(function () {
                                        if (!$(this).data('select2')) {
                                            $(this).select2({
                                                dropdownParent: $(`${modalId} > .modal-body`),
                                                allowClear: false,
                                                width: '100%',
                                            });
                                        }
                                    });
                                }, 100);
                            } else {
                                Swal.fire({
                                    title: 'Error!',
                                    text: 'There was an error processing your request.',
                                    icon: 'error',
                                    confirmButtonText: 'OK',
                                });
                            }
                        },
                    });
                },
            },
            {
                text: "{{ trans('global.close') }}",
                class: "btn btn-secondary",
                click: function () {
                    $(modalId).dialog("close");
                },
            },
        ],
        open: function () {
            // $(modalId).find("input").val('');
            // $(modalId).find(".invalid-feedback").hide();

            $(modalId).find('select.select2').each(function () {
                if ($(this).data('select2')) {
                    $(this).select2({
                        // dropdownParent: $(modalId),
                        dropdownParent: $(`${modalId} > .modal-body`),
                        // placeholder: "{{ trans('global.pleaseSelect') }}",
                        allowClear: false,
                        width: '100%',
                        dropdownAutoWidth: true,
                    });
                }
            });
            let title = currentMode === "create" 
                ? "{{ trans('global.create') }}" 
                : "{{ trans('global.update') }}";
            $(modalId).dialog("option", "title", title);
        },
        close: function() {
            // Remove all files from Dropzone
            if (window.myDropzone) {
                window.myDropzone.removeAllFiles(true);
            }
            $(modalId).find("input").val('');
            $(modalId).find(".invalid-feedback").hide();
        }
    });

    $(document).on("click", ".modal-create, .modal-update, [data-modal-target]", function () {
        isAjax = $(this).data("ajax") == 1 ? true : false;
        modal = $(this).data("table-class");        

        let targetModal = $(this).data("modal-target");
        if (!targetModal) {
            modalId = "#{{ $compName }}Modal";
        } else {
            modalId = targetModal;
        }
    
        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;
                    }
                }
            });
        }

        // Update modal settings
        if (currentMode === "update") {
            recordData = $(this).data("record-data");
            updateUrl = $(this).data("update-url");            
            const parsedRecordData = typeof recordData === "string" ? JSON.parse(recordData) : recordData;
            // console.log(parsedRecordData);
            for (const key in parsedRecordData) {
                const field = $(modalId).find(`[name="${key}[]"], [name="${key}"]`);
                if (Array.isArray(parsedRecordData[key])) {
                    if (field.is("select")) {
                        const ids = parsedRecordData[key].map(item => item.id);

                        if (field.hasClass('select2')) {
                            setTimeout(() => {
                                field.val(ids).trigger('change');
                            }, 400);
                        } else {
                            field.val(ids).trigger('change');
                        }
                    }
                }
                else if (parsedRecordData[key] && typeof parsedRecordData[key] === "object") {
                    if (field.is("select")) {
                        const fieldValue = parsedRecordData[key]?.id;
                        field.val(fieldValue).trigger('change');
                    }
                }
                else if (field.is(":checkbox")) {
                    field.prop("checked", parsedRecordData[key]);
                }
                else if (field.is(":radio")) {
                    $(`${modalId} [name="${key}"][value="${parsedRecordData[key]}"]`).prop("checked", true);
                }
                else if (field.is("select")) {
                    field.val(parsedRecordData[key]).trigger('change');
                }
                else {
                    field.val(parsedRecordData[key]);
                }                
            }          

            // Handle existing attachments (if any)
            if (parsedRecordData?.media && parsedRecordData.media.length > 0) {
                const myDropzone = Dropzone.forElement("#attachments-dropzone");
                    // myDropzone.destroy();
                

                parsedRecordData.media.forEach(function (attachment) {
                   
                    const mockFile = {
                        name: attachment.file_name,
                        size: attachment.size,
                        url: attachment.original_url
                    };

                    myDropzone.emit("addedfile", mockFile);
                    myDropzone.emit("thumbnail", mockFile, attachment.original_url);
                    myDropzone.emit("complete", mockFile);

                    // Add hidden input for the attachment
                    $(modalId).append('<input type="hidden" name="attachments[]" value="' + attachment.file_name + '">');
                });
            }
            
            } else {
                $(modalId).find(":input").each(function () {
                    if (this.type === "checkbox") {
                        // Uncheck checkboxes
                        $(this).prop("checked", false);
                    } else if (this.type !== "hidden") {
                        // Reset other inputs except hidden inputs
                        $(this).val("");
                    }
                });
            }

            $(modalId).dialog("open");
        });


    $(document).on('click', '.select-all', function () {
        let $select2 = $(this).parent().siblings('.d-flex').find('.select2');
        $select2.find('option').prop('selected', 'selected');
        $select2.trigger('change');
    });

    $(document).on('click', '.deselect-all', function () {
        let $select2 = $(this).parent().siblings('.d-flex').find('.select2');
        $select2.find('option').prop('selected', false);
        $select2.trigger('change');
    });
});

</script>