diff --git a/backend/controllers/ArticlesController.php b/backend/controllers/ArticlesController.php
index aaf9835..6a3f3e0 100644
--- a/backend/controllers/ArticlesController.php
+++ b/backend/controllers/ArticlesController.php
@@ -9,7 +9,6 @@
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use developeruz\db_rbac\behaviors\AccessBehavior;
- use yii\web\UploadedFile;
/**
* ArticlesController implements the CRUD actions for Articles model.
@@ -86,18 +85,12 @@
$model_langs = $model->generateLangs();
if($model->load(Yii::$app->request->post())) {
$model->loadLangs(\Yii::$app->request, $model_langs);
- if($model->save()) {
- if($model->linkLangs($model_langs) && $model->saveLangs($model_langs)) {
- return $this->redirect([
- 'view',
- 'id' => $model->id,
- ]);
- } else {
- return $this->redirect([
- 'update',
- 'id' => $model->id,
- ]);
- }
+ $model->model_langs = $model_langs;
+ if($model->save() && $model->transactionStatus) {
+ return $this->redirect([
+ 'view',
+ 'id' => $model->id,
+ ]);
}
}
return $this->render('create', [
@@ -120,13 +113,12 @@
$model_langs = $model->generateLangs();
if($model->load(Yii::$app->request->post())) {
$model->loadLangs(\Yii::$app->request, $model_langs);
- if($model->save()) {
- if($model->linkLangs($model_langs) && $model->saveLangs($model_langs)) {
- return $this->redirect([
- 'view',
- 'id' => $model->id,
- ]);
- }
+ $model->model_langs = $model_langs;
+ if($model->save() && $model->transactionStatus) {
+ return $this->redirect([
+ 'view',
+ 'id' => $model->id,
+ ]);
}
}
return $this->render('update', [
@@ -162,7 +154,11 @@
*/
protected function findModel($id)
{
- if(( $model = Articles::findOne($id) ) !== NULL) {
+ if(( $model = Articles::find()
+ ->where([ 'id' => $id ])
+ ->with('lang')
+ ->one() ) !== NULL
+ ) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
diff --git a/backend/views/articles/index.php b/backend/views/articles/index.php
index 7d2856a..c0655da 100644
--- a/backend/views/articles/index.php
+++ b/backend/views/articles/index.php
@@ -1,29 +1,34 @@
title = \Yii::t('app', 'Articles');
-$this->params['breadcrumbs'][] = $this->title;
+
+ use yii\helpers\Html;
+ use yii\grid\GridView;
+
+ /**
+ * @var yii\web\View $this
+ * @var common\models\ArticlesSearch $searchModel
+ * @var yii\data\ActiveDataProvider $dataProvider
+ */
+
+ $this->title = \Yii::t('app', 'Articles');
+ $this->params[ 'breadcrumbs' ][] = $this->title;
?>
= Html::encode($this->title) ?>
- = Html::a(\Yii::t('app', 'Create Articles'), ['create'], ['class' => 'btn btn-success']) ?>
+ = Html::a(\Yii::t('app', 'Create Articles'), [ 'create' ], [ 'class' => 'btn btn-success' ]) ?>
= GridView::widget([
'dataProvider' => $dataProvider,
- 'filterModel' => $searchModel,
- 'columns' => [
- ['class' => 'yii\grid\SerialColumn'],
+ 'filterModel' => $searchModel,
+ 'columns' => [
'id',
- 'date',
+ [
+ 'attribute' => 'title',
+ 'value' => 'lang.title',
+ ],
+ 'date:date',
'imageUrl:image',
- ['class' => 'yii\grid\ActionColumn'],
+ [ 'class' => 'yii\grid\ActionColumn' ],
],
]); ?>
diff --git a/backend/views/articles/view.php b/backend/views/articles/view.php
index ce6f4cb..462345e 100644
--- a/backend/views/articles/view.php
+++ b/backend/views/articles/view.php
@@ -1,32 +1,46 @@
title = $model->id;
-$this->params['breadcrumbs'][] = ['label' => \Yii::t('app', 'Articles'), 'url' => ['index']];
-$this->params['breadcrumbs'][] = $this->title;
+
+ use yii\helpers\Html;
+ use yii\widgets\DetailView;
+
+ /**
+ * @var yii\web\View $this
+ * @var common\models\Articles $model
+ */
+
+ $this->title = $model->lang->title;
+ $this->params[ 'breadcrumbs' ][] = [
+ 'label' => \Yii::t('app', 'Articles'),
+ 'url' => [ 'index' ],
+ ];
+ $this->params[ 'breadcrumbs' ][] = $this->title;
?>
= Html::encode($this->title) ?>
- = Html::a(\Yii::t('app', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
- = Html::a(\Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], [
+ = Html::a(\Yii::t('app', 'Update'), [
+ 'update',
+ 'id' => $model->id,
+ ], [ 'class' => 'btn btn-primary' ]) ?>
+ = Html::a(\Yii::t('app', 'Delete'), [
+ 'delete',
+ 'id' => $model->id,
+ ], [
'class' => 'btn btn-danger',
- 'data' => [
+ 'data' => [
'confirm' => \Yii::t('app', 'Are you sure you want to delete this item?'),
- 'method' => 'post',
+ 'method' => 'post',
],
]) ?>
= DetailView::widget([
- 'model' => $model,
+ 'model' => $model,
'attributes' => [
'id',
- 'date',
+ 'date:date',
+ 'lang.title',
+ 'lang.body:html',
+ 'imageUrl:image',
],
]) ?>
diff --git a/backend/web/css/site.css b/backend/web/css/site.css
index a454526..7ddcd31 100755
--- a/backend/web/css/site.css
+++ b/backend/web/css/site.css
@@ -207,3 +207,9 @@ a.desc:after {
text-align: center;
font-size: 13px !important;
}
+.grid-view td img {
+ max-width: 250px;
+}
+.detail-view td img {
+ max-width: 100%;
+}
\ No newline at end of file
diff --git a/common/models/Articles.php b/common/models/Articles.php
index af4263e..6a7be6d 100644
--- a/common/models/Articles.php
+++ b/common/models/Articles.php
@@ -1,7 +1,8 @@
[
'class' => LanguageBehavior::className(),
],
+ 'transaction' => [
+ 'class' => TransactionBehavior::className(),
+ ],
];
}
diff --git a/common/models/ArticlesSearch.php b/common/models/ArticlesSearch.php
index 964cd28..a522cfb 100644
--- a/common/models/ArticlesSearch.php
+++ b/common/models/ArticlesSearch.php
@@ -1,69 +1,96 @@
$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');
+
+ public $title;
+
+ /**
+ * @inheritdoc
+ */
+ public function rules()
+ {
+ return [
+ [
+ [ 'id' ],
+ 'integer',
+ ],
+ [
+ [ 'title' ],
+ 'string',
+ ],
+ ];
+ }
+
+ public function behaviors()
+ {
+ return [];
+ }
+
+ /**
+ * @inheritdoc
+ */
+ public function scenarios()
+ {
+ // bypass scenarios() implementation in the parent class
+ return Model::scenarios();
+ }
+
+ /**
+ * Creates data provider instance with search query applied
+ *
+ * @param array $params
+ *
+ * @return ActiveDataProvider
+ */
+ public function search($params)
+ {
+ $query = Articles::find()
+ ->joinWith('lang');
+
+ // add conditions that should always apply here
+
+ $dataProvider = new ActiveDataProvider([
+ 'query' => $query,
+ 'sort' => [
+ 'attributes' => [
+ 'id',
+ 'title' => [
+ 'asc' => [ 'articles_lang.title' => SORT_ASC ],
+ 'desc' => [ 'articles_lang.title' => SORT_DESC ],
+ ],
+ ],
+ ],
+ ]);
+
+ $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,
+ ]);
+
+ $query->andFilterWhere([
+ 'like',
+ 'articles_lang.title',
+ $this->title,
+ ]);
+
return $dataProvider;
}
-
- // grid filtering conditions
- $query->andFilterWhere([
- 'id' => $this->id,
- ]);
-
- return $dataProvider;
}
-}
diff --git a/common/modules/language/behaviors/TransactionBehavior.php b/common/modules/language/behaviors/TransactionBehavior.php
new file mode 100644
index 0000000..43ce2a9
--- /dev/null
+++ b/common/modules/language/behaviors/TransactionBehavior.php
@@ -0,0 +1,77 @@
+ 'beforeSave',
+ ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
+ ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
+ ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
+ ];
+ }
+
+ public function beforeSave($event) {
+ /**
+ * @var ActiveRecord $owner
+ */
+ $owner = $this->owner;
+ $db = $owner::getDb();
+ $this->_transaction = $db->beginTransaction();
+ }
+
+ public function afterSave($event) {
+ /**
+ * @var ActiveRecord $owner
+ */
+ $owner = $this->owner;
+ if(!empty($this->model_langs) && $owner->getBehavior('language')) {
+ if($owner->linkLangs($this->model_langs) && $owner->saveLangs($this->model_langs)) {
+ $this->_transaction->commit();
+ $this->_transaction_status = true;
+ } else {
+ $this->_transaction->rollBack();
+ $this->_transaction_status = false;
+ }
+ } else {
+ $this->_transaction->commit();
+ $this->_transaction_status = true;
+ }
+ }
+
+ /**
+ * @return bool
+ */
+ public function getTransactionStatus():bool {
+ return $this->_transaction_status;
+ }
+
+ }
\ No newline at end of file
diff --git a/common/modules/language/readme.txt b/common/modules/language/readme.txt
index 973803e..63d00e6 100644
--- a/common/modules/language/readme.txt
+++ b/common/modules/language/readme.txt
@@ -45,6 +45,9 @@ public function behaviors() {
'ownerKey' => {Table}->id //optional, default to {Table}->primaryKey()[0]
'langKey' => {TableLang}->table_id //optional, default to {Table}->tableName().'_id'
],
+ 'transaction' => [
+ 'class' => TransactionBehavior::className(),
+ ],
];
}
3.1. PHPDoc для {Table}:
@@ -65,6 +68,11 @@ public function behaviors() {
* @method bool linkLangs(ActiveRecord[] $model_langs)
* @method bool saveLangs(ActiveRecord[] $model_langs)
* * End language behavior *
+ * * From transaction behavior *
+ * @property {TableLang}[] $model_langs
+ * @property bool $transactionStatus
+ * @method bool getTransactionStatus()
+ * * End transaction behavior *
3.2. Убрать language behavior с наследуемых таблиц от {Table} ({TableSearch}...)
4. Доступные полезные методы:
{Table}->getLangs() - получить все текущие {TableLang} для {Table} проиндексированные по language_id
@@ -83,6 +91,6 @@ public function behaviors() {
6. Обрабатывать данные в контроллере.
1. После создания/поиска {Table} создаем/находим языковые модели {Table}->generateLangs()
2. При POST запросе загружаем данные в языковые модели {Table}->loadLangs(Request $request, {TableLangs[]} $model_langs)
- 3. Связываем модель {Table} с языковыми моделями {Table}->linkLangs({TableLang[]} $model_langs). Возвращает true при успехе.
- 4. Сохраняе языковые модели в базу {Table}->saveLangs({TableLang[]} $model_langs). Возвращает true при успешной валидации каждого {TableLang}.
+ 3. Передаем в свойство model_langs модели {Table} массив {TableLang[]}: $model->model_langs = $model_langs
+ 4. После сохранения, если транзанкция успешна, то свойство {Table}->transactionStatus будет true, иначе возникла ошибка в какой то модели.
7. Получать данные на публичной части сайта через {Table}->lang.
\ No newline at end of file
--
libgit2 0.21.4