From: fomichev Date: Fri, 15 Nov 2024 13:59:43 +0000 (+0300) Subject: Создание и редактирование записей X-Git-Tag: 1.7~226^2~10 X-Git-Url: https://gitweb.erp-flowers.ru/?a=commitdiff_plain;h=cae9c3835f7c6159da015ef3919c8f9ef9203786;p=erp24_rep%2Fyii-erp24%2F.git Создание и редактирование записей --- diff --git a/erp24/controllers/crud/Product1cReplacementController.php b/erp24/controllers/crud/Product1cReplacementController.php index d9bf05e3..5a0e7faa 100644 --- a/erp24/controllers/crud/Product1cReplacementController.php +++ b/erp24/controllers/crud/Product1cReplacementController.php @@ -2,12 +2,15 @@ namespace yii_app\controllers\crud; +use Yii; use yii\behaviors\TimestampBehavior; +use yii\data\ActiveDataProvider; use yii_app\records\Product1cReplacement; use yii_app\records\Product1cReplacementSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; +use yii_app\records\Products1c; /** * Product1CReplacementController implements the CRUD actions for Product1CReplacement model. @@ -25,13 +28,14 @@ class Product1cReplacementController extends Controller 'verbs' => [ 'class' => VerbFilter::class, 'actions' => [ - 'delete' => ['POST'], + //'delete' => ['POST'], ], ], [ 'class' => TimestampBehavior::class, 'createdAtAttribute' => 'created_at', 'updatedAtAttribute' => 'updated_at', + //'deletedAtAttribute' => 'deleted_at', 'value' => new \yii\db\Expression('NOW()'), ], ] @@ -48,11 +52,18 @@ class Product1cReplacementController extends Controller $searchModel = new Product1cReplacementSearch(); $dataProvider = $searchModel->search($this->request->queryParams); - // Группируем данные по guid - $models = $dataProvider->query->all(); + // Получаем уникальные значения по guid + $models = $dataProvider->query->select(['guid'])->distinct()->all(); $groupedReplacements = []; + + foreach ($models as $model) { - $groupedReplacements[$model->guid][] = $model->guid_replacement; + $groupedReplacements[$model->guid] = Product1cReplacement::find() + ->select('guid_replacement') + ->where(['guid' => $model->guid]) + ->andWhere(['deleted_at' => null]) + // ->distinct() + ->column(); } return $this->render('index', [ @@ -61,7 +72,6 @@ class Product1cReplacementController extends Controller 'groupedReplacements' => $groupedReplacements, ]); } - /** * Displays a single Product1CReplacement model. * @param int $id ID @@ -70,8 +80,21 @@ class Product1cReplacementController extends Controller */ public function actionView($id) { + + $replacementsQuery = Product1cReplacement::find() + ->where(['guid' => $id]) + ->andWhere(['deleted_at' => null]); + + $replacementsDataProvider = new ActiveDataProvider([ + 'query' => $replacementsQuery, + 'pagination' => [ + 'pageSize' => 10, + ], + ]); + return $this->render('view', [ - 'model' => $this->findModel($id), + 'model' => $this->findModelByGuid($id), + 'replacements' => $replacementsDataProvider, ]); } @@ -80,16 +103,41 @@ class Product1cReplacementController extends Controller * If creation is successful, the browser will be redirected to the 'view' page. * @return string|\yii\web\Response */ + + public function actionCreate() { $model = new Product1cReplacement(); - if ($this->request->isPost) { - if ($model->load($this->request->post()) && $model->save()) { - return $this->redirect(['view', 'id' => $model->id]); + if ($model->load(Yii::$app->request->post())) { + $transaction = Yii::$app->db->beginTransaction(); + try { + + $guidReplacements = $model->guid_replacement; + + + + + if (!empty($guidReplacements)) { + foreach ($guidReplacements as $replacementGuid) { + + $replacementModel = new Product1cReplacement([ + 'guid' => $model->guid, + 'guid_replacement' => $replacementGuid, + ]); + if (!$replacementModel->save()) { + + throw new \Exception('Ошибка сохранения замены.'); + } + } + } + $transaction->commit(); + return $this->redirect(['index']); + + } catch (\Exception $e) { + $transaction->rollBack(); + throw $e; } - } else { - $model->loadDefaultValues(); } return $this->render('create', [ @@ -97,6 +145,22 @@ class Product1cReplacementController extends Controller ]); } + public function actionSearch($q = null) + { + + Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; + $products = Products1c::find() + ->select(['id', 'name']) + ->where(['tip' => 'products']) + ->andWhere(['ilike', 'name', $q]) + ->limit(20) + ->asArray() + ->all(); + + + return ['items' => $products]; + } + /** * Updates an existing Product1CReplacement model. * If update is successful, the browser will be redirected to the 'view' page. @@ -106,31 +170,71 @@ class Product1cReplacementController extends Controller */ public function actionUpdate($id) { - $model = $this->findModel($id); + $model = $this->findModelByGuid($id); + + + $replacementsQuery = Product1cReplacement::find() + ->select(['guid_replacement', 'id']) + ->where(['guid' => $id]) + ->andWhere(['deleted_at' => null]) + ->all(); + + if ($this->request->isPost && $model->load($this->request->post())) { + + $transaction = Yii::$app->db->beginTransaction(); + try { + $replacementData = $this->request->post('Product1cReplacement')['guid_replacement'] ?? []; + $replacementIds = $this->request->post('Product1cReplacement')['replacement_ids'] ?? []; - if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) { - return $this->redirect(['view', 'id' => $model->id]); + foreach ($replacementData as $index => $replacementGuid) { + if (!empty($replacementIds[$index])) { + + $replacementModel = Product1cReplacement::findOne($replacementIds[$index]); + if ($replacementModel) { + $replacementModel->guid_replacement = $replacementGuid; + $replacementModel->save(); + } + } else { + + $replacementModel = new Product1cReplacement([ + 'guid' => $model->guid, + 'guid_replacement' => $replacementGuid, + ]); + $replacementModel->save(); + } + } + + $transaction->commit(); + return $this->redirect(['view', 'id' => $model->guid]); + + } catch (\Exception $e) { + $transaction->rollBack(); + throw $e; + } } return $this->render('update', [ 'model' => $model, + 'replacements' => $replacementsQuery, ]); } - /** * Deletes an existing Product1CReplacement model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param int $id ID - * @return \yii\web\Response + * @return array * @throws NotFoundHttpException if the model cannot be found */ public function actionDelete($id) { - $this->findModel($id)->delete(); + Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; - return $this->redirect(['index']); + $model = $this->findModel($id); + if ($model && $model->softDelete()) { + return ['success' => true]; + } + return ['success' => false, 'message' => 'Ошибка при удалении записи.']; } - /** * Finds the Product1CReplacement model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. @@ -146,4 +250,13 @@ class Product1cReplacementController extends Controller throw new NotFoundHttpException('The requested page does not exist.'); } + + protected function findModelByGuid($id) + { + if (($model = Product1cReplacement::findOne(['guid' => $id])) !== null) { + return $model; + } + + throw new NotFoundHttpException('The requested page does not exist.'); + } } diff --git a/erp24/migrations/m241114_085742_create_product_1c_replacement_table.php b/erp24/migrations/m241114_085742_create_product_1c_replacement_table.php index 8c2a324b..94b61c2e 100644 --- a/erp24/migrations/m241114_085742_create_product_1c_replacement_table.php +++ b/erp24/migrations/m241114_085742_create_product_1c_replacement_table.php @@ -20,6 +20,7 @@ class m241114_085742_create_product_1c_replacement_table extends Migration 'guid_replacement' => $this->string()->notNull(), 'created_at' => $this->timestamp()->defaultExpression('CURRENT_TIMESTAMP'), 'updated_at' => $this->timestamp()->defaultValue(null), + 'deleted_at' => $this->timestamp()->defaultValue(null), ]); } diff --git a/erp24/records/Product1cReplacement.php b/erp24/records/Product1cReplacement.php index 57e5889d..5b177bd8 100644 --- a/erp24/records/Product1cReplacement.php +++ b/erp24/records/Product1cReplacement.php @@ -32,8 +32,9 @@ class Product1cReplacement extends \yii\db\ActiveRecord { return [ [['guid', 'guid_replacement'], 'required'], - [['created_at', 'updated_at'], 'safe'], + [['created_at', 'updated_at', 'deleted_at'], 'safe'], [['guid', 'guid_replacement'], 'string', 'max' => 255], + ]; } @@ -44,10 +45,10 @@ class Product1cReplacement extends \yii\db\ActiveRecord { return [ 'id' => 'ID', - 'guid' => 'Guid', - 'guid_replacement' => 'Guid Replacement', - 'created_at' => 'Created At', - 'updated_at' => 'Updated At', + 'guid' => 'Товар', + 'guid_replacement' => 'Замена', + 'created_at' => 'Создано', + 'updated_at' => 'Обновлено', ]; } @@ -75,4 +76,32 @@ class Product1cReplacement extends \yii\db\ActiveRecord $log->save(); } } + + public function getProduct() + { + return $this->hasOne(Products1c::class, ['id' => 'guid']) + ->where(['products_1c.tip' => 'products']); + } + + public function getReplacementProduct() + { + return $this->hasOne(Products1c::class, ['id' => 'guid_replacement']); + } + + public function softDelete() + { + $this->deleted_at = date('Y-m-d H:i:s'); + return $this->save(false, ['deleted_at']); + } + + public function restore() + { + $this->deleted_at = null; + return $this->save(false, ['deleted_at']); + } + + public static function find() + { + return parent::find()->andWhere(['deleted_at' => null]); + } } diff --git a/erp24/records/Product1cReplacementSearch.php b/erp24/records/Product1cReplacementSearch.php index abdcd51a..91ab1b72 100644 --- a/erp24/records/Product1cReplacementSearch.php +++ b/erp24/records/Product1cReplacementSearch.php @@ -6,11 +6,12 @@ use yii\base\Model; use yii\data\ActiveDataProvider; use yii_app\records\Product1cReplacement; -/** - * Product1CReplacementSearch represents the model behind the search form of `yii_app\records\Product1CReplacement`. - */ class Product1cReplacementSearch extends Product1cReplacement { + public $productName; // Для поиска по имени + public $productCode; // Для поиска по коду + public $productArticule; // Для поиска по артикулу + /** * {@inheritdoc} */ @@ -18,7 +19,7 @@ class Product1cReplacementSearch extends Product1cReplacement { return [ [['id'], 'integer'], - [['guid', 'guid_replacement', 'created_at', 'updated_at'], 'safe'], + [['guid', 'guid_replacement', 'created_at', 'updated_at', 'deleted_at'], 'safe'], ]; } @@ -27,7 +28,6 @@ class Product1cReplacementSearch extends Product1cReplacement */ public function scenarios() { - // bypass scenarios() implementation in the parent class return Model::scenarios(); } @@ -42,7 +42,8 @@ class Product1cReplacementSearch extends Product1cReplacement { $query = Product1cReplacement::find(); - // add conditions that should always apply here + + $query->joinWith(['product']); $dataProvider = new ActiveDataProvider([ 'query' => $query, @@ -51,12 +52,10 @@ class Product1cReplacementSearch extends Product1cReplacement $this->load($params); if (!$this->validate()) { - // uncomment the following line if you do not want to return any records when validation fails - // $query->where('0=1'); return $dataProvider; } - // grid filtering conditions + $query->andFilterWhere([ 'id' => $this->id, 'created_at' => $this->created_at, @@ -64,8 +63,10 @@ class Product1cReplacementSearch extends Product1cReplacement ]); $query->andFilterWhere(['ilike', 'guid', $this->guid]) - ->andFilterWhere(['ilike', 'guid_replacement', $this->guid_replacement]); + ->andFilterWhere(['ilike', 'guid_replacement', $this->guid_replacement]) + ->andFilterWhere(['ilike', 'products_1c.name', $this->productName]); // Поиск по имени + return $dataProvider; } -} +} \ No newline at end of file diff --git a/erp24/views/crud/product1c-replacement/_form.php b/erp24/views/crud/product1c-replacement/_form.php index 35fd0f1b..82f39b9b 100644 --- a/erp24/views/crud/product1c-replacement/_form.php +++ b/erp24/views/crud/product1c-replacement/_form.php @@ -2,26 +2,85 @@ use yii\helpers\Html; use yii\widgets\ActiveForm; +use kartik\select2\Select2; +use yii\web\JsExpression; /** @var yii\web\View $this */ /** @var yii_app\records\Product1cReplacement $model */ /** @var yii\widgets\ActiveForm $form */ + +$this->registerJsFile('/js/crud/product1cReplacement/_form.js', ['position' => \yii\web\View::POS_END]); + ?> -
+
+ + 'product-replacement-form']); ?> +
+ +
- + field($model, 'guid')->widget(Select2::class, [ + 'options' => ['placeholder' => 'Выберите товар...'], + 'pluginOptions' => [ + 'allowClear' => true, + 'minimumInputLength' => 1, + 'ajax' => [ + 'url' => \yii\helpers\Url::to(['/crud/product1c-replacement/search']), + 'dataType' => 'json', + 'data' => new JsExpression('function(params) { return {q:params.term}; }'), + 'processResults' => new JsExpression('function(data) { + return { + results: $.map(data.items, function(item) { + return { + id: item.id, + text: item.name // Убедитесь, что возвращаете корректные данные + }; + }) + }; + }'), + ], + ], + ]) ?> + +
+
- field($model, 'guid')->textInput(['maxlength' => true]) ?> - field($model, 'guid_replacement')->textInput(['maxlength' => true]) ?> +
+
+ field($model, 'guid_replacement[]')->widget(Select2::class, [ + 'options' => ['placeholder' => 'Выберите замену...', 'class' => 'guid-replacement-select'], + 'pluginOptions' => [ + 'allowClear' => true, + 'minimumInputLength' => 1, + 'ajax' => [ + 'url' => \yii\helpers\Url::to(['/crud/product1c-replacement/search']), + 'dataType' => 'json', + 'data' => new JsExpression('function(params) { return {q:params.term}; }'), + 'processResults' => new JsExpression('function(data) { + return { + results: $.map(data.items, function(item) { + return { + id: item.id, + text: item.name // Убедитесь, что возвращаете корректные данные + }; + }) + }; + }'), + ], + ], + ]) ?> +
+
- field($model, 'created_at')->textInput() ?> + + - field($model, 'updated_at')->textInput() ?> -
- 'btn btn-success']) ?> +
+ 'btn btn-success']) ?> + 'btn btn-danger']) ?>
diff --git a/erp24/views/crud/product1c-replacement/create.php b/erp24/views/crud/product1c-replacement/create.php index 6511ef70..52a54412 100644 --- a/erp24/views/crud/product1c-replacement/create.php +++ b/erp24/views/crud/product1c-replacement/create.php @@ -4,17 +4,18 @@ use yii\helpers\Html; /** @var yii\web\View $this */ /** @var yii_app\records\Product1cReplacement $model */ - -$this->title = 'Create Product1c Replacement'; +/** @var array $productItems */ +$this->title = 'Создание замены'; $this->params['breadcrumbs'][] = ['label' => 'Product1c Replacements', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> -
+

title) ?>

