• Почему не удаляются посты с картинками в блоге?

    @Maila Автор вопроса
    Максим Тимофеев: actionDelete- нет, но на fronted картинки и не отображаются в постах вообще.

    BlogController (fronted)

    <?php
    
    namespace frontend\controllers;
    
    
    use medeyacom\blog\models\Blog;
    use Yii;
    use yii\data\ActiveDataProvider;
    use yii\web\Controller;
    use yii\web\NotFoundHttpException;
    
    
    
    /**
     * Blog controller
     */
    class BlogController extends Controller
    {
        /**
         * Displays homepage.
         *
         * @return mixed
         */
        public function actionIndex()
        {
            #$blogs = Blog::find()->where(['status_id'=>1])->orderBy(['id' => SORT_DESC])->all();
    
           $blogs = Blog::find()->with('author')->andWhere(['status_id'=>1])->orderBy('sort');
            $dataProvider = new ActiveDataProvider([
                'query' => $blogs,
                'pagination' => [
                'pageSize' => 10,
                ],
            ]);
            #$blogs = Blog::find()->where(['status_id'=>1])->orderBy(['id' => SORT_ASC])->all();
            return $this->render('all',['dataProvider'=>$dataProvider]);
        }
    
           public function actionOne($url)
        {  
           if($blog = Blog::find()->andWhere(['url'=>$url])->one()) {
                return $this->render('one',['blog'=>$blog]);
          }
           throw new NotFoundHttpException('ой,нет такого блога');
        }
    }

    В backend BlogController нет, только SiteController,

    BlogController (D:\sites\site\yii2\vendor\medeyacom\yii2-blog\controllers)

    <?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.');
            }
        }
    }
  • Почему не удаляются посты с картинками в блоге?

    @Maila Автор вопроса
    пробовала добавить эту строчку: 'blog/delete-image'=>'blog/delete-image' в main.php (fronted), а также вариант -закомментировать другие строки рядом, но не удаляются. acdf4e1a625f4d3d96bf25095f4588a2.jpg может, это правило нужно добавить не в main.php (config/fronted) а в main.php (yii2/common/config)? только там нет правил url вообще. также пробовала добавить это правило в yii2/backend/config/main.php - и тоже не сработало
  • Почему не удаляются посты с картинками в блоге?

    @Maila Автор вопроса
    Максим Тимофеев: в urlmanager есть строчка 'blog'=>'blog/index' - но это вроде бы и должно так быть? или нет?

    main.php (D:\sites\site\yii2\frontend\config)
    <?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,
    ];
  • Почему не удаляются посты с картинками в блоге?

    @Maila Автор вопроса
    Максим Тимофеев: а что в blog/blog/index? не совсем понятно..

    blog/index.php

    <?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>
  • Почему не удаляются посты с картинками в блоге?

    @Maila Автор вопроса
    вот в Blog.Controller вроде бы все в порядке

    <?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.');
            }
        }
    }


    а в UrlManager что смотреть, он длинный?

    код UrlManager https://codepad.remoteinterview.io/TTDNHWUHWS
  • Перенос блога модуля в yii2- как решить ошибку?

    @Maila Автор вопроса
    Андрей Токмаков: разобралась вроде в чем проблема, но вот с тэгами так и непонятно..При нажатии на 'Тэги' в админ.панеле выдаёт 404 по адресу admin.site.com/tag
    309fc5335d934abe94e8a8e1918504e8.jpg
  • Yii2 - почему не загружаются картинки через widget-fileinput?

    @Maila Автор вопроса
    Максим Тимофеев: 86bcc2303e6d4c4a94a8e038f885efa3.jpgf8f51906ad0c4257ae497551a8163d2c.jpg46a34946e6f84962953d41a97cc9fa1b.jpg

    form.php
    <?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>
  • Yii2 - почему не загружаются картинки через widget-fileinput?

    @Maila Автор вопроса
    Максим Тимофеев: ну а зачем тогда Svg именно? И каким образом можно реализовать множественную загрузку картинок и отображение на сайте с этим виджетом? У вас в видео вы тоже применяете этот формат, добавив в css запись .grid-view td > img {max-width: 50px; } - но у меня размер не уменьшается почему-то. Если в Blog.php в функцию getSmallImage добавить в загрузку файл с форматом jpg, то картинка загружается, но на fronted нигде этого не видно. Картинки, по-прежнему, нормально отображаются на сайте в постах только с первым виджетом. Или это так должно быть? afba4e1be28e482c9bd5016eb4bfe756.jpg
  • Yii2 - почему не загружаются картинки через widget-fileinput?

    @Maila Автор вопроса
    Там,наоборот, одна кавычка оказалась лишней т.к я добавила ещё одну проверку с "unlink" вначале. Но проблема не решилась- загрузка происходит, но картинка сохраняется только в блоге в админке, где 'SmallImage', а на фронтеде её не видно и в нормальном разрешении только в 'jpg' если загружать, а в 'svg' -в большом размере и выдаёт ошибку: 3158f390f9b84933b8117dff19bda2d2.jpg
  • Yii2 - почему не загружаются картинки через widget-fileinput?

    @Maila Автор вопроса
    Здравствуйте! В Blog.php выходит какая-то ошибка - если добавить ещё одну кавычку на 185 строке, то страница открывается. Но, мне кажется, её там быть не должно? Виджет загрузки есть, картинка загружается, но после 'update' она не сохраняется -вместо этого огромная картинка svg, хотя в css добавлено:
    .grid-view td > img {max-width: 50px; } 2d2da6342f684e42b821d76d02a3df28.jpg Blog.php

    <?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]);
      }
    
    
     }


    form.php

    <?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>


    view.php
    <?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>
  • Yii2 - почему не создаются новые тэги?

    @Maila Автор вопроса
    но первый код именно из вашего проекта-что там не так? почему сейчас нельзя создать новый тег и сохранить?
  • Yii2 advanced - почему не сохраняются тэги?

    @Maila Автор вопроса
    Максим Тимофеев: Все, нашлась ошибка! В названии свойств без знака доллара нужно указывать.
  • Yii2 advanced - почему не сохраняются тэги?

    @Maila Автор вопроса
    а как проверить это, что afterSave не срабатывает? cdc2014c4376404ba39ecb3953d8d8a3.jpg может быть, в этом ошибка? Failed to set unsafe attribute 'tags_array' in 'common\models\Blog'.
  • Ошибка установки виджета Select2 через Composer -как исправить?

    @Maila Автор вопроса
    Максим Тимофеев: вообщем, разобралась в чем проблема) вместо: "katrik" нужно было "kartik"- в GitBash ещё нельзя просто скопировать, а консоль OpenServer не работает.
  • Ошибка установки виджета Select2 через Composer -как исправить?

    @Maila Автор вопроса
    a что нужно? dev? может быть, дело в 22 строке- "dmstr/yii2-adminlte-asset": "2.*"
    - здесь не хватает чего то? когда пробую устанавливать выдает такую ошибку 642959be676941ccbd1614f3c3704f9a.jpg
  • Сортировка постов в блоге Yii2 advanced -почему не меняется очерёдность?

    @Maila Автор вопроса
    Максим Тимофеев: у Вас и есть один вариант, в моем случае это выглядело как на скрине 1 c8d65eb7b6624124a44d8a99a16d999a.jpg 2 вариант (файл Error2)- это мой, как у меня работает сейчас 766397f9a55f498ebca30d75c4ac28a6.jpg
  • Сортировка постов в блоге Yii2 advanced -почему не меняется очерёдность?

    @Maila Автор вопроса
    Максим Тимофеев: вопрос в том, что при выводе страницы с ошибкой в 1-м вашем варианте эта запись в поле: "ой, нет такого блога" - не появляется, только страница. В BlogController я указываю: use yii\web\NotFoundHttpException;