Как разобраться с маршрутизацией?
Как разобраться с маршрутизацией?
При попытке удаления поста в админ.панели браузер как бы зависает. Удаляется только если это сделать в базе. Картинки загружаются, но потом имеют такой вид и тоже не удаляются.
а на fronted они вообще не отображаются(
Если открывать пост в админке admin.site.com/blog/blog/view?id=2#1 - то их видно, прокрутка fotorama-widget есть, на fronted ничего нет. Из запросов видно, что в (blog/blog/index) запрос идет, а не в blog/image-delete как ожидается. Но что там конкретно менять нужно в url-manager?
И в каком именно urlmanager? в правилах yii2/fronted/config/main.php , yii2/backend/config/main.php или yii2/common/config/main.php?
а на fronted они вообще не отображаются(
Если открывать пост в админке admin.site.com/blog/blog/view?id=2#1 - то их видно, прокрутка fotorama-widget есть, на fronted ничего нет. Из запросов видно, что в (blog/blog/index) запрос идет, а не в blog/image-delete как ожидается. Но что там конкретно менять нужно в url-manager?
И в каком именно urlmanager? в правилах yii2/fronted/config/main.php , yii2/backend/config/main.php или yii2/common/config/main.php?
Re: Как разобраться с маршрутизацией?
Когда в коде удаления указывали маршрут, забыли модуль дописать.
Поменяйте
на
Поменяйте
Код: Выделить всё
blog/image-delete
Код: Выделить всё
blog/blog/image-delete
Re: Как разобраться с маршрутизацией?
Спасибо, это помогло!
Картинки стали удаляться, но вот посты по прежнему в backend не удаляются- браузер просто как-бы зависает и всё. В debage ничего нет,приходится закрывать страницу через диспетчер задач.
Картинки стали удаляться, но вот посты по прежнему в backend не удаляются- браузер просто как-бы зависает и всё. В debage ничего нет,приходится закрывать страницу через диспетчер задач.
Код: Выделить всё
<?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\web\UploadedFile;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use common\models\ImageManager;
use common\models\User;
/**
* 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
*/
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],
[['image'], 'file', 'extensions'=>'jpg, gif, png, svg'],
[['file'], 'image'],
[['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 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 (!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]);
}
public function beforeDelete()
{
if (parent::beforeDelete()) {
$dir = Yii::getAlias('@images').'/blog/';
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;
}
}
}
Re: Как разобраться с маршрутизацией?
Ну и как вы пробовали справиться с этим?
Re: Как разобраться с маршрутизацией?
пробовал добавить такой метод в Blog.Controller, но не сработало
Сейчас BlogController выглядит так:
Код: Выделить всё
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'));
}
Код: Выделить всё
<?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.');
}
}
}
Re: Как разобраться с маршрутизацией?
1. Закомментируйте всё в "beforeDelete" и проверьте, будет ли "зависать".
Если виснуть перестанет, значит проблема в "beforeDelete".
2. Если виснуть не перестало, разберитесь, на каком этапе всё подвисает.
Посмотрите на код, который генерирует кнопку удаления.
Посмотрите код HTML для кнопки, который сгенерировался по факту.
Проверьте, какие запросы идут, в инструментах разработчика в браузере.
Проверьте, срабатывает ли вообще экшен контроллера.
В общем, исследуйте, анализируйте, включайте логику, копайте.
Если виснуть перестанет, значит проблема в "beforeDelete".
2. Если виснуть не перестало, разберитесь, на каком этапе всё подвисает.
Посмотрите на код, который генерирует кнопку удаления.
Посмотрите код HTML для кнопки, который сгенерировался по факту.
Проверьте, какие запросы идут, в инструментах разработчика в браузере.
Проверьте, срабатывает ли вообще экшен контроллера.
В общем, исследуйте, анализируйте, включайте логику, копайте.
Re: Как разобраться с маршрутизацией?
.
Последний раз редактировалось Ilya_s 2017.08.14, 15:57, всего редактировалось 1 раз.
Re: Как разобраться с маршрутизацией?
Все перепробовал, подумал вначале: может, какой-то JS ушёл с бесконечный цикл? Но вот что интересно. В GoogleChrome - зависает, а в Microsoft Edge - c первого раза пост удалился, но со второго появилась ошибка:
в Mozzila- тоже самое. Если в Blog.php закомментировать 'beforeDelete' полностью- то пост удаляется.
В чем причина здесь?
Blog.php
в Mozzila- тоже самое. Если в Blog.php закомментировать 'beforeDelete' полностью- то пост удаляется.
В чем причина здесь?
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(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;
}
}
}
Re: Как разобраться с маршрутизацией?
Ну написано же - вы пытаетесь удалить файл, а имя файла пустое. "$dir" есть, а "$this->image" нет.
Re: Как разобраться с маршрутизацией?
Код: Выделить всё
if($this->image && file_exists($dir.$this->image)){
unlink($dir.$this->image);
}
Re: Как разобраться с маршрутизацией?
Если сделать так, то в MicrosoftEdge и Mozilla посты удаляются, а в GoogleChrome- 'зависает' опять.
Код: Выделить всё
public function beforeDelete()
{
if (parent::beforeDelete()) {
$dir = Yii::getAlias('@images').'/blog/';
if($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;
}
}
}