Как удалять посты в блоге?

Какой механизм удаления постов в Yii2? В проекте блог вынесен как отдельный модуль. Если удалять в админ.панели в backend пост, то debage не фиксирует ошибок, приходится закрывать страницу через диспетчер задач, т.к. браузер зависает, и посты удаляются только в базе.

BlogController (блога в vendor)


<?php


namespace illyas\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 \illyas\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 = \illyas\blog\models\Blog::find()->with('tags')->andWhere(['id'=>$id])->one()) !== null) {

            return $model;

        } else {

            throw new NotFoundHttpException('The requested page does not exist.');

        }

    }

}

Если закомментировать ‘beforeDelete’ в Blog.php- зависает.

Все перепробовал, но вот что интересно: В GoogleChrome - зависает, а в Microsoft Edge - пост удаляется как надо!

В чем причина здесь?

В Yii никакого блога нет. Проблема в вашем коде.

Это понятно, что в коде-где же ещё может быть?

В Yii2 есть возможность сделать блог как отдельный модуль в папке vendor, что я и пытаюсь реализовать.

В Мicrosoft Edge и Mozilla посты удаляются, а в GoogleChrome - он как-бы ‘зависает’.

Сейчас Blog.php выглядит так:


<?php


namespace medeyacom\blog\models;


use common\components\behaviors\StatusBehavior;

use Yii;

use yii\behaviors\TimestampBehavior;

use yii\db\ActiveRecord;

use yii\db\Expression;

use yii\helpers\ArrayHelper;

use yii\helpers\Url;

use yii\web\UploadedFile;

use common\models\User;

use common\models\ImageManager;


/**

 * This is the model class for table "blog".

 *

 * @property integer $id

 * @property string $title

 * @property string $text

 * @property string $image

 * @property string $url

 * @property string $date_create

 * @property string $date_update

 * @property integer $status_id

 * @property integer $sort

 */

class Blog extends ActiveRecord

{

    const STATUS_LIST = ['off','on'];

    const IMAGES_SIZE = [

        ['50','50'],

        ['800',null],

    ];

    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],

            [['file'], 'image'],

            [['tags_array','date_create','date_update'], 'safe'],

        ];

    }


    /**

     * @inheritdoc

     */

    public function attributeLabels()

    {

        return [

            'id' => 'ID',

            'title' => 'Заголовок',

            'text' => 'Текст',

            'url' => 'ЧПУ',

            'status_id' => 'Статус',

            'sort' => 'Сортировка',

            'tags_array' => 'Тэги',

            'image' => 'Картинка',

            'file' => 'Картинка',

            'tagsAsString' => 'Тэги',

            'author.username' => 'Имя Автора',

            'author.email' => 'Почта Автора',

            'date_update' => 'Обновлено',

            'date_create' => 'Создано',

        ];

    }




    public function getAuthor(){

        return $this->hasOne(User::className(),['id'=>'user_id']);

    }

    public function getImages()

    {

        return $this->hasMany(ImageManager::className(), ['item_id' => 'id'])->andWhere(['class'=>self::tableName()])->orderBy('sort');

    }

    public function getImagesLinks()

    {

        return ArrayHelper::getColumn($this->images,'imageUrl');

    }

    public function getImagesLinksData()

    {

        return ArrayHelper::toArray($this->images,[

                ImageManager::className() => [

                    'caption'=>'name',

                    'key'=>'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/ss.jpg';

        }

        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(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]);

    }




     public function beforeDelete()

       {

              if (parent::beforeDelete()) {

                $dir = Yii::getAlias('@images').'/blog/';

             if($this->image != '')

             if (!empty($this->image)) 


             if($this->image && file_exists($dir.$this->image)){

              unlink($dir.$this->image);

                }

          /* if(file_exists($dir.$this->image)){

                    unlink($dir.$this->image);

                }*/

            foreach (self::IMAGES_SIZE as $size){

                    $size_dir = $size[0].'x';

            if($size[1] !== null)

                        $size_dir .= $size[1];

           /* if(file_exists($dir.$this->image)){

                        unlink($dir.$size_dir.'/'.$this->image);

                    }*/

                }

           BlogTag::deleteAll(['blog_id'=>$this->id]);

           return true;

                 } else {

            return false;

              }

        }

}

 

          

7432

au.jpg

7433

auau.jpg

Дебажьте. По этому куску кода не понятно.