#955

parent 27d17067
...@@ -14,6 +14,7 @@ return [ ...@@ -14,6 +14,7 @@ return [
'language' => 'ru-RU', 'language' => 'ru-RU',
'defaultRoute' => '/main/main-admin/index', 'defaultRoute' => '/main/main-admin/index',
'modules' => [ 'modules' => [
'languages' => ['class' => 'common\modules\languages\Module'],
'content' => ['class' => 'common\modules\content\Module'], 'content' => ['class' => 'common\modules\content\Module'],
'faq' => ['class' => 'common\modules\faq\Module'], 'faq' => ['class' => 'common\modules\faq\Module'],
'reviews' => ['class' => 'common\modules\reviews\Module'], 'reviews' => ['class' => 'common\modules\reviews\Module'],
......
...@@ -51,7 +51,6 @@ abstract class BaseController extends Controller ...@@ -51,7 +51,6 @@ abstract class BaseController extends Controller
public function beforeAction($action) public function beforeAction($action)
{ {
/*if(substr($currentUrl, -1) == '/' && $currentUrl!="/") { /*if(substr($currentUrl, -1) == '/' && $currentUrl!="/") {
$urlWithoutSlash = substr($currentUrl, 0, -1); $urlWithoutSlash = substr($currentUrl, 0, -1);
return $this->redirect($urlWithoutSlash,true,301); return $this->redirect($urlWithoutSlash,true,301);
...@@ -282,16 +281,6 @@ abstract class BaseController extends Controller ...@@ -282,16 +281,6 @@ abstract class BaseController extends Controller
} }
protected function performAjaxValidation($model)
{
if (isset($_POST['ajax']))
{
echo CActiveForm::validate($model);
Yii::$app->end();
}
}
/** /**
* Возвращает модель по атрибуту и удовлетворяющую скоупам, * Возвращает модель по атрибуту и удовлетворяющую скоупам,
* или выбрасывает 404 * или выбрасывает 404
......
<?php
namespace common\components;
use Yii;
use yii\web\Request;
use common\modules\languages\models\Languages;
class LangRequest extends Request
{
private $_lang_url;
public function getLangUrl()
{
if ($this->_lang_url === null)
{
$this->_lang_url = $this->getUrl();
$url_list = explode('/', $this->_lang_url);
$lang_url = isset($url_list[1]) ? $url_list[1] : null;
Languages::setCurrent($lang_url);
if( $lang_url !== null && $lang_url === Languages::getCurrent()->url &&
strpos($this->_lang_url, Languages::getCurrent()->url) === 1 )
{
$this->_lang_url = substr($this->_lang_url, strlen(Languages::getCurrent()->url) + 1);
}
}
return $this->_lang_url;
}
protected function resolvePathInfo()
{
$pathInfo = $this->getLangUrl();
if (($pos = strpos($pathInfo, '?')) !== false)
{
$pathInfo = substr($pathInfo, 0, $pos);
}
$pathInfo = urldecode($pathInfo);
// try to encode in UTF8 if not so
// http://w3.org/International/questions/qa-forms-utf-8.html
if (!preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $pathInfo)
)
{
$pathInfo = utf8_encode($pathInfo);
}
$scriptUrl = $this->getScriptUrl();
$baseUrl = $this->getBaseUrl();
if (strpos($pathInfo, $scriptUrl) === 0)
{
$pathInfo = substr($pathInfo, strlen($scriptUrl));
}
elseif ($baseUrl === '' || strpos($pathInfo, $baseUrl) === 0)
{
$pathInfo = substr($pathInfo, strlen($baseUrl));
}
elseif (isset($_SERVER['PHP_SELF']) && strpos($_SERVER['PHP_SELF'], $scriptUrl) === 0)
{
$pathInfo = substr($_SERVER['PHP_SELF'], strlen($scriptUrl));
}
else
{
throw new InvalidConfigException('Unable to determine the path info of the current request.');
}
if ($pathInfo[0] === '/')
{
$pathInfo = substr($pathInfo, 1);
}
return (string) $pathInfo;
}
}
\ No newline at end of file
<?php <?php
namespace common\components; namespace common\components;
use common\modules\languages\models\Languages;
class UrlManager extends \yii\web\UrlManager { class UrlManager extends \yii\web\UrlManager {
public function parseRequest($request){ public function parseRequest($request){
...@@ -7,11 +10,44 @@ class UrlManager extends \yii\web\UrlManager { ...@@ -7,11 +10,44 @@ class UrlManager extends \yii\web\UrlManager {
$rules = []; $rules = [];
foreach($pages as $page) { foreach($pages as $page) {
//$rules[$page->url] = \yii\helpers\Url::toRoute(['/content/page/view','id' => $page->id]); //$rules[$page->url] = \yii\helpers\Url::toRoute(['/content/page/view','id' => $page->id]);
$rules['<page:('.$page->url.')>'] = \yii\helpers\Url::toRoute(['/content/page/view']); $rules['<page:('.$page->url.')>'] = 'content/page/view';
} }
$this->addRules($rules, false); $this->addRules($rules, false);
//die(print_r($request->getPathInfo())); //die(print_r($request->getPathInfo()));
return parent::parseRequest($request); return parent::parseRequest($request);
} }
public function createUrl($params)
{
if(isset($params['lang_id']))
{
//Если указан идентификатор языка, то делаем попытку найти язык в БД,
//иначе работаем с языком по умолчанию
$lang = Languages::findOne($params['lang_id']);
if($lang === null)
{
$lang = Languages::getDefaultLang();
}
unset($params['lang_id']);
}
else
{
//Если не указан параметр языка, то работаем с текущим языком
$lang = Languages::getCurrent();
}
//Получаем сформированный URL(без префикса идентификатора языка)
$url = parent::createUrl($params);
//Добавляем к URL префикс - буквенный идентификатор языка
if($url == '/')
{
return '/' . $lang->url;
}
else
{
return '/' . $lang->url . $url;
}
}
} }
...@@ -7,9 +7,6 @@ use \common\models\MetaTags; ...@@ -7,9 +7,6 @@ use \common\models\MetaTags;
class MetaTagBehavior extends Behavior class MetaTagBehavior extends Behavior
{ {
public $language = 'ru';
public function events() public function events()
{ {
return [ return [
...@@ -21,13 +18,15 @@ class MetaTagBehavior extends Behavior ...@@ -21,13 +18,15 @@ class MetaTagBehavior extends Behavior
public function Save($event) public function Save($event)
{ {
$attributes = \Yii::$app->request->post('MetaTags'); $meta = \Yii::$app->request->post('MetaTags');
if ($attributes) if ($meta)
{
foreach ($meta as $lang_id => $attributes)
{ {
$meta_tag = MetaTags::find()->where([ $meta_tag = MetaTags::find()->where([
'object_id' => $this->owner->id, 'object_id' => $this->owner->id,
'model_id' => get_class($this->owner), 'model_id' => get_class($this->owner),
'language' => $this->language, 'lang_id' => $lang_id,
])->one(); ])->one();
if (!$meta_tag) if (!$meta_tag)
...@@ -37,48 +36,44 @@ class MetaTagBehavior extends Behavior ...@@ -37,48 +36,44 @@ class MetaTagBehavior extends Behavior
$attributes['object_id'] = $this->owner->id; $attributes['object_id'] = $this->owner->id;
$attributes['model_id'] = get_class($this->owner); $attributes['model_id'] = get_class($this->owner);
$attributes['language'] = $this->language; $attributes['lang_id'] = $lang_id;
$meta_tag->setAttributes( $attributes ); $meta_tag->setAttributes( $attributes );
if(!$meta_tag->save()) die(print_r($meta_tag->errors)); if(!$meta_tag->save()) die(print_r($meta_tag->errors));
} }
}
return true; return true;
} }
public function Insert($event) public function Insert($event)
{ {
$attributes = \Yii::$app->request->post('MetaTags'); $meta = \Yii::$app->request->post('MetaTags');
if ($attributes ) if ($meta)
{
foreach ($meta as $lang_id => $attributes)
{ {
$meta_tag = new MetaTags; $meta_tag = new MetaTags;
$attributes['object_id'] = $this->owner->id; $attributes['object_id'] = $this->owner->id;
$attributes['model_id'] = get_class($this->owner); $attributes['model_id'] = get_class($this->owner);
$attributes['language'] = 'ru'; $attributes['lang_id'] = $lang_id;
$meta_tag->setAttributes( $attributes ); $meta_tag->setAttributes($attributes);
$meta_tag->save(false); $meta_tag->save(false);
} }
}
return true; return true;
} }
public function Delete($event) public function Delete($event)
{ {
MetaTags::deleteAll([
$model = MetaTags::find()
->where([
'object_id' => $this->owner->id, 'object_id' => $this->owner->id,
'model_id' => get_class($this->owner) 'model_id' => get_class($this->owner)
])->one(); ]);
if(!empty($model)) $model->delete();
return true; return true;
} }
} }
...@@ -37,12 +37,11 @@ class MetaTags extends \common\components\ActiveRecordModel ...@@ -37,12 +37,11 @@ class MetaTags extends \common\components\ActiveRecordModel
public function rules() public function rules()
{ {
return [ return [
[['object_id', 'model_id', 'language'], 'required'], [['object_id', 'model_id', 'lang_id'], 'required'],
[['object_id', 'created_at', 'updated_at'], 'integer'], [['object_id', 'created_at', 'updated_at', 'lang_id'], 'integer'],
[['model_id'], 'string', 'max' => 50], [['model_id'], 'string', 'max' => 50],
[['language'], 'string', 'max' => 5],
[['title', 'keywords', 'description'], 'string', 'max' => 300], [['title', 'keywords', 'description'], 'string', 'max' => 300],
[['object_id', 'model_id'], 'unique', 'targetAttribute' => ['object_id', 'model_id'], 'message' => 'The combination of ID объекта and Модель has already been taken.'] [['object_id', 'model_id', 'lang_id'], 'unique', 'targetAttribute' => ['object_id', 'model_id', 'lang_id'], 'message' => 'The combination of ID объекта and Модель has already been taken.']
]; ];
} }
...@@ -55,10 +54,10 @@ class MetaTags extends \common\components\ActiveRecordModel ...@@ -55,10 +54,10 @@ class MetaTags extends \common\components\ActiveRecordModel
'id' => Yii::t('content', 'ID'), 'id' => Yii::t('content', 'ID'),
'object_id' => Yii::t('content', 'ID объекта'), 'object_id' => Yii::t('content', 'ID объекта'),
'model_id' => Yii::t('content', 'Модель'), 'model_id' => Yii::t('content', 'Модель'),
'language' => Yii::t('content', 'Язык'), 'lang_id' => Yii::t('content', 'Язык'),
'title' => /*Yii::t('content', 'Заголовок')*/'Title', 'title' => 'Title',
'keywords' => /*Yii::t('content', 'Ключевые слова')*/'Keywords', 'keywords' => 'Keywords',
'description' => /*Yii::t('content', 'Описание')*/ 'Description', 'description' => 'Description',
'created_at' => Yii::t('content', 'Создано'), 'created_at' => Yii::t('content', 'Создано'),
'updated_at' => Yii::t('content', 'Отредактирован'), 'updated_at' => Yii::t('content', 'Отредактирован'),
]; ];
......
<?php
namespace common\modules\content\components;
use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use common\modules\content\models\CoContentLang;
class CoContentLangBehavior extends Behavior
{
public function events()
{
return [
ActiveRecord::EVENT_AFTER_UPDATE => 'Save',
ActiveRecord::EVENT_AFTER_INSERT => 'Insert',
ActiveRecord::EVENT_AFTER_DELETE => 'Delete',
];
}
public function Save($event)
{
$langs = Yii::$app->request->post('CoContentLang');
if ($langs)
{
foreach ($langs as $lang_id => $attributes)
{
$lang = CoContentLang::find()->where([
'content_id' => $this->owner->id,
'lang_id' => $lang_id,
])->one();
if (!$lang)
{
$lang = new CoContentLang;
}
$attributes['content_id'] = $this->owner->id;
$attributes['lang_id'] = $lang_id;
$lang->setAttributes( $attributes );
if(!$lang->save()) die(print_r($lang->errors));
}
}
return true;
}
public function Insert($event)
{
$langs = Yii::$app->request->post('CoContentLang');
if ($langs)
{
foreach ($langs as $lang_id => $attributes)
{
$meta_tag = new CoContentLang;
$attributes['content_id'] = $this->owner->id;
$attributes['lang_id'] = $lang_id;
$meta_tag->setAttributes($attributes);
$meta_tag->save(false);
}
}
return true;
}
public function Delete($event)
{
CoContentLang::deleteAll([
'content_id' => $this->owner->id
]);
return true;
}
}
...@@ -2,17 +2,20 @@ ...@@ -2,17 +2,20 @@
namespace common\modules\content\controllers; namespace common\modules\content\controllers;
use common\models\MetaTags;
use Yii; use Yii;
use common\modules\content\models\CoContent;
use common\modules\content\models\CoContentData;
use common\modules\content\models\SearchCoContent;
use common\modules\content\models\SearchCoContentData;
use common\components\AdminController; use common\components\AdminController;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\web\UploadedFile; use yii\web\UploadedFile;
use common\modules\content\models\CoContent;
use common\modules\content\models\CoContentLang;
use common\modules\languages\models\Languages;
use common\modules\content\models\SearchCoContent;
use common\modules\content\models\SearchCoContentData;
use common\models\MetaTags;
/** /**
* ContentAdminController implements the CRUD actions for CoContent model. * ContentAdminController implements the CRUD actions for CoContent model.
*/ */
...@@ -25,9 +28,6 @@ class ContentAdminController extends AdminController ...@@ -25,9 +28,6 @@ class ContentAdminController extends AdminController
'Update' => 'Редактирование контента', 'Update' => 'Редактирование контента',
'Delete' => 'Удаление контента', 'Delete' => 'Удаление контента',
'View' => 'Просмотр контента', 'View' => 'Просмотр контента',
'Createcontent' => 'Добавление данных контента',
'Updatecontent' => 'Редактирование данных контента',
'Deletecontent' => 'Удаление данных контента',
'Copypage' => '', 'Copypage' => '',
]; ];
} }
...@@ -87,15 +87,9 @@ class ContentAdminController extends AdminController ...@@ -87,15 +87,9 @@ class ContentAdminController extends AdminController
*/ */
public function actionView($id) public function actionView($id)
{ {
$searchModel = new SearchCoContentData();
$dataProvider = $searchModel->search(['content_id'=>$id]);
return $this->render('view', [ return $this->render('view', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $this->findModel($id), 'model' => $this->findModel($id),
]); ]);
} }
/** /**
...@@ -105,12 +99,63 @@ class ContentAdminController extends AdminController ...@@ -105,12 +99,63 @@ class ContentAdminController extends AdminController
*/ */
public function actionCreate() public function actionCreate()
{ {
return $this->actionUpdate(); $model = new CoContent;
$langs = [];
$meta = [];
foreach (Languages::find()->all() as $lang)
{
$lng = new CoContentLang;
$lng->lang_id = $lang->id;
$langs[$lang->id] = $lng;
$mt = new \common\models\MetaTags;
$mt->lang_id = $lang->id;
$meta[$lang->id] = $mt;
} }
public function actionCreatecontent($content_id) Yii::$app->controller->page_title = 'Добавить страницу';
Yii::$app->controller->breadcrumbs = [
['Управление контентом' => \yii\helpers\Url::toRoute('manage')],
'Добавить страницу',
];
if (Yii::$app->request->isPost)
{ {
return $this->actionUpdatecontent($content_id); $transaction = Yii::$app->db->beginTransaction();
try
{
$model->attributes = Yii::$app->request->post('CoContent');
$model->image = UploadedFile::getInstance($model, 'image');
if($model->validate())
{
if($model->image)
{
$model->upload();
$model->image = null;
}
$model->save();
$transaction->commit();
return $this->redirect(['manage']);
}
}
catch (\Exception $e)
{
$transaction->rollBack();
throw $e;
}
}
return $this->render('create', [
'model' => $model,
'meta' => $meta,
'langs' => $langs
]);
} }
/** /**
...@@ -119,36 +164,52 @@ class ContentAdminController extends AdminController ...@@ -119,36 +164,52 @@ class ContentAdminController extends AdminController
* @param integer $id * @param integer $id
* @return mixed * @return mixed
*/ */
public function actionUpdate($id = null) public function actionUpdate($id)
{ {
if(empty($id)) { $model = $this->findModel($id);
$model = new CoContent(); $langs = [];
$meta = [];
$meta = new \common\models\MetaTags; foreach (Languages::find()->all() as $lang)
$meta->language = 'ru'; {
$mt = $model->getMetaTags($lang->id)->one();
\yii::$app->controller->page_title = 'Добавить страницу'; if(!$mt)
{
$mt = new \common\models\MetaTags;
$mt->lang_id = $lang->id;
}
\yii::$app->controller->breadcrumbs = [ $meta[$lang->id] = $mt;
['Управление контентом' => \yii\helpers\Url::toRoute('manage')],
'Добавить страницу', $lng = $model->getContent($lang->id)->one();
];
if(!$lng)
{
$lng = new CoContentLang;
$lng->lang_id = $lang->id;
} }
else {
$model = $this->findModel($id);
$meta = $model->metaTags;
\yii::$app->controller->page_title = 'Редактировать страницу';
\yii::$app->controller->breadcrumbs = [ $langs[$lang->id] = $lng;
}
Yii::$app->controller->page_title = 'Редактировать страницу';
Yii::$app->controller->breadcrumbs = [
['Управление контентом' => \yii\helpers\Url::toRoute('manage')], ['Управление контентом' => \yii\helpers\Url::toRoute('manage')],
$model->name, $model->name,
]; ];
}
$model->load(Yii::$app->request->post()); if (Yii::$app->request->isPost)
{
$transaction = Yii::$app->db->beginTransaction();
try
{
$model->attributes = Yii::$app->request->post('CoContent');
$model->image = UploadedFile::getInstance($model, 'image'); $model->image = UploadedFile::getInstance($model, 'image');
if (Yii::$app->request->isPost && $model->validate()) if($model->validate())
{ {
if($model->image) if($model->image)
{ {
...@@ -163,50 +224,23 @@ class ContentAdminController extends AdminController ...@@ -163,50 +224,23 @@ class ContentAdminController extends AdminController
$model->save(); $model->save();
$transaction->commit();
return $this->redirect(['manage']); return $this->redirect(['manage']);
} }
$form = new \common\components\BaseForm('/common/modules/content/forms/ContentForm', $model);
return $this->render('update', [
'model' => $model,
'meta' => $meta,
'form' => $form->out,
]);
} }
catch (\Exception $e)
public function actionUpdatecontent($content_id, $id = null)
{ {
if(empty($id)) { $transaction->rollBack();
$model = new CoContentData(); throw $e;
$model->content_id = $content_id;
\yii::$app->controller->page_title = 'Добавить данные контента';
\yii::$app->controller->breadcrumbs = [
['Управление данными контента' => \yii\helpers\Url::toRoute(['view', 'id'=>$content_id])],
'Добавить данные контента',
];
} }
else {
$model = $this->findModelData($id);
\yii::$app->controller->page_title = 'Редактировать данные контента <small>' . $model->title . '</small>';
\yii::$app->controller->breadcrumbs = [
['Управление данными контента' => \yii\helpers\Url::toRoute('manage')],
'Редактировать данные контента ' . $model->title,
];
} }
if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->render('update', [
return $this->redirect(['view', 'id' => $model->content_id]);
} else {
$form = new \common\components\BaseForm('/common/modules/content/forms/ContentDataForm', $model);
return $this->render('updatecontent', [
'model' => $model, 'model' => $model,
'form' => $form->out, 'meta' => $meta,
'langs' => $langs,
]); ]);
} }
}
/** /**
* Deletes an existing CoContent model. * Deletes an existing CoContent model.
...@@ -236,13 +270,4 @@ class ContentAdminController extends AdminController ...@@ -236,13 +270,4 @@ class ContentAdminController extends AdminController
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');
} }
} }
protected function findModelData($id)
{
if (($model = CoContentData::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
} }
<?php
use yii\helpers\ArrayHelper;
return [
'activeForm'=>[
'id' => 'controller-form',
],
'elements' => [
'content_id' => [
'type' => 'dropdownlist',
'items' => ArrayHelper::map(\common\modules\content\models\CoContent::find()->all(), 'id', 'name'),
'class' => 'form-control',
],
'title' => ['type' => 'text', 'class' => 'form-control'],
'short_description' => ['type' => 'textarea', 'class' => 'form-control'],
'description' => ['type' => 'textarea', 'class' => 'form-control'],
],
'buttons' => [
'submit' => ['type' => 'submit', 'value' => 'Cохранить']
]
];
...@@ -37,7 +37,7 @@ class CoBlocks extends \common\components\ActiveRecordModel ...@@ -37,7 +37,7 @@ class CoBlocks extends \common\components\ActiveRecordModel
return [ return [
[['title', 'name', 'text'], 'required'], [['title', 'name', 'text'], 'required'],
[['text'], 'string'], [['text'], 'string'],
[['date_create', 'category_id'], 'safe'], [['category_id'], 'safe'],
[['lang'], 'string', 'max' => 2], [['lang'], 'string', 'max' => 2],
[['module'], 'string', 'max' => 100], [['module'], 'string', 'max' => 100],
[['title'], 'string', 'max' => 250], [['title'], 'string', 'max' => 250],
...@@ -58,11 +58,17 @@ class CoBlocks extends \common\components\ActiveRecordModel ...@@ -58,11 +58,17 @@ class CoBlocks extends \common\components\ActiveRecordModel
'title' => Yii::t('content', 'Заголовок'), 'title' => Yii::t('content', 'Заголовок'),
'name' => Yii::t('content', 'Наименование виджета'), 'name' => Yii::t('content', 'Наименование виджета'),
'text' => Yii::t('content', 'Текст'), 'text' => Yii::t('content', 'Текст'),
'date_create' => Yii::t('content', 'Добавлено'),
'category_id' => 'Категория', 'category_id' => 'Категория',
]; ];
} }
public function getContent($lang_id = null)
{
$lang_id = ($lang_id === null)? Languages::getCurrent()->id: $lang_id;
return $this->hasOne(CoBlocksLang::className(), ['block_id' => 'id'])->where('lang_id = :lang_id', [':lang_id' => $lang_id]);
}
/** /**
* @block string name block * @block string name block
* @return HTML string * @return HTML string
...@@ -74,7 +80,7 @@ class CoBlocks extends \common\components\ActiveRecordModel ...@@ -74,7 +80,7 @@ class CoBlocks extends \common\components\ActiveRecordModel
public static function printStaticBlock($block, $addPath = false) public static function printStaticBlock($block, $addPath = false)
{ {
return \yii::$app->getView()->render( '@app/views/layouts/block/' . $block . '.php'); return Yii::$app->getView()->render( '@app/views/layouts/block/' . $block . '.php');
} }
public function afterFind() { public function afterFind() {
......
...@@ -5,30 +5,26 @@ namespace common\modules\content\models; ...@@ -5,30 +5,26 @@ namespace common\modules\content\models;
use Yii; use Yii;
/** /**
* This is the model class for table "co_content_data". * This is the model class for table "co_blocks_lang".
* *
* @property integer $id * @property integer $id
* @property integer $content_id * @property integer $block_id
* @property integer $lang_id
* @property string $name
* @property string $title * @property string $title
* @property string $short_description * @property string $text
* @property string $description
* @property integer $created_at
* @property integer $updated_at
* *
* @property CoContent $content * @property CoBlocks $block
* @property Languages $lang
*/ */
class CoContentData extends \common\components\ActiveRecordModel class CoBlocksLang extends \common\components\ActiveRecordModel
{ {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public static function tableName() public static function tableName()
{ {
return 'co_content_data'; return 'co_blocks_lang';
}
public function name() {
return 'Содержание контента';
} }
/** /**
...@@ -37,10 +33,13 @@ class CoContentData extends \common\components\ActiveRecordModel ...@@ -37,10 +33,13 @@ class CoContentData extends \common\components\ActiveRecordModel
public function rules() public function rules()
{ {
return [ return [
[['content_id', 'created_at', 'updated_at'], 'integer'], [['block_id', 'lang_id', 'name', 'title'], 'required'],
[['description'], 'string'], [['block_id', 'lang_id'], 'integer'],
[['text'], 'string'],
[['name'], 'string', 'max' => 50],
[['title'], 'string', 'max' => 250], [['title'], 'string', 'max' => 250],
[['short_description'], 'string', 'max' => 255] [['block_id'], 'exist', 'skipOnError' => true, 'targetClass' => CoBlocks::className(), 'targetAttribute' => ['block_id' => 'id']],
[['lang_id'], 'exist', 'skipOnError' => true, 'targetClass' => Languages::className(), 'targetAttribute' => ['lang_id' => 'id']],
]; ];
} }
...@@ -50,21 +49,28 @@ class CoContentData extends \common\components\ActiveRecordModel ...@@ -50,21 +49,28 @@ class CoContentData extends \common\components\ActiveRecordModel
public function attributeLabels() public function attributeLabels()
{ {
return [ return [
'id' => Yii::t('content', 'ID'), 'id' => 'ID',
'content_id' => Yii::t('content', 'Content ID'), 'block_id' => 'Block ID',
'title' => Yii::t('content', 'Title'), 'lang_id' => 'Lang ID',
'short_description' => Yii::t('content', 'Short Description'), 'name' => 'Name',
'description' => Yii::t('content', 'Description'), 'title' => 'Title',
'created_at' => Yii::t('content', 'Created At'), 'text' => 'Text',
'updated_at' => Yii::t('content', 'Updated At'),
]; ];
} }
/** /**
* @return \yii\db\ActiveQuery * @return \yii\db\ActiveQuery
*/ */
public function getContent() public function getBlock()
{
return $this->hasOne(CoBlocks::className(), ['id' => 'block_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getLang()
{ {
return $this->hasOne(CoContent::className(), ['id' => 'content_id']); return $this->hasOne(Languages::className(), ['id' => 'lang_id']);
} }
} }
...@@ -5,7 +5,7 @@ namespace common\modules\content\models; ...@@ -5,7 +5,7 @@ namespace common\modules\content\models;
use Yii; use Yii;
use common\modules\content\models\CoBlocks; use common\modules\content\models\CoBlocks;
use common\models\MetaTags; use common\models\MetaTags;
use yii\base\Controller;
/** /**
* This is the model class for table "co_content". * This is the model class for table "co_content".
* *
...@@ -43,6 +43,9 @@ class CoContent extends \common\components\ActiveRecordModel ...@@ -43,6 +43,9 @@ class CoContent extends \common\components\ActiveRecordModel
return [ return [
'meta' => [ 'meta' => [
'class' => 'common\components\activeRecordBehaviors\MetaTagBehavior', 'class' => 'common\components\activeRecordBehaviors\MetaTagBehavior',
],
'langs' => [
'class' => 'common\modules\content\components\CoContentLangBehavior',
] ]
]; ];
} }
...@@ -60,11 +63,11 @@ class CoContent extends \common\components\ActiveRecordModel ...@@ -60,11 +63,11 @@ class CoContent extends \common\components\ActiveRecordModel
public function rules() public function rules()
{ {
return [ return [
[['active', 'created_at', 'updated_at'], 'integer'], [['active'], 'integer'],
[['image'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif'], [['image'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif'],
[['url', 'name', 'text'], 'required'], [['url'], 'required'],
[['url', 'name', 'title'], 'string', 'max' => 250], [['url'], 'string', 'max' => 250],
[['category_id', 'text'], 'safe'] [['category_id'], 'safe']
]; ];
} }
...@@ -90,15 +93,18 @@ class CoContent extends \common\components\ActiveRecordModel ...@@ -90,15 +93,18 @@ class CoContent extends \common\components\ActiveRecordModel
/** /**
* @return \yii\db\ActiveQuery * @return \yii\db\ActiveQuery
*/ */
public function getMetaTags() { public function getMetaTags($lang_id = null)
return $this->hasOne(MetaTags::className(), [ {
'object_id' => 'id', $query = $this->hasOne(MetaTags::className(), ['object_id' => 'id'])->where(['model_id' => get_class($this)]);
/* */
])->where([
'model_id' => get_class($this),
'language' => 'ru',]);
if($lang_id)
{
$query->andWhere(['lang_id' => $lang_id]);
} }
return $query;
}
/** /**
* @return \yii\db\ActiveQuery * @return \yii\db\ActiveQuery
*/ */
...@@ -107,40 +113,16 @@ class CoContent extends \common\components\ActiveRecordModel ...@@ -107,40 +113,16 @@ class CoContent extends \common\components\ActiveRecordModel
return $this->hasOne(CoCategory::className(), ['id' => 'category_id']); return $this->hasOne(CoCategory::className(), ['id' => 'category_id']);
} }
/** public function getContent($lang_id = null)
* @return html {
*/ $lang_id = ($lang_id === null)? Languages::getCurrent()->id: $lang_id;
public function getContent() {
$content = $this->text; return $this->hasOne(CoContentLang::className(), ['content_id' => 'id'])->where('lang_id = :lang_id', [':lang_id' => $lang_id]);
$content = \common\components\AppManager::prepareWidget($content); }
$blocks = CoBlocks::find()->all();
$arrWhatReplace = []; public function getLangs()
$arrReplace = []; {
$arrWhatReplaceNext = []; return $this->hasMany(CoContentLang::className(), ['content_id' => 'id']);
$arrReplaceNext = [];
foreach($blocks as $block) {
$arrWhatReplace[] = '{' . $block->name . '}';
$arrReplace[] = $block->text;
$arrWhatReplaceNext[] = '[' . $block->name . ']';
$arrReplaceNext[] = $block->text;
}
$arrWhatReplaceNext[] = '[about-reviews]';
$arrReplaceNext[] = \common\modules\content\models\CoBlocks::printStaticBlock('about-reviews', true);
$arrWhatReplaceNext[] = '[content-phone]';
$arrReplaceNext[] = \common\models\Settings::getValue('content-phone');
$arrWhatReplaceNext[] = '[cases]';
$arrReplaceNext[] = \common\modules\content\models\CoBlocks::printStaticBlock('cases', true);
$arrWhatReplaceNext[] = '[projects]';
$arrReplaceNext[] = \common\modules\content\models\CoBlocks::printStaticBlock('projects', true);
$arrWhatReplaceNext[] = '[case-subscribe]';
$arrReplaceNext[] = \common\modules\content\models\CoBlocks::printStaticBlock('case-subscribe', true);
$arrWhatReplaceNext[] = '[footer]';
$arrReplaceNext[] = \Yii::$app->getView()->render('@app/views/layouts/footer');
$arrWhatReplaceNext[] = '[footer-index]';
$arrReplaceNext[] = \Yii::$app->getView()->render('@app/views/layouts/footer-index');
return str_replace($arrWhatReplaceNext, $arrReplaceNext,str_replace($arrWhatReplace, $arrReplace, $content));
} }
public function beforeSave($insert) { public function beforeSave($insert) {
......
<?php
namespace common\modules\content\models;
use Yii;
use common\modules\content\models\CoContent;
use common\modules\languages\models\Languages;
/**
* This is the model class for table "co_content_lang".
*
* @property integer $id
* @property integer $content_id
* @property integer $lang_id
* @property string $name
* @property string $title
* @property string $text
*
* @property CoContent $content
* @property Languages $lang
*/
class CoContentLang extends \common\components\ActiveRecordModel
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'co_content_lang';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['content_id', 'lang_id', 'name', 'title'], 'required'],
[['content_id', 'lang_id'], 'integer'],
[['text'], 'string'],
[['name', 'title'], 'string', 'max' => 250],
[['content_id'], 'exist', 'skipOnError' => true, 'targetClass' => CoContent::className(), 'targetAttribute' => ['content_id' => 'id']],
[['lang_id'], 'exist', 'skipOnError' => true, 'targetClass' => Languages::className(), 'targetAttribute' => ['lang_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
];
}
/**
* @inheritdoc
*/
public function name()
{
return 'Языковой контент';
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('content', 'ID'),
'name' => Yii::t('content', 'Name'),
'image' => 'Превью',
'title' => Yii::t('content', 'Title'),
'text' => Yii::t('content', 'Content'),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getLang()
{
return $this->hasOne(Languages::className(), ['id' => 'lang_id']);
}
/**
* @return html
*/
public function getContent()
{
$content = $this->text;
$content = \common\components\AppManager::prepareWidget($content);
$blocks = CoBlocks::find()->all();
$arrWhatReplace = [];
$arrReplace = [];
$arrWhatReplaceNext = [];
$arrReplaceNext = [];
foreach($blocks as $block) {
$arrWhatReplace[] = '{' . $block->name . '}';
$arrReplace[] = $block->text;
$arrWhatReplaceNext[] = '[' . $block->name . ']';
$arrReplaceNext[] = $block->text;
}
$arrWhatReplaceNext[] = '[about-reviews]';
$arrReplaceNext[] = \common\modules\content\models\CoBlocks::printStaticBlock('about-reviews', true);
$arrWhatReplaceNext[] = '[content-phone]';
$arrReplaceNext[] = \common\models\Settings::getValue('content-phone');
$arrWhatReplaceNext[] = '[cases]';
$arrReplaceNext[] = \common\modules\content\models\CoBlocks::printStaticBlock('cases', true);
$arrWhatReplaceNext[] = '[projects]';
$arrReplaceNext[] = \common\modules\content\models\CoBlocks::printStaticBlock('projects', true);
$arrWhatReplaceNext[] = '[case-subscribe]';
$arrReplaceNext[] = \common\modules\content\models\CoBlocks::printStaticBlock('case-subscribe', true);
$arrWhatReplaceNext[] = '[footer]';
$arrReplaceNext[] = \Yii::$app->getView()->render('@app/views/layouts/footer');
$arrWhatReplaceNext[] = '[footer-index]';
$arrReplaceNext[] = \Yii::$app->getView()->render('@app/views/layouts/footer-index');
return str_replace($arrWhatReplaceNext, $arrReplaceNext,str_replace($arrWhatReplace, $arrReplace, $content));
}
}
...@@ -19,7 +19,7 @@ class SearchCoBlocks extends CoBlocks ...@@ -19,7 +19,7 @@ class SearchCoBlocks extends CoBlocks
{ {
return [ return [
[['id'], 'integer'], [['id'], 'integer'],
[['lang', 'title', 'name', 'text', 'date_create', 'category_id'], 'safe'], [['lang', 'title', 'name', 'text', 'category_id'], 'safe'],
]; ];
} }
...@@ -57,7 +57,6 @@ class SearchCoBlocks extends CoBlocks ...@@ -57,7 +57,6 @@ class SearchCoBlocks extends CoBlocks
$query->andFilterWhere([ $query->andFilterWhere([
'id' => $this->id, 'id' => $this->id,
'date_create' => $this->date_create,
'category_id' => $this->category_id, 'category_id' => $this->category_id,
]); ]);
......
...@@ -2,32 +2,122 @@ ...@@ -2,32 +2,122 @@
use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use common\modules\content\models\CoContent;
use common\modules\content\widgets\MetaTagsWidget;
/* @var $this yii\web\View */ /* @var $this yii\web\View */
/* @var $model common\modules\content\models\CoContent */ /* @var $model common\modules\content\models\CoContent */
/* @var $form yii\widgets\ActiveForm */ /* @var $form yii\widgets\ActiveForm */
$this->registerJsFile('/plugins/switchery/switchery.min.js', ['position' => \yii\web\View::POS_HEAD ]);
$this->registerCssFile('/plugins/switchery/switchery.min.css', ['position' => \yii\web\View::POS_HEAD ]);
$this->registerJsFile('/js/form-slider-switcher.demo.min.js', ['position' => \yii\web\View::POS_HEAD ]);
$this->registerJsFile('/plugins/tinymce/js/tinymce/tinymce.min.js', ['position' => \yii\web\View::POS_END ]);
$js = <<<JS
FormSliderSwitcher.init();
tinymce.init({
selector: "textarea",theme: "modern",
language: "ru_RU",
custom_elements: "emstart,emend,header,main,span",
extended_valid_elements: "span[id|name|class|style],i[id|name|class|style],ul[id|name|class|style],li[id|name|class|style]",
height: '350px',
menubar: "edit insert view format table tools",
plugins: [
"advlist autolink link image code lists charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking",
"table contextmenu directionality emoticons paste textcolor responsivefilemanager"
],
toolbar1: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | styleselect",
toolbar2: "| responsivefilemanager | link unlink anchor | image media | forecolor backcolor | print preview code ",
image_advtab: true ,
forced_root_block : false,
external_filemanager_path:"/filemanager/",
filemanager_title:"Responsive Filemanager" ,
external_plugins: { "filemanager" : "/filemanager/plugin.min.js"}
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY, 'switcheryLoad');
$blocks = \common\modules\content\models\CoBlocks::find()->all();
?> ?>
<div class="co-content-form"> <div class="co-content-form">
<?php $form = ActiveForm::begin(); ?> <?php $form = ActiveForm::begin([
'options' => [
'enctype' => 'multipart/form-data'
]
]); ?>
<?= $form->field($model, 'category_id')->dropDownList(ArrayHelper::map(\common\modules\content\models\CoCategory::find()->all(), 'id', 'name'), [
'prompt' => 'Без привязки к категории',
'class' => 'form-control',
])->hint('Для того что бы было проще сортировать данную страницу в общем списке вы можете привязать ее к определенной категории. Список категории настраивается ' . Html::a('тут',['/content/category-admin/manage']) . '.') ?>
<?= $form->field($model, 'url')->textInput(['maxlength' => 250])->hint('Для создания ЧПУ («Человеку Понятный Урл») укажите латинскими буквами путь, например, razdel/podrazdel/nazvanie_stranici.html') ?>
<?= $form->field($model, 'category_id')->textInput() ?> <?= $form->field($model, 'active', [
'template' => '{input}<a href="#" class="btn btn-xs btn-success m-l-5 disabled">Страница скрыта от пользователя / Страница видна пользователю</a>'
])->checkbox([
'data-theme' => 'self',
'data-render' => 'switchery',
'data-classname' => 'switchery',
'label' => ' '
], false); ?>
<?= $form->field($model, 'url')->textInput(['maxlength' => 250]) ?> <?php if($model->preview)
{
echo Html::img(\Yii::$app->params['frontUrl'] . CoContent::PHOTO_FOLDER . $model->preview);
} ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 250]) ?> <?= $form->field($model, 'image')->fileInput() ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => 250]) ?> <ul class="nav nav-pills">
<?php $c = 0; foreach ($langs as $i => $content) : $c++; ?>
<li class="<?=($c==1?'active':'')?>"><a href="#lang-<?=$content->lang->url?>" data-toggle="tab"><?=$content->lang->name?></a></li>
<?php endforeach; ?>
</ul>
<?= $form->field($model, 'active')->textInput() ?> <?php
$block_hint = '';
if(count($blocks))
{
$block_hint .= "<ul>\n";
foreach($blocks as $block) {
$block_hint .= "<li>{{$block->name}} {$block->title}</li>\n";
}
<?= $form->field($model, 'created_at')->textInput() ?> $block_hint .= "</ul>\n";
}
?>
<?= $form->field($model, 'updated_at')->textInput() ?> <div class="tab-content">
<?php $c = 0; foreach ($langs as $content) : $c++;
$lang_id = $content->lang->id; ?>
<div class="tab-pane fade <?=($c==1?'active in':'')?>" id="lang-<?=$content->lang->url;?>">
<?= $form->field($content, '['.$lang_id.']name')->textInput(['maxlength' => 250])->hint('Название страницы не будет отображаться пользователям сайта и служит исключительно для служебного пользования в Панель управления.') ?>
<?= $form->field($content, '['.$lang_id.']title')->textInput(['maxlength' => 250])->hint('Заголовок страницы виден пользователю сайта и как правило оформляется в тег &lt;h1&gt;. Если дизайном страницы не предусмотрен вывод заголовка, то он не будет выводиться даже если был введен в данное поле.') ?>
<?= $form->field($content, '['.$lang_id.']text')->textArea()->hint($block_hint) ?>
<?= MetaTagsWidget::widget([
'model' => $meta[$lang_id],
'form' => $form,
])?>
</div>
<?php endforeach; ?>
</div>
<div class="form-group"> <div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('content', 'Create') : Yii::t('content', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> <?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
</div> </div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
......
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model common\modules\content\models\SearchCoContent */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="co-content-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'category_id') ?>
<?= $form->field($model, 'url') ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'title') ?>
<?php // echo $form->field($model, 'active') ?>
<?php // echo $form->field($model, 'created_at') ?>
<?php // echo $form->field($model, 'updated_at') ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('content', 'Search'), ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton(Yii::t('content', 'Reset'), ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
...@@ -12,10 +12,10 @@ $this->params['breadcrumbs'][] = $this->title; ...@@ -12,10 +12,10 @@ $this->params['breadcrumbs'][] = $this->title;
?> ?>
<div class="co-content-create"> <div class="co-content-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [ <?= $this->render('_form', [
'model' => $model, 'model' => $model,
'meta' => $meta,
'langs' => $langs
]) ?> ]) ?>
</div> </div>
<?php <?php
echo $form;
\ No newline at end of file use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\modules\content\models\CoContent */
$this->title = Yii::t('content', 'Update Co Content');
$this->params['breadcrumbs'][] = ['label' => Yii::t('content', 'Co Contents'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="co-content-update">
<?= $this->render('_form', [
'model' => $model,
'meta' => $meta,
'langs' => $langs,
]) ?>
</div>
\ No newline at end of file
<?php
namespace common\modules\content\widgets;
use Yii;
use yii\helpers\Html;
class MetaTagsWidget extends \yii\bootstrap\Widget
{
public $form;
public $model;
public function run()
{
return $this->render('meta-tags', [
'model' => $this->model,
'form' => $this->form,
]);
}
}
<?php
use yii\helpers\Html;
echo Html::tag('h4', 'Meta-теги страницы:');
echo $form->field($model, '['.$model->lang_id.']title')->textInput();
echo $form->field($model, '['.$model->lang_id.']description')->textInput();
echo $form->field($model, '['.$model->lang_id.']keywords')->textInput();
\ No newline at end of file
...@@ -20,6 +20,7 @@ class LanguageAdminController extends AdminController ...@@ -20,6 +20,7 @@ class LanguageAdminController extends AdminController
'Create' => 'Добавить язык', 'Create' => 'Добавить язык',
'Update' => 'Редактированть язык', 'Update' => 'Редактированть язык',
'View' => 'Просмотр языка', 'View' => 'Просмотр языка',
'Delete' => 'Удаление языка',
]; ];
} }
...@@ -78,7 +79,7 @@ class LanguageAdminController extends AdminController ...@@ -78,7 +79,7 @@ class LanguageAdminController extends AdminController
$model = new Languages(); $model = new Languages();
if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]); return $this->redirect(['manage']);
} else { } else {
return $this->render('create', [ return $this->render('create', [
'model' => $model, 'model' => $model,
...@@ -97,7 +98,7 @@ class LanguageAdminController extends AdminController ...@@ -97,7 +98,7 @@ class LanguageAdminController extends AdminController
$model = $this->findModel($id); $model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]); return $this->redirect(['manage']);
} else { } else {
return $this->render('update', [ return $this->render('update', [
'model' => $model, 'model' => $model,
...@@ -115,7 +116,7 @@ class LanguageAdminController extends AdminController ...@@ -115,7 +116,7 @@ class LanguageAdminController extends AdminController
{ {
$this->findModel($id)->delete(); $this->findModel($id)->delete();
return $this->redirect(['index']); return $this->redirect(['manage']);
} }
/** /**
......
...@@ -3,17 +3,30 @@ ...@@ -3,17 +3,30 @@
namespace common\modules\languages\models; namespace common\modules\languages\models;
use Yii; use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
/** /**
* This is the model class for table "languages". * This is the model class for table "languages".
* *
* @property integer $id * @property integer $id
* @property string $code * @property string $url
* @property string $codeFull * @property string $local
* @property string $name * @property string $name
*/ */
class Languages extends \common\components\ActiveRecordModel class Languages extends \common\components\ActiveRecordModel
{ {
//Переменная, для хранения текущего объекта языка
static $current = null;
const DEFAULT_TRUE = 1;
const DEFAULT_FALSE = 0;
public static $defaults_title = [
self::DEFAULT_TRUE => 'Да',
self::DEFAULT_FALSE => 'Нет',
];
/** /**
* @inheritdoc * @inheritdoc
*/ */
...@@ -33,11 +46,12 @@ class Languages extends \common\components\ActiveRecordModel ...@@ -33,11 +46,12 @@ class Languages extends \common\components\ActiveRecordModel
public function rules() public function rules()
{ {
return [ return [
[['code', 'codeFull', 'name'], 'required'], [['url', 'local', 'name'], 'required'],
[['code'], 'string', 'max' => 2], [['default'], 'safe'],
[['codeFull'], 'string', 'max' => 5], [['url'], 'string', 'max' => 2],
[['local'], 'string', 'max' => 5],
[['name'], 'string', 'max' => 15], [['name'], 'string', 'max' => 15],
[['name'], 'unique'] [['url'], 'unique']
]; ];
} }
...@@ -47,10 +61,90 @@ class Languages extends \common\components\ActiveRecordModel ...@@ -47,10 +61,90 @@ class Languages extends \common\components\ActiveRecordModel
public function attributeLabels() public function attributeLabels()
{ {
return [ return [
'id' => Yii::t('languages', 'ID'), 'id' => 'ID',
'code' => Yii::t('languages', 'Language Code'), 'url' => 'Идентификатор для отображения в URL',
'codeFull' => Yii::t('languages', 'Locale Code'), 'local' => 'Язык пользователя (локаль)',
'name' => Yii::t('languages', 'Name'), 'name' => 'Название',
'default' => 'По умолчанию',
];
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => null,
'updatedAtAttribute' => null,
'value' => new Expression('NOW()'),
],
]; ];
} }
public function beforeSave($insert)
{
if (parent::beforeSave($insert))
{
if($this->default)
{
static::updateAll(['default' => self::DEFAULT_FALSE], ['default' => self::DEFAULT_TRUE]);
}
return true;
}
else
{
return false;
}
}
//Получение текущего объекта языка
static function getCurrent()
{
if(self::$current === null)
{
self::$current = self::getDefaultLang();
}
return self::$current;
}
//Установка текущего объекта языка и локаль пользователя
static function setCurrent($url = null)
{
$language = self::getLangByUrl($url);
self::$current = ($language === null) ? self::getDefaultLang() : $language;
Yii::$app->language = self::$current->local;
}
//Получения объекта языка по умолчанию
static function getDefaultLang()
{
return static::find()->where('`default` = :default', [':default' => self::DEFAULT_TRUE])->one();
}
//Получения объекта языка по буквенному идентификатору
static function getLangByUrl($url = null)
{
if ($url === null)
{
return null;
}
else
{
$language = static::find()->where('url = :url', [':url' => $url])->one();
if ($language === null)
{
return null;
}
else
{
return $language;
}
}
}
} }
...@@ -18,8 +18,8 @@ class SearchLanguages extends Languages ...@@ -18,8 +18,8 @@ class SearchLanguages extends Languages
public function rules() public function rules()
{ {
return [ return [
[['id'], 'integer'], [['id', 'default'], 'integer'],
[['code', 'codeFull', 'name'], 'safe'], [['url', 'local', 'name', 'default'], 'safe'],
]; ];
} }
...@@ -57,10 +57,11 @@ class SearchLanguages extends Languages ...@@ -57,10 +57,11 @@ class SearchLanguages extends Languages
$query->andFilterWhere([ $query->andFilterWhere([
'id' => $this->id, 'id' => $this->id,
'default' => $this->default,
]); ]);
$query->andFilterWhere(['like', 'code', $this->code]) $query->andFilterWhere(['like', 'url', $this->url])
->andFilterWhere(['like', 'codeFull', $this->codeFull]) ->andFilterWhere(['like', 'local', $this->local])
->andFilterWhere(['like', 'name', $this->name]); ->andFilterWhere(['like', 'name', $this->name]);
return $dataProvider; return $dataProvider;
......
...@@ -12,14 +12,16 @@ use yii\widgets\ActiveForm; ...@@ -12,14 +12,16 @@ use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin(); ?> <?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'code')->textInput(['maxlength' => 2]) ?> <?= $form->field($model, 'url')->textInput(['maxlength' => 2]) ?>
<?= $form->field($model, 'codeFull')->textInput(['maxlength' => 5]) ?> <?= $form->field($model, 'local')->textInput(['maxlength' => 5]) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 15]) ?> <?= $form->field($model, 'name')->textInput(['maxlength' => 15]) ?>
<?= $form->field($model, 'default')->checkbox() ?>
<div class="form-group"> <div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('content', 'Create') : Yii::t('content', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> <?= Html::submitButton('Сохранить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div> </div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
......
...@@ -12,8 +12,6 @@ $this->params['breadcrumbs'][] = $this->title; ...@@ -12,8 +12,6 @@ $this->params['breadcrumbs'][] = $this->title;
?> ?>
<div class="languages-create"> <div class="languages-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [ <?= $this->render('_form', [
'model' => $model, 'model' => $model,
]) ?> ]) ?>
......
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
use yii\helpers\Html; use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use common\modules\languages\models\Languages;
/* @var $this yii\web\View */ /* @var $this yii\web\View */
/* @var $searchModel common\modules\languages\models\SearchLanguages */ /* @var $searchModel common\modules\languages\models\SearchLanguages */
/* @var $dataProvider yii\data\ActiveDataProvider */ /* @var $dataProvider yii\data\ActiveDataProvider */
...@@ -12,18 +14,26 @@ use yii\grid\GridView; ...@@ -12,18 +14,26 @@ use yii\grid\GridView;
<?php // echo $this->render('_search', ['model' => $searchModel]); ?> <?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p> <p>
<?= Html::a(Yii::t('languages', 'Create Languages'), ['create'], ['class' => 'btn btn-success']) ?> <?= Html::a('Добавить', ['create'], ['class' => 'btn btn-success']) ?>
</p> </p>
<?= \common\components\zii\AdminGrid::widget([ <?= \common\components\zii\AdminGrid::widget([
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'filterModel' => $searchModel, 'filterModel' => $searchModel,
'columns' => [ 'columns' => [
['class' => 'yii\grid\SerialColumn'], // ['class' => 'yii\grid\SerialColumn'],
'code', 'url',
'codeFull', 'local',
'name', 'name',
[
'attribute' => 'default',
'filter' => Html::dropDownList($searchModel->formName() . '[default]', $searchModel->default, Languages::$defaults_title, ['class' => 'form-control', 'prompt' => '']),
'value' => function($model)
{
return Languages::$defaults_title[$model->default];
}
],
[ [
'class' => 'common\components\ColorActionColumn', 'class' => 'common\components\ColorActionColumn',
......
...@@ -14,8 +14,6 @@ $this->params['breadcrumbs'][] = Yii::t('content', 'Update'); ...@@ -14,8 +14,6 @@ $this->params['breadcrumbs'][] = Yii::t('content', 'Update');
?> ?>
<div class="languages-update"> <div class="languages-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [ <?= $this->render('_form', [
'model' => $model, 'model' => $model,
]) ?> ]) ?>
......
...@@ -29,9 +29,10 @@ $this->params['breadcrumbs'][] = $this->title; ...@@ -29,9 +29,10 @@ $this->params['breadcrumbs'][] = $this->title;
'model' => $model, 'model' => $model,
'attributes' => [ 'attributes' => [
'id', 'id',
'code', 'url',
'codeFull', 'local',
'name', 'name',
'default',
], ],
]) ?> ]) ?>
......
<?php
namespace common\modules\languages\widgets;
use common\modules\languages\models\Languages as Model;
class Languages extends \yii\bootstrap\Widget
{
public function init(){}
public function run()
{
return $this->render('languages', [
'current' => Model::getCurrent(),
'langs' => Model::find()->where('id != :current_id', [':current_id' => Model::getCurrent()->id])->all(),
'count' => Model::find()->count(),
]);
}
}
\ No newline at end of file
<?php
use yii\helpers\Html;
?>
<?php if($count > 2) : ?>
<div class="lang_check">
<?= Html::a('<i class="icon-arrowDown"></i>' . $current->name, '#', ['class' => 'd_menu']) ?>
<?php foreach ($langs as $i => $lang): ?>
<?= Html::a('<i class="icon-arrowRight"></i>' . $lang->name, '/' . $lang->url . Yii::$app->getRequest()->getLangUrl(), ['class' => 'd_menu_hide']) ?>
<?php endforeach;?>
</div>
<?php else : ?>
<nav class="top_nav clearfix">
<ul>
<?php foreach ($langs as $lang):?>
<li><?= Html::a($lang->name, '/' . $lang->url . Yii::$app->getRequest()->getLangUrl()) ?></li>
<?php endforeach;?>
</ul>
</nav>
<?php endif; ?>
\ No newline at end of file
<?php
use yii\db\Migration;
class m160202_053232_fix_language_table extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->update('languages', ['codeFull' => 'en-EN'], ['code' => 'en']);
$this->update('languages', ['codeFull' => 'ru-RU'], ['code' => 'ru']);
$this->renameColumn('languages', 'codeFull', 'local');
$this->renameColumn('languages', 'code', 'url');
$this->addColumn('languages', 'default', 'smallint(6) NOT NULL DEFAULT 0');
$this->update('languages', ['default' => 1], ['url' => 'ru']);
}
public function safeDown()
{
$this->renameColumn('languages', 'local', 'codeFull');
$this->renameColumn('languages', 'url', 'code');
$this->update('languages', ['codeFull' => 'eng'], ['code' => 'en']);
$this->update('languages', ['codeFull' => 'rus'], ['code' => 'ru']);
$this->dropColumn('languages', 'default');
}
}
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160202_104337_upgrade_content extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
Yii::$app->db->createCommand('ALTER TABLE `co_blocks` ENGINE = InnoDB;')->execute();
Yii::$app->db->createCommand('ALTER TABLE `co_blocks` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;')->execute();
$this->createTable(
'co_content_lang',
[
'id' => Schema::TYPE_PK,
'content_id' => Schema::TYPE_INTEGER.'(11) NOT NULL',
'lang_id' => Schema::TYPE_INTEGER.'(11) NOT NULL',
'name' => Schema::TYPE_STRING.'(250) NOT NULL',
'title' => Schema::TYPE_STRING.'(250) NOT NULL',
'text' => 'longtext DEFAULT NULL',
]
);
$this->addForeignKey(
'fk_content_lang_lang_id_languages_id',
'co_content_lang', 'lang_id',
'languages', 'id'
);
$this->addForeignKey(
'fk_content_lang_content_id_content_id',
'co_content_lang', 'content_id',
'co_content', 'id'
);
$this->createTable(
'co_blocks_lang',
[
'id' => Schema::TYPE_PK,
'block_id' => Schema::TYPE_INTEGER.'(11) NOT NULL',
'lang_id' => Schema::TYPE_INTEGER.'(11) NOT NULL',
'name' => Schema::TYPE_STRING.'(50) NOT NULL',
'title' => Schema::TYPE_STRING.'(250) NOT NULL',
'text' => 'longtext DEFAULT NULL',
]
);
$this->addForeignKey(
'fk_blocks_lang_lang_id_languages_id',
'co_blocks_lang', 'lang_id',
'languages', 'id'
);
$this->addForeignKey(
'fk_blocks_lang_blocks_id_blocks_id',
'co_blocks_lang', 'block_id',
'co_blocks', 'id'
);
$this->dropColumn('co_blocks', 'date_create');
$this->dropTable('co_content_data');
}
public function safeDown()
{
$this->dropForeignKey('fk_content_lang_lang_id_languages_id', 'co_content_lang');
$this->dropForeignKey('fk_content_lang_content_id_content_id', 'co_content_lang');
$this->dropForeignKey('fk_blocks_lang_lang_id_languages_id', 'co_blocks_lang');
$this->dropForeignKey('fk_blocks_lang_blocks_id_blocks_id', 'co_blocks_lang');
$this->dropTable('co_content_lang');
$this->dropTable('co_blocks_lang');
$this->addColumn('co_blocks', 'date_create', Schema::TYPE_TIMESTAMP . ' NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
$this->createTable(
'co_content_data',
[
'id' => Schema::TYPE_PK,
]
);
}
}
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160202_163727_fix_metatags extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->renameColumn('meta_tags', 'language', 'lang_id');
$this->alterColumn('meta_tags', 'lang_id', Schema::TYPE_INTEGER.'(11) DEFAULT NULL');
$this->truncateTable('meta_tags');
$this->addForeignKey(
'fk_meta_tags_lang_id_languages_id',
'meta_tags', 'lang_id',
'languages', 'id'
);
}
public function safeDown()
{
$this->dropForeignKey('fk_meta_tags_lang_id_languages_id', 'meta_tags');
$this->renameColumn('meta_tags', 'lang_id', 'language');
$this->alterColumn('meta_tags', 'language', Schema::TYPE_STRING.'(5) NOT NULL');
}
}
<?php
use yii\db\Migration;
class m160202_173116_fix_index_meta_tags extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->dropIndex('object_id', 'meta_tags');
$this->createIndex('unique_object_model_lang', 'meta_tags', ['object_id', 'lang_id', 'model_id'], true);
}
public function safeDown()
{
$this->dropIndex('unique_object_model_lang', 'meta_tags');
$this->createIndex('object_id', 'meta_tags', ['object_id', 'model_id'], true);
}
}
...@@ -61,6 +61,9 @@ return [ ...@@ -61,6 +61,9 @@ return [
], ],
], ],
'components' => [ 'components' => [
'request' => [
'class' => 'common\components\LangRequest'
],
'cache' => [ 'cache' => [
'class' => 'yii\caching\FileCache', 'class' => 'yii\caching\FileCache',
], ],
...@@ -98,7 +101,11 @@ return [ ...@@ -98,7 +101,11 @@ return [
'translations' => [ 'translations' => [
'*' => [ '*' => [
'class' => 'yii\i18n\PhpMessageSource', 'class' => 'yii\i18n\PhpMessageSource',
'sourceLanguage' => 'ru-RU', 'basePath' => '@frontend/messages',
'sourceLanguage' => 'en',
'fileMap' => [
//'main' => 'main.php',
],
], ],
], ],
], ],
...@@ -146,14 +153,10 @@ return [ ...@@ -146,14 +153,10 @@ return [
'showScriptName' => false, 'showScriptName' => false,
'enableStrictParsing' => true, 'enableStrictParsing' => true,
'rules' => [ 'rules' => [
//TEMP
'keys' => 'site/keys',
'contacts' => 'site/contacts', 'contacts' => 'site/contacts',
['pattern' => 'sitemap', 'route' => 'sitemap/default/index', 'suffix' => '.xml'], ['pattern' => 'sitemap', 'route' => 'sitemap/default/index', 'suffix' => '.xml'],
'source/<_u>/<_f>/<file>' => '@backend/web/<_u>/<_f>/<file>',
'' => 'content/page/view', '' => 'content/page/view',
'<page:(/)>' => 'content/page/view', '<page:(/)>' => 'content/page/view',
'reviews' => 'reviews/review/index', 'reviews' => 'reviews/review/index',
'faq/view/all' => 'faq/faq/all', 'faq/view/all' => 'faq/faq/all',
......
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use common\modules\languages\widgets\Languages;
?>
<nav class="menu"> <nav class="menu">
<div class="toggle_block"><a href="#" class="toggle-mnu"><span></span></a></div> <div class="toggle_block"><a href="#" class="toggle-mnu"><span></span></a></div>
<div class="phone_menu"><?=\common\models\Settings::getValue('content-phone')?></div> <div class="phone_menu"><?=\common\models\Settings::getValue('content-phone')?></div>
<ul> <ul>
<li><a href="/about" class="link">О компании</a></li> <li><?=Html::a('О компании', ['/about']);?></li>
<li><a href="/case" class="link">Кейсы</a></li> <li><?=Html::a('Кейсы', ['/case']);?></li>
<li><a href="#" class="link">Блог</a></li> <li><?=Html::a('Блог', ['/#']);?></li>
<?php /*<li><a href="/school" class="link">Школа аналитики</a></li>*/ ?> <!-- <li><?=Html::a('Школа аналитики', ['/school']);?></li> -->
<li><a href="/contacts" class="link">Контакты</a></li> <li><?=Html::a('Контакты', ['/contacts']);?></li>
</ul> </ul>
</nav> </nav>
...@@ -14,26 +21,21 @@ ...@@ -14,26 +21,21 @@
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<div class="col-md-2 col-xs-3 col-sm-12"> <div class="col-md-2 col-xs-3 col-sm-12">
<a href="/" class="logo"> <a href="<?=Url::to(['/'])?>" class="logo">
<img src="/images/logo.png" height="34" width="125" alt=""> <img src="/images/logo.png" height="34" width="125" alt="">
</a> </a>
</div> </div>
<div class="col-md-7 col-xs-6 col-sm-12"> <div class="col-md-7 col-xs-6 col-sm-12">
<nav class="top_nav clearfix"> <nav class="top_nav clearfix">
<ul> <ul>
<li><a href="/about">О компании</a></li> <li><?=Html::a('О компании', ['/about']);?></li>
<li><a href="/case">Кейсы</a></li> <li><?=Html::a('Кейсы', ['/case']);?></li>
<li><a href="#">Блог</a></li> <li><?=Html::a('Блог', ['/#']);?></li>
<?php /*<li><a href="/school">Школа аналитики</a></li>*/ ?> <!-- <li><?=Html::a('Школа аналитики', ['/school']);?></li> -->
<li><a href="/contacts">Контакты</a></li> <li><?=Html::a('Контакты', ['/contacts']);?></li>
<li><a href="#">ENG</a></li>
<!-- <li><a href="#">RUS</a></li> -->
</ul> </ul>
</nav> </nav>
<!-- <div class="lang_check"> <?= Languages::widget();?>
<a href="#" class="d_menu"><i class="icon-arrowDown"></i>ENG</a>
<a href="#" class="d_menu_hide"><i class="icon-arrowRight"></i>RUS</a>
</div> -->
</div> </div>
<div class="col-md-3 col-xs-3 col-sm-12"> <div class="col-md-3 col-xs-3 col-sm-12">
<span class="top_phone"><?=\common\models\Settings::getValue('content-phone')?></span> <span class="top_phone"><?=\common\models\Settings::getValue('content-phone')?></span>
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment