I
I
Illya_s2017-08-12 20:44:15
Yii
Illya_s, 2017-08-12 20:44:15

How to delete blog posts?

What is the post deletion mechanism in Yii2? In the project, the blog is rendered as a separate module. If you delete a post on a local site in the backend, then debage does not fix errors, you have to close the page through the task manager, because the browser freezes, and posts are deleted only in the database.
Tried to add such method to Blog.Controller - doesn't work.

public function actionDelete($id=NULL)
{
    if ($id === NULL)
    {
        Yii::$app->session->setFlash('PostDeletedError');
        Yii::$app->getResponse()->redirect(array('site/index'));
    }
 
    $post = Post::find($id);
 
 
    if ($post === NULL)
    {
        Yii::$app->session->setFlash('PostDeletedError');
        Yii::$app->getResponse()->redirect(array('site/index'));
    }
 
    $post->delete();
 
    Yii::$app->session->setFlash('PostDeleted');
    Yii::$app->getResponse()->redirect(array('site/index'));
}

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

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2017-08-12
@webinar

posts are deleted only in the database

Where else should they go?
Here yii has nothing to do with it.
if you do public function actionDelete($id)
Then yii and so it will throw an error, so the first condition is superfluous, I'm talking about
if ($id === NULL)
    {
        Yii::$app->session->setFlash('PostDeletedError');
        Yii::$app->getResponse()->redirect(array('site/index'));
    }

And in general, you screwed up a lot of superfluous things, the standard crud through gii makes a normal action, you even brought it in the code, all that remains is to add flash:
public function actionDelete($id){
    if (($post = Post::findOne($id)) and $post->delete())
    {
         Yii::$app->session->setFlash('PostDeleted');
    }else{
         Yii::$app->session->setFlash('PostDeleted');
   }
   return $this->redirect(['site/index']);
}

I
Illya_s, 2017-08-13
@Illya_s

This code is not working

public function actionDelete($id){
    if (($post = Post::findOne($id)) and $post->delete())
    {
         Yii::$app->session->setFlash('PostDeleted');
    }else{
         Yii::$app->session->setFlash('PostDeleted');
   }
   return $this->redirect(['site/index']);
}

Let me explain: if you go to MySQL manager in 'blog' - 'data' and 'delete the selected row', then the post will be deleted.
Should be removed from the site.
If you try to delete a post on the blog page " admin.site.com/blog " or at: " admin.site.com/blog/blog/view?id=4 " then the posts will not be deleted. After clicking in the lower left corner, the line appears: admin.site.com/blog/blog/delete?id=4 and the browser window can only be closed after that through the task manager.
I tried everything, I thought at first: maybe some JS left with an infinite loop? But here's what's interesting. In GoogleChrome, it freezes, and in Microsoft Edge, the post was deleted from the first time, but an error appeared from the second:
d27950bce5c0444bb232129e2918c9d8.jpgMozzila is the same. If you comment out 'beforeDelete' completely in Blog.php, then the post is deleted.
What is the reason here?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question