$model = new StoresTypeList();
$editId = $this->request->post('editId');
+ $dataProvider = new ActiveDataProvider([
+ 'query' => StoresTypeList::find(),
+ ]);
+
+
if ($model->load($this->request->post())) {
if (!empty($editId)) {
// Редактирование
return $this->redirect(['index']);
} else {
Yii::$app->session->setFlash('error', 'Ошибка сохранения.');
+ return $this->renderAjax('index', [
+ 'model' => $model,
+ 'dataProvider' => $dataProvider,
+ ]);
}
}
} else {
$model->type_alias = strtolower(preg_replace('/[\s-]+/', '_', $model->type_name));
+ $existingDeleted = StoresTypeList::find()->where(['type_name' => $model->type_name, 'active' => 0])->one();
+ if ($existingDeleted) {
+ Yii::$app->session->setFlash('error', 'Запись с таким именем была удалена. Вы можете восстановить её.');
+ if (Yii::$app->request->isPjax) {
+ return $this->renderAjax('index', [
+ 'model' => $model,
+ 'dataProvider' => $dataProvider,
+ ]);
+ }
+ return;
+ }
if ($model->save()) {
Yii::$app->session->setFlash('success', 'Новая запись успешно создана.');
return $this->redirect(['index']);
} else {
Yii::$app->session->setFlash('error', 'Ошибка сохранения.');
+ if (Yii::$app->request->isPjax) {
+ return $this->renderAjax('index', [
+ 'model' => $model,
+ 'dataProvider' => $dataProvider,
+ ]);
+ }
}
}
}
- $dataProvider = new ActiveDataProvider([
- 'query' => StoresTypeList::find(),
- ]);
-
return $this->render('index', [
'dataProvider' => $dataProvider,
'model' => $model,
*/
public function actionDelete($id)
{
- $this->findModel($id)->delete();
+ $this->findModel($id)->softDelete();
if (Yii::$app->request->isAjax) {
return $this->asJson(['success' => true, 'message' => 'Запись успешно удалена.']);
'type_name' => $this->string()->notNull()->comment('Наименование типа магазина'),
'type_alias' => $this->string()->notNull()->comment('Алиас типа магазина'),
'type_description' => $this->string()->null()->comment('Описание типа магазина'),
+ 'active' => $this->tinyInteger()->notNull()->defaultValue(1)->comment('Активность'),
+ 'deleted_by' => $this->integer()->null()->comment('Пользователь, удаливший запись'),
+ 'deleted_at' => $this->timestamp()
+ ->null()->defaultValue(null)->comment('Дата мягкого удаления'),
'created_at' => $this->dateTime()
->notNull()
->defaultExpression('CURRENT_TIMESTAMP')
namespace yii_app\records;
use Yii;
+use yii_app\traits\SoftDeleteTrait;
/**
* This is the model class for table "stores_type_list".
* @property string $type_name Наименование типа магазина
* @property string $type_alias Алиас типа магазина
* @property string|null $type_description Описание типа магазина
+ * @property Admin $deleted_by удаливший пользователь
+ * @property int $active активность
+ * @property string $deleted_at время удаления
* @property string $created_at Дата создания записи
*/
class StoresTypeList extends \yii\db\ActiveRecord
{
+ use SoftDeleteTrait;
+
/**
* {@inheritdoc}
*/
{
return [
[['type_name'], 'required'],
- [['created_at'], 'safe'],
- [['type_name'], 'unique', 'message' => 'Название "{value}" уже существует.'],
+ [['created_at', 'active'], 'safe'],
+ [['type_name'], 'unique', 'targetAttribute' => 'type_name', 'filter' => ['active' => 1], 'message' => 'Название "{value}" уже существует.'],
[['type_name', 'type_alias', 'type_description'], 'string', 'max' => 255],
];
}
'created_at' => 'Дата создания записи',
];
}
+
+ public static function hasSoftDelete(): bool
+ {
+ return true;
+ }
+
+ public static function find()
+ {
+ $query = parent::find();
+ if (static::hasSoftDelete()) {
+ $query->andWhere(['active' => 1]);
+ }
+ return $query;
+ }
}
namespace yii_app\traits;
use Yii;
-use yii\db\ActiveQuery;
trait SoftDeleteTrait
{
document.addEventListener('DOMContentLoaded', function () {
+ init();
+ $(document).on('pjax:end', function () {
+ console.log('Pjax обновил содержимое.');
+ init();
+ });
+});
+
+
+
+function init () {
const list = document.getElementById('record-list');
const typeNameField = document.getElementById('type-name-field');
const editIdInput = document.getElementById('edit-id');
const id = target.dataset.id;
fetch('/stores-type-list/get-record?id=' + id)
- .then(response => response.json())
+ .then(response => response.json())
.then(data => {
if (data.error) {
alert(data.error);
item.classList.remove('active');
});
});
-});
\ No newline at end of file
+}
\ No newline at end of file