From 3c0ba70bc8767a644cbab801970e2f70502bfb55 Mon Sep 17 00:00:00 2001 From: Andrey Smakotin Date: Mon, 10 Nov 2025 23:40:34 +0300 Subject: [PATCH] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=BE=20=D0=BE=D1=82=D0=BE=D0=B1=D1=80=D0=B0=D0=B6?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B2=D1=8B=D0=B1=D1=80=D0=B0=D0=BD?= =?UTF-8?q?=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=BA=D0=BB=D0=B8=D0=B5=D0=BD=D1=82?= =?UTF-8?q?=D0=B0=20=D0=BF=D1=80=D0=B8=20=D1=80=D0=B5=D0=B4=D0=B0=D0=BA?= =?UTF-8?q?=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B8=20=D1=87?= =?UTF-8?q?=D0=B5=D1=80=D0=BD=D0=BE=D0=B2=D0=B8=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Проблема: При редактировании черновика заказа клиент не отображался на форме. Решение: - Не очищаем select если уже есть выбранный клиент (не вызываем empty()) - Оставляем option элемент в DOM, позволяя Select2 его видеть - Просто устанавливаем значение через .val() после инициализации Select2 - Исправлена formatCustomerSelection чтобы обрабатывала option.text если option.name отсутствует Ключевое изменение: Select2 AJAX mode корректно работает с pre-rendered option элементами, если мы их не очищаем перед инициализацией. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .../orders/templates/orders/order_form.html | 55 +++++++++---------- 1 file changed, 25 insertions(+), 30 deletions(-) diff --git a/myproject/orders/templates/orders/order_form.html b/myproject/orders/templates/orders/order_form.html index 822ec5b..c0ba776 100644 --- a/myproject/orders/templates/orders/order_form.html +++ b/myproject/orders/templates/orders/order_form.html @@ -461,8 +461,10 @@ function initCustomerSelect2() { const currentText = $customerSelect.find(':selected').text(); console.log('Сохраняем текущее значение:', currentValue, currentText); - // Очищаем существующие опции - $customerSelect.empty(); + // НЕ очищаем, если у нас есть текущий выбранный клиент + if (!currentValue) { + $customerSelect.empty(); + } // Инициализируем Select2 с AJAX $customerSelect.select2({ @@ -495,40 +497,32 @@ function initCustomerSelect2() { }, templateResult: formatCustomerOption, templateSelection: formatCustomerSelection, - escapeMarkup: function(markup) { return markup; } + escapeMarkup: function(markup) { return markup; }, + // Очень важно: указываем как отображать уже выбранное значение + matcher: function(params, data) { + // Если нет поискового термина, показываем все результаты + if ($.trim(params.term) === '') { + return data; + } + // Иначе ищем совпадение + if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) { + return data; + } + return null; + } }); console.log('6. Select2 инициализирован'); // Восстанавливаем значение если оно было (для редактирования черновика) - if (currentValue) { + if (currentValue && currentText) { 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'); - }); + // Select2 видит option элемент в DOM (так как мы его не очищали) + // Просто устанавливаем значение через Select2 API + $customerSelect.val(currentValue); + + console.log('Значение восстановлено:', $customerSelect.val()); } // Слушаем события @@ -593,7 +587,8 @@ function initCustomerSelect2() { if (option.is_create_option) { return option.text; } - return option.name; + // Возвращаем name если есть (из AJAX), иначе text (из DOM опции) + return option.name || option.text; } }