]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Создание и редактирование записей
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Fri, 15 Nov 2024 13:59:43 +0000 (16:59 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Fri, 15 Nov 2024 13:59:43 +0000 (16:59 +0300)
12 files changed:
erp24/controllers/crud/Product1cReplacementController.php
erp24/migrations/m241114_085742_create_product_1c_replacement_table.php
erp24/records/Product1cReplacement.php
erp24/records/Product1cReplacementSearch.php
erp24/views/crud/product1c-replacement/_form.php
erp24/views/crud/product1c-replacement/create.php
erp24/views/crud/product1c-replacement/index.php
erp24/views/crud/product1c-replacement/multy-form.php [new file with mode: 0644]
erp24/views/crud/product1c-replacement/update.php
erp24/views/crud/product1c-replacement/view.php
erp24/web/js/crud/product1cReplacement/_form.js [new file with mode: 0644]
erp24/web/js/crud/product1cReplacement/multy-form.js [new file with mode: 0644]

index d9bf05e3577c696c3fe82e8c0c5306ece4645830..5a0e7faac02705418876e731f3276ab078d3ad9a 100644 (file)
@@ -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);
 
-        // Ð\93Ñ\80Ñ\83ппиÑ\80Ñ\83ем Ð´Ð°Ð½Ð½Ñ\8bе по guid
-        $models = $dataProvider->query->all();
+        // Ð\9fолÑ\83Ñ\87аем Ñ\83никалÑ\8cнÑ\8bе Ð·Ð½Ð°Ñ\87ениÑ\8f по 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.');
+    }
 }
index 8c2a324b2072f17f5c506f9846a2d130ec765d35..94b61c2e04826175552578d150d2420440141a68 100644 (file)
@@ -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),
         ]);
     }
 
index 57e5889d3347276deaf9f9dd83375c7406baf5c2..5b177bd84e09e75e4be5e3175bf506e95cc9e650 100644 (file)
@@ -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]);
+    }
 }
index abdcd51aa8bfe46267a3f567f986f54571ddea00..91ab1b72b18d7102e3d7cc78efdf4185982eb53b 100644 (file)
@@ -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
index 35fd0f1b6aa489b2189fc270459cd2365b2e1806..82f39b9b89e30dc3b69ea1023f2625f5d7360659 100644 (file)
@@ -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]);
+
 ?>
 
-<div class="product1-creplacement-form">
+<div class="product1-creplacement-form p-4">
+
+    <?php $form = ActiveForm::begin(['id' => 'product-replacement-form']); ?>
+    <div class="row">
+
+    <div class="col-6">
 
-    <?php $form = ActiveForm::begin(); ?>
+        <?= $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 // Убедитесь, что возвращаете корректные данные
+                        };
+                    })
+                };
+            }'),
+                ],
+            ],
+        ]) ?>
+
+        </div>
+    </div>
 
-    <?= $form->field($model, 'guid')->textInput(['maxlength' => true]) ?>
 
-    <?= $form->field($model, 'guid_replacement')->textInput(['maxlength' => true]) ?>
+    <div class="row">
+    <div id="guid-replacement-container" class="col-6">
+        <?= $form->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 // Убедитесь, что возвращаете корректные данные
+                        };
+                    })
+                };
+            }'),
+                ],
+            ],
+        ]) ?>
+    </div>
+    </div>
 
-    <?= $form->field($model, 'created_at')->textInput() ?>
+    <!-- Кнопка добавления нового Select2 -->
+    <button type="button" id="add-guid-replacement" class="btn btn-primary my-4">Добавить еще замену</button>
 
-    <?= $form->field($model, 'updated_at')->textInput() ?>
 
-    <div class="form-group">
-        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
+    <div class="form-group py-4">
+        <?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
+        <?= Html::a('Отмена', ['index'], ['class' => 'btn btn-danger']) ?>
     </div>
 
     <?php ActiveForm::end(); ?>
index 6511ef7063861b7a7b0697e881c693938d5ee7aa..52a54412752d52e94ef1f3d905c21290fb18577c 100644 (file)
@@ -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;
 ?>
-<div class="product1-creplacement-create">
+<div class="product1-creplacement-create p-4">
 
     <h1><?= Html::encode($this->title) ?></h1>
 
     <?= $this->render('_form', [
         'model' => $model,
+
     ]) ?>
 
 </div>
