/** * Creates a new Book model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Book(); $model->date = strtotime(date('d.m.Y')); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['index', 'id' => $model->id]); } else { return $this->render('create', ['model' => $model]); } }
/** * Добавление книги. * * @return mixed * @throws \Exception * @throws \yii\base\Exception */ public function actionCreate() { $model = new Book(); if ($model->load(Yii::$app->request->post()) && $model->save()) { if (null !== ($image = UploadedFile::getInstance($model, 'preview'))) { $model->preview = $image; if (!$model->validate(['preview'])) { Yii::$app->getSession()->setFlash('error', Html::errorSummary($model, ['header' => 'Пожалуйста, исправьте следующие ошибки:', 'encode' => false])); return $this->redirect(['book/update', 'id' => $model->id]); } // работаем с новым загруженным изображением $uploadsDir = realpath(Yii::$app->params['booksUploadsDir']); $uploadsTmpDir = realpath(Yii::$app->params['frontendUploadsTmpDir']); // сохраняем изображение во временную директорию $tmpFilename = $uploadsTmpDir . DIRECTORY_SEPARATOR . 'book_preview_' . uniqid() . '.' . $image->getExtension(); if (false === $image->saveAs($tmpFilename)) { throw new Exception('Невозможно сохранить загруженное изображение для книги в файл: ' . $tmpFilename); } else { // создаем вложенные директории $path = Util::createNestedFolders($uploadsDir, $model->id); $filename = $path . DIRECTORY_SEPARATOR . dechex($model->id) . '.' . $image->getExtension(); $previewFilename = $path . DIRECTORY_SEPARATOR . dechex($model->id) . '_thumb.' . $image->getExtension(); $imagine = Image::getImagine(); /** @var $i \Imagine\Gd\Image */ $i = $imagine->open($tmpFilename); // если размеры изображения превышают лимиты, оно ресайзится if ($i->getSize()->getWidth() > Yii::$app->params['maxImageWidth'] || $i->getSize()->getHeight() > Yii::$app->params['maxImageHeight']) { $i->thumbnail(new Box(Yii::$app->params['maxImageWidth'], Yii::$app->params['maxImageHeight']), ImageInterface::THUMBNAIL_INSET)->save($filename, ['quality' => 100]); } else { $i->save($filename); } // создаем превьюшку из исходника $i = $imagine->open($tmpFilename); if ($i->getSize()->getWidth() > Yii::$app->params['thumbnailDefaultWidth'] || $i->getSize()->getHeight() > Yii::$app->params['thumbnailDefaultHeight']) { $i->thumbnail(new Box(Yii::$app->params['thumbnailDefaultWidth'], Yii::$app->params['thumbnailDefaultHeight']), ImageInterface::THUMBNAIL_INSET)->save($previewFilename, ['quality' => 100]); } // удаляем временный файл unlink($tmpFilename); $filename = str_replace('\\', '/', $filename); $filename = preg_replace('=^(.*?)(/uploads/books/.*)$=iu', '\\2', $filename); $model->preview = $filename; } $model->update(false, ['preview']); } Yii::$app->session->setFlash('success', 'Новая книга успешно добавлена.'); return $this->redirect(['index']); } else { return $this->render('create', ['model' => $model]); } }
public function safeUp() { $authors = Author::find()->all(); $authorsIds = []; foreach ($authors as $author) { $authorsIds[] = $author->id; } $fakerRus = Factory::create('ru_RU'); for ($i = 0; $i < 40; $i++) { $time = $fakerRus->unixTime; $book = new Book(); $book->name = $fakerRus->sentence(4); $book->date_create = $time; $book->date_update = $time; $book->date = $fakerRus->date; $book->author_id = $fakerRus->randomElement($authorsIds); $image = $fakerRus->image(Yii::getAlias('@frontend') . '/web/images'); $book->preview = str_replace(Yii::getAlias('@frontend') . '/web', '', $image); $result = $book->save(false); if (!$result) { return false; } } }