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.
'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()'),
],
]
$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', [
'groupedReplacements' => $groupedReplacements,
]);
}
-
/**
* Displays a single Product1CReplacement model.
* @param int $id ID
*/
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,
]);
}
* 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', [
]);
}
+ 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.
*/
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.
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.');
+ }
}
'guid_replacement' => $this->string()->notNull(),
'created_at' => $this->timestamp()->defaultExpression('CURRENT_TIMESTAMP'),
'updated_at' => $this->timestamp()->defaultValue(null),
+ 'deleted_at' => $this->timestamp()->defaultValue(null),
]);
}
{
return [
[['guid', 'guid_replacement'], 'required'],
- [['created_at', 'updated_at'], 'safe'],
+ [['created_at', 'updated_at', 'deleted_at'], 'safe'],
[['guid', 'guid_replacement'], 'string', 'max' => 255],
+
];
}
{
return [
'id' => 'ID',
- 'guid' => 'Guid',
- 'guid_replacement' => 'Guid Replacement',
- 'created_at' => 'Created At',
- 'updated_at' => 'Updated At',
+ 'guid' => 'Товар',
+ 'guid_replacement' => 'Замена',
+ 'created_at' => 'Создано',
+ 'updated_at' => 'Обновлено',
];
}
$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]);
+ }
}
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}
*/
{
return [
[['id'], 'integer'],
- [['guid', 'guid_replacement', 'created_at', 'updated_at'], 'safe'],
+ [['guid', 'guid_replacement', 'created_at', 'updated_at', 'deleted_at'], 'safe'],
];
}
*/
public function scenarios()
{
- // bypass scenarios() implementation in the parent class
return Model::scenarios();
}
{
$query = Product1cReplacement::find();
- // add conditions that should always apply here
+
+ $query->joinWith(['product']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
$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,
]);
$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
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(); ?>
/** @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>
<?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">
'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ы замены',
'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;
},
'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
--- /dev/null
+<?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
/** @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>
<?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>
--- /dev/null
+$(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
--- /dev/null
+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();
+ });
+
+});
+
+
+