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; } }