class NewDocumentModal { constructor() { this.$modal = $("#new-document-modal"); this.modal = bootstrap.Modal.getInstance(this.$modal.get(0)); this.$modal.on("show.bs.modal", event => this.onShow(event)); this.$modal.on("shown.bs.modal", () => this.onShown()); this.$modal.on("hidden.bs.modal", () => this.onHidden()); this.$title = this.$modal.find(".modal-title"); this.$form = this.$modal.find("form"); this.$form.on("submit", event => this.onSubmit(event)); this.$ticketIdField = this.getField("ticket_id"); this.$companyDropdown = this.getField("company_id"); this.$locationDropdown = this.getField("location_id"); this.$supplierDropdown = this.getField("supplier_id"); this.$aruSection = $("#new-document-aru-section"); this.$itemDescriptionField = this.getField("item_description"); this.$itemSerialNumberField = this.getField("item_serial_number"); this.$locationDropdown.select2({ theme: "bootstrap-5", dropdownParent: this.$locationDropdown.closest("div") }); } getField(name) { return this.$form.find(`[name=${name}]`); } // Modal lifecycle onShow(event) { const $element = $(event.relatedTarget); const data = $element.data(); const { type, locationId, ticketId } = data; this.$supplierDropdown.closest(".mb-3").show(); this.$aruSection.show(); switch(type) { case DocumentTypes.GoodsIn: this.$title.text("New Goods-In"); this.baseUrl = "/goods-in"; this.$aruSection.hide(); break; case DocumentTypes.AdvancedReplacementUnit: this.$title.text("New ARU"); this.baseUrl = "/arus"; this.$supplierDropdown.closest(".mb-3").hide(); break; } if(locationId) { this.$locationDropdown.val(locationId); } if(ticketId) { this.$ticketIdField.val(ticketId); } } onShown() { this.$companyDropdown.trigger("focus"); } onHidden() { this.$form.get(0).reset(); this.$ticketIdField.val(null); } onSubmit(event) { event.preventDefault(); const data = this.$form.serialize(); $.post(`${this.baseUrl}/create`, data).then(response => { this.$modal.modal("hide"); window.location = response.url; }).catch(error => { console.log(error); }); } } $(() => new NewDocumentModal());