index b04c6216f2bfb5e05e055d8a859a22914cc8eb29..918d8f27a963e63b460dad42c9eed58cf7745877 100644 (file)
@@ -1,16 +1,22 @@
 <?php
 
+use yii\grid\ActionColumn;
 use yii\helpers\Html;
 use yii\grid\GridView;
+use yii\helpers\Url;
 use yii\widgets\Pjax;
+use yii_app\records\Product1cReplacementSearch;
+use yii_app\records\Products1c;
 
 /* @var $this yii\web\View */
-/* @var $searchModel app\models\Product1CReplacementSearch */
+/* @var $searchModel app\records\Product1cReplacementSearch */
 /* @var $dataProvider yii\data\ActiveDataProvider */
 /* @var $groupedReplacements array */
 
 $this->title = 'Возможные замены номенклатуры';
 $this->params['breadcrumbs'][] = $this->title;
+
+
 ?>
 <div class="product1c-replacement-index p-4">
 
@@ -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 = '<ul>';
                         foreach ($guidReplacements as $replacementGuid) {
-                            $listItems .= '<li>' . Html::encode($replacementGuid) . '</li>';
+
+                            $replacementProduct = Products1c::findOne(['id' => $replacementGuid, 'tip' => 'products']);
+                            if ($replacementProduct) {
+
+                                $code = $replacementProduct->code ? (', ' . $replacementProduct->code) : '';
+                                $articule = $replacementProduct->articule ? (', ' . $replacementProduct->articule) : '';
+
+                                $listItems .= '<li>' . Html::encode($replacementProduct->name . ' (' . $replacementGuid . $code . $articule . ')') . '</li> <br>';
+                            } else {
+                                $listItems .= '<li>' . Html::encode($replacementGuid) . '</li>';
+                            }
                         }
                         $listItems .= '</ul>';
                         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;
+                }
+            ],
         ],
     ]); ?>
 
-    <?php Pjax::end(); ?>
+    <?php Pjax::end();
+
+    ?>
+
+
 
 </div>
\ 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 (file)
index 0000000..ec2bed4
--- /dev/null
@@ -0,0 +1,117 @@
+<?php
+
+use yii\helpers\Html;
+use yii\widgets\ActiveForm;
+use kartik\select2\Select2;
+use yii\web\JsExpression;
+use yii\widgets\Pjax;
+
+/** @var yii\web\View $this */
+/** @var yii_app\records\Product1cReplacement $model */
+/** @var yii\widgets\ActiveForm $form */
+/** @var yii_app\records\Product1cReplacement $replacements */
+
+$this->registerJsFile('/js/crud/product1cReplacement/multy-form.js', ['position' => \yii\web\View::POS_END]);
+?>
+<?php Pjax::begin(['id' => 'pjax-container']); ?>
+    <div class="product1-creplacement-form p-4">
+
+        <?php $form = ActiveForm::begin(['id' => 'product-replacement-form']); ?>
+
+        <!-- Скрытое поле GUID -->
+        <?= Html::activeHiddenInput($model, 'guid') ?>
+       <!-- --><?php /*= $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
+                            };
+                        })
+                    };
+                }'),
+                ],
+            ],
+        ]) */?>
+
+<div class="row">
+        <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;">
+                <?= Html::hiddenInput('Product1cReplacement[replacement_ids][]', $replacement->id) ?>
+                <?= $form->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);
+                }'),
+                    ],
+                ]) ?>
+                <button type="button"
+                        class="btn btn-danger delete-guid-replacement btn-remove"
+                        data-url="<?= \yii\helpers\Url::to(['/crud/product1c-replacement/delete', 'id' => $replacement->id]) ?>"
+                        style="position: absolute; right: -40px; top:33%; width:auto;">
+                    ×
+                </button>
+            </div>
+            <?php endforeach; ?>
+
+        </div>
+</div>
+        <!-- Кнопка добавления нового Select2 -->
+        <button type="button" id="add-guid-replacement" class="btn btn-primary my-4">Добавить замену</button>
+
+
+        <div class="form-group">
+            <?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
+
+        </div>
+
+        <?php ActiveForm::end(); ?>
+
+
+
+    </div>
+<?php Pjax::end(); ?>
+<?php /*foreach ($replacements as $key => $replacement): */?><!--
+    <?php
+/*    // Проверяем, существует ли связанный продукт
+    $replacementName = $replacement->replacementProduct ? $replacement->replacementProduct->name : 'Неизвестно';
+    print_r($replacement);
+    */?>
+
+
+--><?php /*endforeach; */?>
\ No newline at end of file
index c73b731d517717d256819b76293b874ebb5f3a81..ad0b6405c72ba41cf0757f93cc13104d33ec9c48 100644 (file)
@@ -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';
 ?>
