]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Исключение товаров те которые уже добавлены из поиска
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Mon, 18 Nov 2024 15:00:08 +0000 (18:00 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Mon, 18 Nov 2024 15:00:08 +0000 (18:00 +0300)
erp24/controllers/crud/Product1cReplacementController.php
erp24/views/crud/product1c-replacement/_form.php
erp24/views/crud/product1c-replacement/multy-form.php
erp24/web/js/crud/product1cReplacement/_form.js
erp24/web/js/crud/product1cReplacement/multy-form.js

index 4f26b9f16f13c94a7020784cd08d9b6da38038d3..042988bb0e72fe29ef9777aef2962849a2f42073 100644 (file)
@@ -177,18 +177,36 @@ class Product1cReplacementController extends Controller
         ]);
     }
 
-    public function actionSearch($q = null)
+    public function actionSearch($q = null, $exclude = null, $guid = null)
     {
         Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
 
-        $products = Products1c::find()
-            ->select(['id', 'name', 'articule']) // Добавляем 'articule'
+
+        $query = Products1c::find()
+            ->select(['id', 'name', 'articule'])
             ->where(['tip' => 'products'])
-            ->andWhere(['ilike', 'name', $q])
-            ->limit(20)
-            ->asArray()
-            ->all();
+            ->andFilterWhere(['ilike', 'name', $q])
+            ->limit(20);
+
+
+        if ($exclude) {
+            $excludeIds = explode(',', $exclude);
+            $query->andWhere(['not in', 'id', $excludeIds]);
+        }
+
+
+        if ($guid) {
+            $existingReplacements = Product1cReplacement::find()
+                ->select('guid_replacement')
+                ->where(['guid' => $guid])
+                ->column();
 
+            if ($existingReplacements) {
+                $query->andWhere(['not in', 'id', $existingReplacements]);
+            }
+        }
+
+        $products = $query->asArray()->all();
 
         $items = [];
         foreach ($products as $product) {
@@ -200,6 +218,8 @@ class Product1cReplacementController extends Controller
 
         return ['items' => $items];
     }
+
+
     /**
      * Updates an existing Product1CReplacement model.
      * If update is successful, the browser will be redirected to the 'view' page.
index f52415b4c9a92ae10089efe2e686875fe2b5cf69..ff411109e4c67665cb718ec1bbaf251a92e3f4d9 100644 (file)
@@ -57,7 +57,20 @@ $this->registerJsFile('/js/crud/product1cReplacement/_form.js', ['position' => \
                 'ajax' => [
                     'url' => \yii\helpers\Url::to(['/crud/product1c-replacement/search']),
                     'dataType' => 'json',
-                    'data' => new JsExpression('function(params) { return {q:params.term}; }'),
+                    'data' => new JsExpression('function(params) { 
+                var exclude = [];
+                exclude.push($("#product1creplacement-guid").val()); 
+                $(".guid-replacement-select").each(function() {
+                    if ($(this).val()) {
+                        exclude.push($(this).val());
+                    }
+                });
+                return {
+                    q: params.term,
+                    exclude: exclude.join(","),
+                    guid: $("#guid-select").val() 
+                };
+            }'),
                     'processResults' => new JsExpression('function(data) {
                 return {
                     results: $.map(data.items, function(item) {
index f3487daa4b7fd71c91c9435d4cf966037ac14253..7316549889cf74b3117feb2d921434d2df134622 100644 (file)
@@ -19,7 +19,7 @@ $this->registerJsFile('/js/crud/product1cReplacement/multy-form.js', ['position'
         <?php $form = ActiveForm::begin(['id' => 'product-replacement-form']); ?>
 
         <!-- Скрытое поле GUID -->
-        <?= Html::activeHiddenInput($model, 'guid') ?>
+        <?= Html::activeHiddenInput($model, 'guid', ['id' => 'guid-select']) ?>
        <!-- --><?php /*= $form->field($model, 'guid')->widget(Select2::class, [
             'value' => $model->id,
             'options' => ['placeholder' => 'Выберите товар...', 'id' => 'product-replacement-form-guid'],
@@ -48,7 +48,7 @@ $this->registerJsFile('/js/crud/product1cReplacement/multy-form.js', ['position'
         <div id="guid-replacement-container" class="col-6">
             <?php foreach ($replacements as $key => $replacement): ?>
                 <?php
-                // Проверяем, существует ли связанный продукт
+
                 $replacementName = $replacement->replacementProduct ? $replacement->replacementProduct->name : 'Неизвестно';
                 ?>
             <div class="guid-replacement-group row" style="position: relative;">
@@ -62,7 +62,20 @@ $this->registerJsFile('/js/crud/product1cReplacement/multy-form.js', ['position'
                         'ajax' => [
                             'url' => \yii\helpers\Url::to(['/crud/product1c-replacement/search']),
                             'dataType' => 'json',
-                            'data' => new JsExpression('function(params) { return {q:params.term}; }'),
+                            'data' => new JsExpression('function(params) { 
+                                var exclude = [];
+                                exclude.push($("#guid-select").val());
+                                $(".guid-replacement-select").each(function() {
+                                    if ($(this).val()) {
+                                     exclude.push($(this).val());
+                                 }
+                                 });
+                                 return {
+                                     q: params.term,
+                                      exclude: exclude.join(","),
+                     
+                                      };
+                             }'),
                             'processResults' => new JsExpression('function(data) {
                         return {
                             results: $.map(data.items, function(item) {
index 88918ef3a1d4239ecee97a69065a65a0b2aed66f..de94ed4f4dcb59d9bf45d71ee85e414fe4fd5575 100644 (file)
@@ -1,49 +1,67 @@
 $(document).ready(function () {
     let counter = 1;
 
-    // Добавление нового поля
-    $('#add-guid-replacement').on('click', function () {
-        counter++;
-        let newField = `
-            
-            <div class="guid-replacement-group my-4" id="guid-replacement-group-${counter}" style="position: relative;">
-                <label for="product1creplacement-guid_replacement-${counter}">Замена</label>
-                <select class="form-control guid-replacement-select" name="Product1cReplacement[guid_replacement][]" id="product1creplacement-guid_replacement-${counter}">
-                </select>
-                <button type="button" class="btn btn-danger remove-guid-replacement btn-remove" data-target="#guid-replacement-group-${counter}" style="position: absolute;  right: -45px; ">×</button>
-            </div>        
-                        
-        `;
-        $('#guid-replacement-container').append(newField);
 
-        // Инициализация Select2 с использованием AJAX для нового поля
-        $(`#product1creplacement-guid_replacement-${counter}`).select2({
+    function initializeSelect2(selector) {
+        $(selector).select2({
             placeholder: 'Выберите замену...',
             allowClear: true,
             minimumInputLength: 1,
             ajax: {
-                url: '/crud/product1c-replacement/search', // Замените URL на ваш реальный путь поиска
+                url: '/crud/product1c-replacement/search',
                 dataType: 'json',
                 data: function (params) {
-                    return { q: params.term }; // Передача поискового термина
+                    var exclude = [];
+                    exclude.push($("#product1creplacement-guid").val());
+                    $(".guid-replacement-select").each(function () {
+                        if ($(this).val()) {
+                            exclude.push($(this).val());
+                        }
+                    });
+                    console.log(exclude);
+                    return {
+                        q: params.term,
+                        exclude: exclude.join(",")
+                    };
                 },
                 processResults: function (data) {
+                    console.log(data);
                     return {
                         results: $.map(data.items, function (item) {
                             return {
                                 id: item.id,
-                                text: item.name
+                                text: item.text
                             };
                         })
                     };
                 }
             }
         });
+    }
+
+
+    $('#add-guid-replacement').on('click', function () {
+        counter++;
+        let newField = `
+            <div class="guid-replacement-group my-4" id="guid-replacement-group-${counter}" style="position: relative;">
+                <label for="product1creplacement-guid_replacement-${counter}">Замена</label>
+                <select class="form-control guid-replacement-select" name="Product1cReplacement[guid_replacement][]" id="product1creplacement-guid_replacement-${counter}">
+                </select>
+                <button type="button" class="btn btn-danger remove-guid-replacement btn-remove" data-target="#guid-replacement-group-${counter}" style="position: absolute; right: -45px;">×</button>
+            </div>        
+        `;
+        $('#guid-replacement-container').append(newField);
+
+
+        initializeSelect2(`#product1creplacement-guid_replacement-${counter}`);
     });
 
-    // Удаление поля
+
     $(document).on('click', '.remove-guid-replacement', function () {
         let target = $(this).data('target');
-        $(target).remove(); // Удаляем группу полей
+        $(target).remove();
     });
+
+
+    initializeSelect2('.guid-replacement-select');
 });
\ No newline at end of file
index a71e8580107cc9b33ff3dd2d8d315fa15a5c6fd9..37a2849fd2169429a7b81b441dea868c4331119c 100644 (file)
@@ -13,7 +13,7 @@ function initReplacementHandlers() {
         `;
         $('#guid-replacement-container').append(newField);
 
-        // Инициализация Select2 для нового поля
+
         $(`#product1creplacement-guid_replacement-${counter}`).select2({
             placeholder: 'Выберите замену...',
             allowClear: true,
@@ -21,13 +21,24 @@ function initReplacementHandlers() {
             ajax: {
                 url: '/crud/product1c-replacement/search',
                 dataType: 'json',
-                data: function (params) {
-                    return { q: params.term };
+                data: function(params) {
+                    var exclude = [];
+                    exclude.push($("#guid-select").val());
+                    $(".guid-replacement-select").each(function() {
+                        if ($(this).val()) {
+                            exclude.push($(this).val());
+                        }
+                    });
+                    return {
+                        q: params.term,
+                        exclude: exclude.join(","),
+
+                    };
                 },
                 processResults: function (data) {
                     return {
                         results: $.map(data.items, function (item) {
-                            return { id: item.id, text: item.name };
+                            return { id: item.id, text: item.text };
                         })
                     };
                 }
@@ -53,7 +64,7 @@ function initReplacementHandlers() {
             success: function(data) {
                 console.log(data);
                 if (data.success) {
-                    // Перезагрузка через Pjax после успешного удаления
+
                     $.pjax.reload({container: '#pjax-container', async: false});
                 } else {
                     alert(data.message || 'Ошибка при удалении записи.');
@@ -66,7 +77,7 @@ function initReplacementHandlers() {
     });
 }
 
-// Инициализация обработчиков при загрузке страницы
+
 $(document).ready(function () {
     initReplacementHandlers();
     $(document).on('pjax:end', function () {