diff --git a/myproject/orders/templates/orders/order_form.html b/myproject/orders/templates/orders/order_form.html index 3e6df4f..822ec5b 100644 --- a/myproject/orders/templates/orders/order_form.html +++ b/myproject/orders/templates/orders/order_form.html @@ -456,6 +456,11 @@ function initCustomerSelect2() { console.log('1. Поле customer найдено:', $customerSelect.length); console.log('2. AJAX URL:', ajaxUrl); + // Сохраняем текущее значение перед очисткой (может быть при редактировании черновика) + const currentValue = $customerSelect.val(); + const currentText = $customerSelect.find(':selected').text(); + console.log('Сохраняем текущее значение:', currentValue, currentText); + // Очищаем существующие опции $customerSelect.empty(); @@ -495,6 +500,37 @@ function initCustomerSelect2() { console.log('6. Select2 инициализирован'); + // Восстанавливаем значение если оно было (для редактирования черновика) + if (currentValue) { + console.log('Восстанавливаем значение:', currentValue, 'Текст:', currentText); + + // Загружаем информацию о клиенте через AJAX + fetch(ajaxUrl + '?q=' + encodeURIComponent(currentText)) + .then(response => response.json()) + .then(data => { + // Ищем клиента в результатах + const customer = data.results.find(r => r.id == currentValue); + if (customer) { + console.log('Найден клиент:', customer); + const option = new Option(customer.text, customer.id, true, true); + $customerSelect.append(option).val(customer.id); + } else { + // Если не найден, создаем опцию с сохраненным текстом + console.log('Клиент не найден в результатах, используем сохраненный текст'); + const option = new Option(currentText, currentValue, true, true); + $customerSelect.append(option).val(currentValue); + } + // Обновляем Select2 + $customerSelect.trigger('change'); + }) + .catch(error => { + console.error('Ошибка при загрузке клиента:', error); + // Создаем option с сохраненным текстом в любом случае + const option = new Option(currentText, currentValue, true, true); + $customerSelect.append(option).val(currentValue).trigger('change'); + }); + } + // Слушаем события $customerSelect.on('select2:open', function(e) { console.log('7. Dropdown открыт'); @@ -514,8 +550,16 @@ function initCustomerSelect2() { if (data.is_create_option) { console.log('10. Открываем модальное окно для создания клиента'); - $(this).val(null).trigger('change'); + this.value = ''; + // Триггерим нативное change событие для draft-creator.js + const changeEvent = new Event('change', { bubbles: true }); + this.dispatchEvent(changeEvent); openCreateCustomerModal(data.search_text); + } else { + // Триггерим нативное change событие для других обработчиков (например, draft-creator.js) + console.log('11. Триггерим нативное change событие'); + const changeEvent = new Event('change', { bubbles: true }); + this.dispatchEvent(changeEvent); } });