Php начал изучать недавно и решил попробовать сделать блог. В структуре он вынесен как отдельный модуль в папке vendor в Yii-2. Но с удалением постов возникла проблема! И ищу ошибку уже неделю..
Запускаю Open Server и пробую тестировать блог в разных браузерах по адресу: admin.site.com Так вот..в MicrosoftEdge и Mozilla - все работает и удаляется, а в GoogleGhrome-при нажатии на кнопку удаления появляется звук и после этого всё 'зависает'.
Blog.php
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. 125. 126. 127. 128. 129. 130. 131. 132. 133. 134. 135. 136. 137. 138. 139. 140. 141. 142. 143. 144. 145. 146. 147. 148. 149. 150. 151. 152. 153. 154. 155. 156. 157. 158. 159. 160. 161. 162. 163. 164. 165. 166. 167. 168. 169. 170. 171. 172. 173. 174. 175. 176. 177. 178. 179. 180. 181. 182. 183. 184. 185. 186. 187. 188. 189. 190. 191. 192. 193. 194. 195. 196. 197. 198. 199. 200. 201. 202. 203. 204. 205. 206. 207. 208. 209. 210. 211. 212. 213. 214. 215. 216. 217. 218. 219. 220. 221. 222. 223. 224. 225. 226. 227. 228. 229. 230. 231. 232. 233. 234.
<?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;
}
}
}
Blog Controller
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. 125. 126. 127. 128. 129. 130. 131. 132. 133. 134. 135. 136. 137. 138. 139. 140. 141. 142. 143. 144. 145. 146. 147. 148. 149. 150. 151. 152. 153. 154. 155. 156. 157. 158. 159. 160. 161. 162. 163. 164. 165. 166. 167. 168. 169. 170.
<?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.');
}
}
}
veiw.php
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72.
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use kartik\widgets\ActiveForm;
use kartik\widgets\FileInput;
use metalguardian\fotorama;
/* @var $this yii\web\View */
/* @var $model medeyacom\blog\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',
],
]) ?>
<?php
$fotorama = \metalguardian\fotorama\Fotorama::begin(
[
'options' => [
'loop' => true,
'hash' => true,
'ratio' => 800/600,
],
'spinner' => [
'lines' => 20,
],
'tagName' => 'span',
'useHtmlData' => false,
'htmlOptions' => [
'class' => 'custom-class',
'id' => 'custom-id',
],
]
);
foreach ($model->images as $one) {
echo Html::img($one->imageUrl,['alt'=>$one->alt]);
}
$fotorama->end(); ?>
</div>
Изначально было такое сообщение, но потом действие с 'unlink'-в function 'beforeDelete' Blog.php - закомментировал. Может быть, здесь нужно применить такой метод с проверкой? Но как это реализовать -не разберусь.
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
if(empty($this->image)){
//выполнится код, если:
//"" (пустая строка)
//0 (целое число)
//0.0 (дробное число)
//"0" (строка)
//NULL
//FALSE
//array() (пустой массив)
//$var; (переменная объявлена, но не имеет значения)
}
|