]);
}
- 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) {
return ['items' => $items];
}
+
+
/**
* Updates an existing Product1CReplacement model.
* If update is successful, the browser will be redirected to the 'view' page.
'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) {
<?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'],
<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;">
'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) {
$(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
`;
$('#guid-replacement-container').append(newField);
- // Инициализация Select2 для нового поля
+
$(`#product1creplacement-guid_replacement-${counter}`).select2({
placeholder: 'Выберите замену...',
allowClear: true,
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 };
})
};
}
success: function(data) {
console.log(data);
if (data.success) {
- // Перезагрузка через Pjax после успешного удаления
+
$.pjax.reload({container: '#pjax-container', async: false});
} else {
alert(data.message || 'Ошибка при удалении записи.');
});
}
-// Инициализация обработчиков при загрузке страницы
+
$(document).ready(function () {
initReplacementHandlers();
$(document).on('pjax:end', function () {