<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log','debug'],
'controllerNamespace' => 'frontend\controllers',
'modules'=>[
'debug'=>[
'class'=>'yii2\debug\Module'
],
],
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'blog/<url>'=>'blog/one',
'blog'=>'blog/index'
],
],
],
'params' => $params,
];
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Url;
use yii\web\UploadedFile;
use vova07\imperavi\Widget;
use kartik\widgets\FileInput;
/* @var $this yii\web\View */
/* @var $searchModel medeyacom\blog\models\BlogSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Blogs';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="blog-index">
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Blog', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{view} {update} {delete} {check}',
'buttons' => [
'check' => function($url,$model,$key) {
return Html::a('<i class="fa fa-check" aria-hidden="true"></i>',$url);
}
],
'visibleButtons' => [
'check' => function ($model, $key, $index){
return $model->status_id === 1;
}
]
],
'id',
'title',
['attribute'=>'url','format'=>'raw'],
/*'headerOptions'=>['class'=>'dgfdhh']], */
/* ['attribute'=>'status_id','filter'=>['off','on'],'value'=>function($model){
$status = 'off';
if($model->status_id ==1) {
$status = 'on';
}
return $status;
}], */
['attribute'=>'status_id','filter'=>\medeyacom\blog\models\Blog::STATUS_LIST,'value'=>'statusName'],
/* return $model->statusName;
}],*/
'sort',
'smallImage:image',
'date_create:datetime',
'date_update:datetime',
['attribute'=>'tags','value'=>'tagsAsString'],
],
]); ?>
<?php Pjax::end(); ?></div>
<?php
namespace medeyacom\blog\controllers;
use Yii;
use common\models\ImageManager;
use medeyacom\blog\models\BlogSearch;
use yii\web\Controller;
use yii\web\MethodNotAllowedHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* BlogController implements the CRUD actions for Blog model.
*/
class BlogController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
'delete-image' => ['POST'],
'sort-image' => ['POST'],
],
],
];
}
/**
* Lists all Blog models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new BlogSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Blog model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Blog model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new \medeyacom\blog\models\Blog();
$model->sort = 50;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Blog model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Blog model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
public function actionDeleteImage()
{
if(($model = ImageManager::findOne(Yii::$app->request->post('key'))) and $model->delete()){
return true;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
public function actionSortImage($id)
{
if(Yii::$app->request->isAjax){
$post = Yii::$app->request->post('sort');
if($post['oldIndex'] > $post['newIndex']){
$param = ['and',['>=','sort',$post['newIndex']],['<','sort',$post['oldIndex']]];
$counter = 1;
}else{
$param = ['and',['<=','sort',$post['newIndex']],['>','sort',$post['oldIndex']]];
$counter = -1;
}
ImageManager::updateAllCounters(['sort' => $counter], [
'and',['class'=>'blog','item_id'=>$id],$param
]);
ImageManager::updateAll(['sort' => $post['newIndex']], [
'id' => $post['stack'][$post['newIndex']]['key']
]);
return true;
}
throw new MethodNotAllowedHttpException();
}
/**
* Finds the Blog model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Blog the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = \medeyacom\blog\models\Blog::find()->with('tags')->andWhere(['id'=>$id])->one()) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use vova07\imperavi\Widget;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;
use kartik\widgets\FileInput;
/* @var $this yii\web\View */
/* @var $model common\models\Blog */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="blog-form">
<?php
$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']
]); ?>
<div class="row">
<?= $form->field($model, 'file', ['options'=>['class'=>'col-xs-6']])->widget(\kartik\file\FileInput::classname(), [
'options'=> ['accept'=> 'image/*'],
'pluginOptions' => [
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'browseClass' => 'btn btn-primary btn-block',
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
'browseLabel' => 'Выбрать фото'
],
]);?>
<?= $form->field($model, 'title', ['options'=>['class'=>'col-xs-6']])->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'url', ['options'=>['class'=>'col-xs-6']])->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'status_id',['options'=>['class'=>'col-xs-6']])->dropDownList(\common\models\Blog::STATUS_LIST) ?>
<?= $form->field($model, 'sort',['options'=>['class'=>'col-xs-6']])->textInput() ?>
<?= $form->field($model, 'tags_array',['options'=>['class'=>'col-xs-6']])->widget(\kartik\select2\Select2::classname(), [
'data' =>\yii\helpers\ArrayHelper::map(\common\models\Tag::find()->all(),'id','name'),
'language' => 'ru',
'options' => ['placeholder' => 'Выбрать tag...','multiple'=> true],
'pluginOptions' => [
'allowClear' => true,
'tags'=>true,
'maximumInputLength'=> 10
],
]); ?>
</div>
<?= $form->field ($model, 'text')->widget(Widget::classname(), [
'settings' => [
'lang' => 'ru',
'minHeight' => 200,
'formatting' =>['p','blockquots', 'h2','h1'],
'imageUpload' => \yii\helpers\Url::to(['/site/save-redactor-img','sub'=>'blog']),
'plugins' => [
'clips',
'fullscreen'
]
]
])?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
namespace common\models;
use common\components\behaviors\StatusBehavior;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\web\UploadedFile;
use yii\helpers\Url;
use kartik\widgets\FileInput;
use kartik\widgets\ActiveForm;
use app\models\UploadForm;
use yii\imagine\Image;
use yii\helpers\FileHelper;
use yii\grid\GridView;
/**
* This is the model class for table "blog".
*
* @property integer $id
* @property string $title
* @property string $image
* @property string $text
* @property string $date_create
* @property string $date_update
* @property string $url
* @property integer $status_id
* @property integer $sort
* @package common\models
*/
class Blog extends ActiveRecord {
const STATUS_LIST = ['off','on'];
/* public $tags_array;*/
public $tags_array;
public $file;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'blog';
}
public function behaviors()
{
return [
'timestampBehavior'=>[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'date_create',
'updatedAtAttribute' => 'date_update',
'value' => new Expression('NOW()'),
],
'statusBehavior'=> [
'class' => StatusBehavior::className(),
'statusList'=> self::STATUS_LIST,
]
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'url'], 'required'],
[['text'], 'string'],
[['url'], 'unique'],
[['status_id', 'sort'], 'integer'],
[['sort'], 'integer','max'=>99, 'min'=>1],
[['title', 'url'], 'string', 'max' => 150],
[['image'], 'string', 'max' => 100],
[['image'], 'file', 'extensions'=>'jpg, gif, png'],
[['tags_array','date_create','date_update'],'safe'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Заголовок',
'text' => 'Текст',
'url' => 'ЧПУ',
'status_id' => 'Статус',
'sort' => 'Сортировка',
'date_update' => 'Обновлено',
'date_create' => 'Создано',
'tags_array' => 'Тэги',
'tagsAsString' => 'Тэги',
'image' => 'Картинка',
'file' => 'Картинка',
'author.username'=>'Имя Автора',
'author.email'=>'Почта Автора',
];
}
public function getAuthor () {
return $this->hasOne (User::className(),['id'=>'user_id']);
}
public function getBlogTag () {
return $this->hasMany(BlogTag::className(),['blog_id'=>'id']);
}
public function getTags()
{
return $this->hasMany(Tag::className(),['id'=>'tag_id'])->via('blogTag');
}
public function getTagsAsString()
{
$arr = \yii\helpers\ArrayHelper::map($this->tags,'id','name');
return implode (', ',$arr);
}
public function getSmallImage()
{
if($this->image){
$path = str_replace('admin.','',Url::home(true)).'uploads/images/blog/50x50/'.$this->image;
}else{
$path = str_replace('admin.','', Url::home(true)).'uploads/images/pic.svg';
}
return $path;
}
public function afterFind()
{
parent::afterFind();
$this->tags_array = $this->tags;
}
public function beforeSave ($insert)
{
if ($file = UploadedFile::getInstance($this,'file')) {
$dir = Yii::getAlias('@images').'/blog/';
if (!is_dir($dir . $this->image)) {
if (file_exists($dir.$this->image)){
unlink($dir.$this->image);
}
if (file_exists($dir.'50x50/'.$this->image)) {
unlink($dir.'50x50/'.$this->image);
}
if (file_exists($dir. '800x/'.$this->image)) {
unlink($dir.'800x/'.$this->image);
}
}
$this->image = strtotime ('now').'_'.Yii::$app->getSecurity()->generateRandomString(6) .'.'. $file->extension;
$file ->saveAs($dir.$this->image);
$imag = Yii::$app->image->load($dir.$this->image);
$imag ->background ('#fff',0);
$imag ->resize ('50','50', Yii\image\drivers\Image::INVERSE);
$imag ->crop ('50','50');
$imag ->save($dir.'50x50/'.$this->image, 90);
$imag = Yii::$app->image->load($dir.$this->image);
$imag->background('#fff',0);
$imag->resize('800',null, Yii\image\drivers\Image::INVERSE);
$imag->save($dir.'800x/'.$this->image, 90);
}
return parent::beforeSave($insert);
}
public function afterSave ($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
$arr = \yii\helpers\ArrayHelper::map($this->tags,'id','id');
foreach ($this->tags_array as $one) {
if(!in_array($one,$arr)){
$model = new BlogTag();
$model->blog_id = $this->id;
$model->tag_id = $one;
$model->save();
}
if(isset($arr[$one])) {
unset ($arr[$one]);
}
}
BlogTag::deleteAll(['tag_id'=>$arr]);
}
}
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use vova07\imperavi\Widget;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;
use kartik\widgets\FileInput;
/* @var $this yii\web\View */
/* @var $model common\models\Blog */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="blog-form">
<?php
$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']
]); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'text')->widget(Widget::className(), [
'settings' => [
'lang' => 'ru',
'minHeight' => 200,
#'formatting' =>['p','blockquots', 'h2','h1'],
'imageUpload' => \yii\helpers\Url::to(['/site/save-redactor-img','sub'=>'blog']),
'plugins' => [
'clips',
'fullscreen'
]
]
])?>
<?= $form->field ($model, 'file')->widget(\kartik\file\FileInput::classname(), [
'options'=> ['accept'=> 'image/*'],
'pluginOptions' => [
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'browseClass' => 'btn btn-primary btn-block',
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
'browseLabel' => 'Выбрать фото'
],
]);?>
<?= $form->field($model, 'url')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'status_id')->dropDownList(\common\models\Blog::STATUS_LIST) ?>
<?= $form->field($model, 'sort')->textInput() ?>
<?= $form->field($model, 'tags_array')->widget(\kartik\select2\Select2::classname(), [
'data' =>\yii\helpers\ArrayHelper::map(\common\models\Tag::find()->all(),'id','name'),
'language' => 'ru',
'options' => ['placeholder' => 'Выбрать tag...','multiple'=> true],
'pluginOptions' => [
'allowClear' => true,
'tags'=>true,
'maximumInputLength'=> 10
],
]); ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use kartik\widgets\ActiveForm; // or yii\widgets\ActiveForm
use kartik\widgets\FileInput;
use yii\grid\GridView;
// or 'use kartik\file\FileInput' if you have only installed
// yii2-widget-fileinput in isolation
/* @var $this yii\web\View */
/* @var $model common\models\Blog */
$this->title = $model->title;
$this->params['breadcrumbs'][] = ['label' => 'Blogs', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="blog-view">
<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',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'title',
'text:text',
'url:url',
'status_id',
'sort',
'author.username',
'author.email',
'tagsAsString',
'smallImage:image',
],
]) ?>
</div>
BlogController (fronted)
В backend BlogController нет, только SiteController,
BlogController (D:\sites\site\yii2\vendor\medeyacom\yii2-blog\controllers)