render('_form', [ 'model' => $model, + ]) ?>
diff --git a/erp24/views/crud/product1c-replacement/index.php b/erp24/views/crud/product1c-replacement/index.php index b04c6216..918d8f27 100644 --- a/erp24/views/crud/product1c-replacement/index.php +++ b/erp24/views/crud/product1c-replacement/index.php @@ -1,16 +1,22 @@ title = 'Возможные замены номенклатуры'; $this->params['breadcrumbs'][] = $this->title; + + ?>
@@ -30,6 +36,11 @@ $this->params['breadcrumbs'][] = $this->title; 'attribute' => 'guid', 'label' => 'GUID, который заменяют', 'value' => function ($model) { + + $product = $model->product; + if ($product) { + return Html::encode($product->name . ' (' . $model->guid . ', ' . $product->code . ', ' . $product->articule . ')'); + } return Html::encode($model->guid); }, 'format' => 'raw', @@ -37,12 +48,21 @@ $this->params['breadcrumbs'][] = $this->title; [ 'label' => 'GUIDы замены', 'value' => function ($model) use ($groupedReplacements) { - $guidReplacements = $groupedReplacements[$model->guid] ?? []; if (!empty($guidReplacements)) { $listItems = '
    '; foreach ($guidReplacements as $replacementGuid) { - $listItems .= '
  • ' . Html::encode($replacementGuid) . '
  • '; + + $replacementProduct = Products1c::findOne(['id' => $replacementGuid, 'tip' => 'products']); + if ($replacementProduct) { + + $code = $replacementProduct->code ? (', ' . $replacementProduct->code) : ''; + $articule = $replacementProduct->articule ? (', ' . $replacementProduct->articule) : ''; + + $listItems .= '
  • ' . Html::encode($replacementProduct->name . ' (' . $replacementGuid . $code . $articule . ')') . '

  • '; + } else { + $listItems .= '
  • ' . Html::encode($replacementGuid) . '
  • '; + } } $listItems .= '
'; return $listItems; @@ -51,9 +71,21 @@ $this->params['breadcrumbs'][] = $this->title; }, 'format' => 'raw', ], + [ + 'class' => ActionColumn::class, + 'template' => '{view} {update} ', + 'urlCreator' => function ($action, $model, $key, $index) { + + return $action . '?id=' . $model->guid; + } + ], ], ]); ?> - + + +
\ No newline at end of file diff --git a/erp24/views/crud/product1c-replacement/multy-form.php b/erp24/views/crud/product1c-replacement/multy-form.php new file mode 100644 index 00000000..ec2bed4c --- /dev/null +++ b/erp24/views/crud/product1c-replacement/multy-form.php @@ -0,0 +1,117 @@ +registerJsFile('/js/crud/product1cReplacement/multy-form.js', ['position' => \yii\web\View::POS_END]); +?> + 'pjax-container']); ?> +
+ + 'product-replacement-form']); ?> + + + + field($model, 'guid')->widget(Select2::class, [ + 'value' => $model->id, + 'options' => ['placeholder' => 'Выберите товар...', 'id' => 'product-replacement-form-guid'], + 'pluginOptions' => [ + 'allowClear' => true, + 'minimumInputLength' => 1, + 'ajax' => [ + 'url' => \yii\helpers\Url::to(['/crud/product1c-replacement/search']), + 'dataType' => 'json', + 'data' => new JsExpression('function(params) { return {q:params.term}; }'), + 'processResults' => new JsExpression('function(data) { + return { + results: $.map(data.items, function(item) { + return { + id: item.id, + text: item.name + }; + }) + }; + }'), + ], + ], + ]) */?> + +
+
+ $replacement): ?> + replacementProduct ? $replacement->replacementProduct->name : 'Неизвестно'; + ?> +
+ id) ?> + field($model, 'guid_replacement[]')->widget(Select2::class, [ + 'value' => $replacement->guid_replacement, + 'options' => [ 'value' => $replacement->guid_replacement, 'placeholder' => 'Выберите замену...', 'id' => 'product1creplacement-guid_replacement-' . $key, 'class' => 'guid-replacement-select'], + 'pluginOptions' => [ + 'allowClear' => true, + 'minimumInputLength' => 1, + 'ajax' => [ + 'url' => \yii\helpers\Url::to(['/crud/product1c-replacement/search']), + 'dataType' => 'json', + 'data' => new JsExpression('function(params) { return {q:params.term}; }'), + 'processResults' => new JsExpression('function(data) { + return { + results: $.map(data.items, function(item) { + return { + id: item.id, + text: item.name + }; + }) + }; + }'), + ], + 'initSelection' => new JsExpression('function (element, callback) { + var data = {id: ' . json_encode($replacement->guid_replacement) . ', text: ' . json_encode($replacementName) . '}; + callback(data); + }'), + ], + ]) ?> + +
+ + +
+
+ + + + +
+ 'btn btn-success']) ?> + +
+ + + + + +
+ + $replacement): */?> \ No newline at end of file diff --git a/erp24/views/crud/product1c-replacement/update.php b/erp24/views/crud/product1c-replacement/update.php index c73b731d..ad0b6405 100644 --- a/erp24/views/crud/product1c-replacement/update.php +++ b/erp24/views/crud/product1c-replacement/update.php @@ -4,18 +4,19 @@ use yii\helpers\Html; /** @var yii\web\View $this */ /** @var yii_app\records\Product1cReplacement $model */ - -$this->title = 'Update Product1c Replacement: ' . $model->id; +/** @var yii_app\records\Product1cReplacement $replacements */ +$this->title = 'Редактирование замен: ' . $model->product->name; $this->params['breadcrumbs'][] = ['label' => 'Product1c Replacements', 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = 'Update'; ?> -
- +
+ 'btn btn-danger my-4']) ?>

title) ?>

- render('_form', [ + render('multy-form', [ 'model' => $model, + 'replacements' => $replacements, ]) ?>
diff --git a/erp24/views/crud/product1c-replacement/view.php b/erp24/views/crud/product1c-replacement/view.php index 45331245..179a8b0d 100644 --- a/erp24/views/crud/product1c-replacement/view.php +++ b/erp24/views/crud/product1c-replacement/view.php @@ -1,40 +1,124 @@ title = $model->id; +$this->title = $model->product->name; $this->params['breadcrumbs'][] = ['label' => 'Product1c Replacements', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; \yii\web\YiiAsset::register($this); + +$this->registerJs(<< -
+
-

title) ?>

+

Замены для title) ?>

- $model->id], ['class' => 'btn btn-primary']) ?> - $model->id], [ - 'class' => 'btn btn-danger', - 'data' => [ - 'confirm' => 'Are you sure you want to delete this item?', - 'method' => 'post', - ], - ]) ?> + $model->guid], ['class' => 'btn btn-primary']) ?> + 'btn btn-danger']) ?> + + 'btn btn-success']) ?>

+ 'pjax-container']); ?> +
+ $replacements, + + 'columns' => [ + /*[ + 'attribute' => 'guid', + 'label' => 'GUID, который заменяют', + 'value' => function ($model) { + + $product = $model->product; + if ($product) { + return Html::encode($product->name . ' (' . $model->guid . ', ' . $product->code . ', ' . $product->articule . ')'); + } + return Html::encode($model->guid); + }, + 'format' => 'raw', + ],*/ + [ + 'label' => 'GUIDы замены', + 'attribute' => 'replacement_guid', + 'value' => function ($model) { - $model, - 'attributes' => [ - 'id', - 'guid', - 'guid_replacement', - 'created_at', - 'updated_at', + $product = Products1c::findOne(['id' => $model->guid_replacement, 'tip' => 'products']); + if ($product) { + return Html::encode($product->name . ' (' . $model->guid . ', ' . $product->code . ', ' . $product->articule . ')'); + } + return Html::encode($model->guid_replacement); + }, + 'format' => 'raw', + ], + /*[ + 'class' => ActionColumn::class, + 'template' => '{delete}', + 'buttons' => [ + 'delete' => function ($url, $model) { + return Html::a( + '', + $url, + [ + 'title' => 'Удалить', + 'aria-label' => 'Удалить', + 'data-pjax' => '0', + 'class' => 'soft-delete', + 'data-method' => false, + //'data-confirm' => 'Вы уверены, что хотите удалить эту запись?', + 'data-id' => $model->id + ] + ); + }, + ], + ],*/ ], - ]) ?> + ]); + + + + ?> + + +
+
diff --git a/erp24/web/js/crud/product1cReplacement/_form.js b/erp24/web/js/crud/product1cReplacement/_form.js new file mode 100644 index 00000000..88918ef3 --- /dev/null +++ b/erp24/web/js/crud/product1cReplacement/_form.js @@ -0,0 +1,49 @@ +$(document).ready(function () { + let counter = 1; + + // Добавление нового поля + $('#add-guid-replacement').on('click', function () { + counter++; + let newField = ` + +
+ + + +
+ + `; + $('#guid-replacement-container').append(newField); + + // Инициализация Select2 с использованием AJAX для нового поля + $(`#product1creplacement-guid_replacement-${counter}`).select2({ + placeholder: 'Выберите замену...', + allowClear: true, + minimumInputLength: 1, + ajax: { + url: '/crud/product1c-replacement/search', // Замените URL на ваш реальный путь поиска + dataType: 'json', + data: function (params) { + return { q: params.term }; // Передача поискового термина + }, + processResults: function (data) { + return { + results: $.map(data.items, function (item) { + return { + id: item.id, + text: item.name + }; + }) + }; + } + } + }); + }); + + // Удаление поля + $(document).on('click', '.remove-guid-replacement', function () { + let target = $(this).data('target'); + $(target).remove(); // Удаляем группу полей + }); +}); \ No newline at end of file diff --git a/erp24/web/js/crud/product1cReplacement/multy-form.js b/erp24/web/js/crud/product1cReplacement/multy-form.js new file mode 100644 index 00000000..a71e8580 --- /dev/null +++ b/erp24/web/js/crud/product1cReplacement/multy-form.js @@ -0,0 +1,80 @@ +function initReplacementHandlers() { + let counter = $('.guid-replacement-select').length; + + $('#add-guid-replacement').on('click', function () { + counter++; + let newField = ` +
+ + + +
+ `; + $('#guid-replacement-container').append(newField); + + // Инициализация Select2 для нового поля + $(`#product1creplacement-guid_replacement-${counter}`).select2({ + placeholder: 'Выберите замену...', + allowClear: true, + minimumInputLength: 1, + ajax: { + url: '/crud/product1c-replacement/search', + dataType: 'json', + data: function (params) { + return { q: params.term }; + }, + processResults: function (data) { + return { + results: $.map(data.items, function (item) { + return { id: item.id, text: item.name }; + }) + }; + } + } + }); + }); + + $(document).on('click', '.remove-guid-replacement', function () { + let target = $(this).data('target'); + $(target).remove(); + }); + + $(document).on('click', '.delete-guid-replacement', function (e) { + e.preventDefault(); + if (!confirm('Вы уверены, что хотите удалить эту запись?')) { + return; + } + + var url = $(this).data('url'); + $.ajax({ + url: url, + type: 'POST', + success: function(data) { + console.log(data); + if (data.success) { + // Перезагрузка через Pjax после успешного удаления + $.pjax.reload({container: '#pjax-container', async: false}); + } else { + alert(data.message || 'Ошибка при удалении записи.'); + } + }, + error: function() { + alert('Ошибка при выполнении запроса.'); + } + }); + }); +} + +// Инициализация обработчиков при загрузке страницы +$(document).ready(function () { + initReplacementHandlers(); + $(document).on('pjax:end', function () { + console.log('Pjax завершен'); + initReplacementHandlers(); + }); + +}); + + +