namespace yii_app\controllers\crud;
use Yii;
+use yii\db\Transaction;
use yii\helpers\ArrayHelper;
use yii_app\records\MarketplaceOrder1cStatuses;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
+use yii_app\records\MarketplaceOrder1cStatusesRelations;
use yii_app\services\LessonService;
/**
}
}
+
+
$dataProvider = new ActiveDataProvider([
- 'query' => MarketplaceOrder1cStatuses::find()->orderBy(["posit" => SORT_ASC]),
- /*
- 'pagination' => [
- 'pageSize' => 50
- ],
- 'sort' => [
- 'defaultOrder' => [
- 'id' => SORT_DESC,
- ]
- ],
- */
+ 'query' => MarketplaceOrder1cStatuses::find()
+ ->with(['relationsFrom', 'nextStatuses'])
+ ->orderBy(['posit' => SORT_ASC]),
]);
return $this->render('index', [
{
$model = new MarketplaceOrder1cStatuses();
- if ($this->request->isPost) {
- if ($model->load($this->request->post()) && $model->save()) {
- return $this->redirect(['view', 'id' => $model->id]);
+ $relationModels = [new MarketplaceOrder1cStatusesRelations()];
+
+ $statusOptions = MarketplaceOrder1cStatuses::find()
+ ->select(['status'])
+ ->indexBy('id')
+ ->column();
+
+ if (Yii::$app->request->isPost) {
+ if ($model->load(Yii::$app->request->post())) {
+ $transaction = Yii::$app->db->beginTransaction(Transaction::SERIALIZABLE);
+ try {
+ if (!$model->save()) {
+ throw new \Exception('Не удалось сохранить MarketplaceOrder1cStatuses');
+ }
+
+ $postRelations = Yii::$app->request->post('Relations', []);
+
+ foreach ($postRelations as $i => $relData) {
+ if (empty($relData['status_id_to'])) {
+ continue;
+ }
+
+ $rel = new MarketplaceOrder1cStatusesRelations();
+ $rel->status_id_from = $model->id;
+ $rel->status_id_to = $relData['status_id_to'];
+ $rel->description = $relData['description'];
+ $rel->button_text = $relData['button_text'];
+
+ if (!$rel->save()) {
+ throw new \Exception('Не удалось сохранить Relation #' . $i);
+ }
+ }
+
+ $transaction->commit();
+ return $this->redirect(['view', 'id' => $model->id]);
+
+ } catch (\Exception $e) {
+ $transaction->rollBack();
+ Yii::$app->session->setFlash('error', 'Ошибка при сохранении: ' . $e->getMessage());
+ }
}
- } else {
- $model->loadDefaultValues();
}
+
return $this->render('create', [
- 'model' => $model,
+ 'model' => $model,
+ 'relationModels' => $relationModels,
+ 'statusOptions' => $statusOptions,
]);
}
{
$model = $this->findModel($id);
- if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
- return $this->redirect(['view', 'id' => $model->id]);
+ $existingRelations = $model->getRelationsFrom()->all();
+ $relationModels = count($existingRelations) ? $existingRelations : [new MarketplaceOrder1cStatusesRelations()];
+
+ $statusOptions = MarketplaceOrder1cStatuses::find()
+ ->select(['status'])
+ ->indexBy('id')
+ ->column();
+
+ if (Yii::$app->request->isPost) {
+ if ($model->load(Yii::$app->request->post())) {
+ $transaction = Yii::$app->db->beginTransaction(Transaction::SERIALIZABLE);
+ try {
+ if (!$model->save()) {
+ throw new \Exception('Не удалось сохранить основной статус');
+ }
+
+ MarketplaceOrder1cStatusesRelations::deleteAll(['status_id_from' => $model->id]);
+
+ $postRelations = Yii::$app->request->post('Relations', []);
+ foreach ($postRelations as $i => $relData) {
+ if (empty($relData['status_id_to'])) {
+ continue;
+ }
+ $rel = new MarketplaceOrder1cStatusesRelations();
+ $rel->status_id_from = $model->id;
+ $rel->status_id_to = $relData['status_id_to'];
+ $rel->description = $relData['description'];
+ $rel->button_text = $relData['button_text'];
+ if (!$rel->save()) {
+ throw new \Exception('Не удалось сохранить Relation #' . $i);
+ }
+ }
+
+ $transaction->commit();
+ return $this->redirect(['view', 'id' => $model->id]);
+ } catch (\Exception $e) {
+ $transaction->rollBack();
+ Yii::$app->session->setFlash('error', 'Ошибка при сохранении отношений: ' . $e->getMessage());
+ }
+ }
}
return $this->render('update', [
- 'model' => $model,
+ 'model' => $model,
+ 'relationModels' => $relationModels,
+ 'statusOptions' => $statusOptions,
]);
}
*/
protected function findModel($id)
{
- if (($model = MarketplaceOrder1cStatuses::findOne(['id' => $id])) !== null) {
- return $model;
+ $model = MarketplaceOrder1cStatuses::find()
+ ->with(['relationsFrom', 'nextStatuses'])
+ ->andWhere(['id' => $id])
+ ->one();
+
+ if ($model === null) {
+ throw new \yii\web\NotFoundHttpException('Запрошенная страница не найдена.');
}
- throw new NotFoundHttpException('The requested page does not exist.');
+ return $model;
}
}
namespace yii_app\records;
use Yii;
+use yii\db\ActiveQuery;
/**
* This is the model class for table "marketplace_order_1c_statuses".
'posit' => 'Порядок статусов',
];
}
+
+ public function getRelationsFrom(): ActiveQuery
+ {
+ return $this->hasMany(
+ MarketplaceOrder1cStatusesRelations::class,
+ ['status_id_from' => 'id']
+ );
+ }
+
+
+ public function getRelationsTo(): ActiveQuery
+ {
+ return $this->hasMany(
+ MarketplaceOrder1cStatusesRelations::class,
+ ['status_id_to' => 'id']
+ );
+ }
+
+ public function getNextStatuses(): ActiveQuery
+ {
+ return $this->hasMany(
+ MarketplaceOrder1cStatuses::class,
+ ['id' => 'status_id_to']
+ )->via('relationsFrom');
+ }
+
+ public function getPrevStatuses(): ActiveQuery
+ {
+ return $this->hasMany(
+ MarketplaceOrder1cStatuses::class,
+ ['id' => 'status_id_from']
+ )->via('relationsTo');
+ }
}
<?php
-
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/** @var yii\web\View $this */
/** @var yii_app\records\MarketplaceOrder1cStatuses $model */
-/** @var yii\widgets\ActiveForm $form */
+/** @var yii_app\records\MarketplaceOrder1cStatusesRelations[] $relationModels */
+/** @var array $statusOptions (ключ = id, значение = статус) */
+
+$js = <<<JS
+$(document).ready(function() {
+
+ $('#add-relation-btn').on('click', function() {
+ var template = $('#relation-template .relation-item.template');
+ var clone = template.clone().removeClass('template');
+ $('#relations-container').append(clone);
+ });
+
+ $('#relations-container').on('click', '.remove-relation-btn', function() {
+ $(this).closest('.relation-item').remove();
+ });
+});
+JS;
+$this->registerJs($js);
+
?>
<div class="marketplace-order1c-statuses-form">
<?php $form = ActiveForm::begin(); ?>
- <?= $form->field($model, 'marketplace_id')->dropDownList([1 => 'ФлауВау', 2 => 'ЯндексМаркет']) ?>
+ <!-- Поля самого статуса -->
+ <?= $form->field($model, 'marketplace_id')
+ ->dropDownList([1 => 'ФлауВау', 2 => 'ЯндексМаркет'], ['prompt' => 'Выберите маркетплейс']) ?>
<?= $form->field($model, 'status')->textInput(['maxlength' => true]) ?>
- <?= $form->field($model, 'status_instruction')->textarea(['rows' => 6]) ?>
+ <?= $form->field($model, 'status_instruction')->textarea(['rows' => 4]) ?>
+
+ <hr>
+
+
+ <h4>Связанные статусы (relations)</h4>
+ <div id="relations-container">
+ <?php foreach ($relationModels as $i => $rel): ?>
+ <div class="relation-item" style="border:1px solid #ddd; padding:10px; margin-bottom:10px; position: relative;">
+ <!-- Поле «Статус-назначения» -->
+ <?= Html::label('Статус-назначения', null, ['class' => 'control-label']) ?>
+ <?= Html::dropDownList(
+ "Relations[{$i}][status_id_to]",
+ $rel->status_id_to,
+ $statusOptions,
+ ['prompt' => '— выберите статус —', 'class' => 'form-control']
+ ); ?>
+
+
+ <?= Html::label('Описание (description)', null, ['class' => 'control-label', 'style' => 'margin-top:8px;']) ?>
+ <?= Html::textInput(
+ "Relations[{$i}][description]",
+ $rel->description,
+ ['class' => 'form-control']
+ ); ?>
+
+
+ <?= Html::label('Текст кнопки (button_text)', null, ['class' => 'control-label', 'style' => 'margin-top:8px;']) ?>
+ <?= Html::textInput(
+ "Relations[{$i}][button_text]",
+ $rel->button_text,
+ ['class' => 'form-control']
+ ); ?>
+
+
+ <button type="button" class="btn btn-danger btn-sm remove-relation-btn"
+ style="position:absolute; top:10px; right:10px;">
+ − Удалить
+ </button>
+ </div>
+ <?php endforeach; ?>
+ </div>
+
+ <button type="button" id="add-relation-btn" class="btn btn-primary btn-sm" style="margin-bottom:15px;">
+ + Добавить ещё одну связь
+ </button>
<div class="form-group">
<?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
-</div>
+
+
+ <div id="relation-template" style="display:none;">
+ <div class="relation-item template" style="border:1px solid #ddd; padding:10px; margin-bottom:10px; position: relative;">
+ <?= Html::label('Статус-назначения', null, ['class' => 'control-label']) ?>
+ <?= Html::dropDownList(
+ "Relations[__index__][status_id_to]",
+ null,
+ $statusOptions,
+ ['prompt' => '— выберите статус —', 'class' => 'form-control']
+ ); ?>
+
+ <?= Html::label('Описание (description)', null, ['class' => 'control-label', 'style' => 'margin-top:8px;']) ?>
+ <?= Html::textInput("Relations[__index__][description]", null, ['class' => 'form-control']) ?>
+
+ <?= Html::label('Текст кнопки (button_text)', null, ['class' => 'control-label', 'style' => 'margin-top:8px;']) ?>
+ <?= Html::textInput("Relations[__index__][button_text]", null, ['class' => 'form-control']) ?>
+
+ <button type="button" class="btn btn-danger btn-sm remove-relation-btn"
+ style="position:absolute; top:10px; right:10px;">
+ − Удалить
+ </button>
+ </div>
+ </div>
+</div>
\ No newline at end of file
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
- 'model' => $model,
+ 'model' => $model,
+ 'relationModels' => $relationModels,
+ 'statusOptions' => $statusOptions,
]) ?>
</div>
return Url::toRoute([$action, 'id' => $model->id]);
}
],
+ [
+ 'label' => 'Связанные статусы',
+ 'format' => 'raw',
+ 'value' => function (MarketplaceOrder1cStatuses $model) {
+ $links = [];
+ foreach ($model->nextStatuses as $nextStatus) {
+ $links[] = Html::a(
+ Html::encode($nextStatus->status),
+ ['/crud/marketplace-order-1c-statuses/view', 'id' => $nextStatus->id]
+ );
+ }
+ return empty($links)
+ ? '<span class="text-muted">— нет связи —</span>'
+ : implode('<br>', $links);
+ },
+ ],
],
]); ?>
</h1>
<?= $this->render('_form', [
- 'model' => $model,
+ 'model' => $model,
+ 'relationModels' => $relationModels,
+ 'statusOptions' => $statusOptions,
]) ?>
</div>
use yii\helpers\Html;
use yii\widgets\DetailView;
+use yii_app\records\MarketplaceOrder1cStatuses;
/** @var yii\web\View $this */
/** @var yii_app\records\MarketplaceOrder1cStatuses $model */
],
'status',
'status_instruction:ntext',
+ [
+ 'label' => 'Связанные статусы',
+ 'format' => 'raw',
+ 'value' => function (MarketplaceOrder1cStatuses $model) {
+ $links = [];
+ foreach ($model->nextStatuses as $nextStatus) {
+ $links[] = Html::a(
+ Html::encode($nextStatus->status),
+ ['marketplace-order1c-statuses/view', 'id' => $nextStatus->id]
+ );
+ }
+ return empty($links)
+ ? '<span class="text-muted">— нет связи —</span>'
+ : implode('<br>', $links);
+ },
+ ],
],
]) ?>