-<div class="product1-creplacement-update">
-
+<div class="product1-creplacement-update p-4">
+    <?= Html::a('Отмена', ['index'], ['class' => 'btn btn-danger my-4']) ?>
     <h1><?= Html::encode($this->title) ?></h1>
 
-    <?= $this->render('_form', [
+    <?= $this->render('multy-form', [
         'model' => $model,
+        'replacements' => $replacements,
     ]) ?>
 
 </div>
index 453312451bbac367142fa3a96a403a97fb23bcde..179a8b0dac003e8520b80e345f05ee67c53ddcb0 100644 (file)
 <?php
 
+use kartik\grid\ActionColumn;
+use kartik\grid\GridView;
 use yii\helpers\Html;
 use yii\widgets\DetailView;
+use yii\widgets\Pjax;
+use yii_app\records\Products1c;
 
 /** @var yii\web\View $this */
 /** @var yii_app\records\Product1cReplacement $model */
+/** @var  yii_app\records\Product1cReplacement $replacements  */
 
-$this->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(<<<JS
+$(document).ready(function () {
+    $(document).on('click', '.soft-delete', function(e) {
+        e.preventDefault();
+        if (!confirm($(this).data('confirm'))) {
+            return;
+        }
+
+        var url = $(this).attr('href');
+        $.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('Ошибка при выполнении запроса.');
+            }
+        });
+    });
+});
+
+JS
+);
 ?>
-<div class="product1-creplacement-view">
+<div class="product1-creplacement-view p-4">
 
-    <h1><?= Html::encode($this->title) ?></h1>
+    <h1>Замены для <?= Html::encode($this->title) ?></h1>
 
     <p>
-        <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
-        <?= Html::a('Delete', ['delete', 'id' => $model->id], [
-            'class' => 'btn btn-danger',
-            'data' => [
-                'confirm' => 'Are you sure you want to delete this item?',
-                'method' => 'post',
-            ],
-        ]) ?>
+        <?= Html::a('Редактировать', ['update', 'id' => $model->guid], ['class' => 'btn btn-primary']) ?>
+        <?= Html::a('Назад', ['index'], ['class' => 'btn btn-danger']) ?>
+
+        <?= Html::a('Просмотр логов', ['index'], ['class' => 'btn btn-success']) ?>
     </p>
+    <?php Pjax::begin(['id' => 'pjax-container']); ?>
+    <div id="grid-container">
+    <?= GridView::widget([
+        'dataProvider' => $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) {
 
-    <?= DetailView::widget([
-        '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(
+                            '<span class="glyphicon glyphicon-trash"></span>',
+                            $url,
+                            [
+                                'title' => 'Удалить',
+                                'aria-label' => 'Удалить',
+                                'data-pjax' => '0',
+                                'class' => 'soft-delete',
+                                'data-method' => false,
+                                //'data-confirm' => 'Вы уверены, что хотите удалить эту запись?',
+                                'data-id' => $model->id
+                            ]
+                        );
+                    },
+                ],
+            ],*/
         ],
-    ]) ?>
+    ]);
+
+
+
+    ?>
+
+
+    </div>
+    <?php Pjax::end(); ?>
 
 </div>
diff --git a/erp24/web/js/crud/product1cReplacement/_form.js b/erp24/web/js/crud/product1cReplacement/_form.js
new file mode 100644 (file)
index 0000000..88918ef
--- /dev/null
@@ -0,0 +1,49 @@
+$(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({
+            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 (file)
index 0000000..a71e858
--- /dev/null
@@ -0,0 +1,80 @@
+function initReplacementHandlers() {
+    let counter = $('.guid-replacement-select').length;
+
+    $('#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}">GUID Замена</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 для нового поля
+        $(`#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();
+    });
+
+});
+
+
+