Coder Social home page Coder Social logo

yii2-gallery-manager's Introduction

Gallery Manager usage instructions

Yii2 port of https://github.com/zxbodya/yii-gallery-manager

(frontend part mostly without changes, but backend was rewritten almost completely)

Gallery manager screenshots (yii 1.x version, new one has bootstrap 3 styles):

GalleryManager images list

Few more screenshots: drag & drop upload, editing image information, upload progress,

Features

  1. AJAX image upload
  2. Optional name and description for each image
  3. Possibility to arrange images in gallery
  4. Ability to generate few versions for each image with different configurations
  5. Drag & Drop

Decencies

  1. Yii2
  2. Twitter bootstrap assets (version 3)
  3. Imagine library
  4. JQuery UI (included with Yii)

Installation:

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist zxbodya/yii2-gallery-manager "*@dev"

or add

"zxbodya/yii2-gallery-manager": "*@dev"

to the require section of your composer.json file.

Usage

Prepare

Add migration to create table for images:

class m150318_154933_gallery_ext
    extends zxbodya\yii2\galleryManager\migrations\m140930_003227_gallery_manager
{

}

Or better - copy migration to you application(but be sure to remove namespace from it - it should be in global namespace)

Add configurations for upload and store images

Add GalleryBehavior to your model, and configure it, create folder for uploaded files.

use zxbodya\yii2\galleryManager\GalleryBehavior;

class Product extends \yii\db\ActiveRecord 
{
...
public function behaviors()
{
    return [
         'galleryBehavior' => [
             'class' => GalleryBehavior::className(),
             'type' => 'product',
             'extension' => 'jpg',
             'directory' => Yii::getAlias('@webroot') . '/images/product/gallery',
             'url' => Yii::getAlias('@web') . '/images/product/gallery',
             'versions' => [
                 'small' => function ($img) {
                     /** @var \Imagine\Image\ImageInterface $img */
                     return $img
                         ->copy()
                         ->thumbnail(new \Imagine\Image\Box(200, 200));
                 },
                 'medium' => function ($img) {
                     /** @var \Imagine\Image\ImageInterface $img */
                     $dstSize = $img->getSize();
                     $maxWidth = 800;
                     if ($dstSize->getWidth() > $maxWidth) {
                         $dstSize = $dstSize->widen($maxWidth);
                     }
                     return $img
                         ->copy()
                         ->resize($dstSize);
                 },
             ]
         ]
    ];
}

See also documentations of imagine for image transformations.

Add GalleryManagerAction in controller somewhere in your application. Also on this step you can add some security checks for this action.

use zxbodya\yii2\galleryManager\GalleryManagerAction;

class ProductController extends Controller
{
...
public function actions()
{
    return [
       'galleryApi' => [
           'class' => GalleryManagerAction::className(),
           // mappings between type names and model classes (should be the same as in behaviour)
           'types' => [
               'product' => Product::className()
           ]
       ],
    ];
}

Add ImageAttachmentWidget somewhere in you application, for example in editing from.

use zxbodya\yii2\galleryManager\GalleryManager;

/* @var $this yii\web\View */
/* @var $model Product */
?>
...
<?php
if ($model->isNewRecord) {
    echo 'Can not upload images for new record';
} else {
    echo GalleryManager::widget(
        [
            'model' => $model,
            'behaviorName' => 'galleryBehavior',
            'apiRoute' => 'product/galleryApi'
        ]
    );
}
?>

Done!

Get uploaded images

Now, you can use uploaded images from gallery like following:

foreach($model->getBehavior('galleryBehavior')->getImages() as $image) {
    echo Html::img($image->getUrl('medium'));
}

Options

Using non default table name for gallery images(default is {{%gallery_image}}):

  1. Add migration that will create table you need
  2. Change tableName property in behavior configuration

yii2-gallery-manager's People

Contributors

and800 avatar andku83 avatar bscheshirwork avatar davarresc avatar davidyew avatar douglasmk avatar ekawalec avatar garando avatar oonne avatar sheershoff avatar stupidusername avatar zxbodya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-gallery-manager's Issues

Extension does not condiser type option

I have two models - products and services. For both I've configured galleryBehavior option accordingly:

public function behaviors()
    {
        Image::$driver = [Image::DRIVER_IMAGICK];
        return [
            'galleryBehavior' => [
                'class' => GalleryBehavior::className(),
                'type' => 'service',
                'extension' => 'jpg',
                'directory' => Yii::getAlias('@webroot') . '/upload/images/service',
                'url' => Yii::getAlias('@web') . '/upload/images/service',
                'versions' => [
                    ...
                ]
            ],
        ];
    }

and

public function behaviors()
    {
        Image::$driver = [Image::DRIVER_IMAGICK];
        return [
            'galleryBehavior' => [
                'class' => GalleryBehavior::className(),
                'type' => 'product',
                'extension' => 'jpg',
                'directory' => Yii::getAlias('@webroot') . '/upload/images/product',
                'url' => Yii::getAlias('@web') . '/upload/images/product',
                'versions' => [
                    ...
                ]
            ],
        ];
    }

Images are saving correctly - each gallery to its directory but when I try to display them in my views I get strange behavior: images will be loading without considering a type.

In my view I render the gallery as follows:

<?php $images = $service->images; ?>

<?php foreach($images as $image) : ?>
    <?= Html::img("/upload/images/{$image->type}/{$image->ownerId}/{$image->id}/full_image.jpg") ?>
<?php endforeach; ?>

What is does is it loads all of the images with suited ownerId without noticing a type field.

Button 'Select All' is bigger that others?

Hi! Good widget, but it looks very ugly in my project.

1
Is simple way to fix this bug, but overriding rules for this purpose is really no well idea and may not work when widget will updated

fix1
Please, check how you widget looks in different browsers and correct styles

Limit number of images

Nice Job! i wanted to know if there is already a parameter o configuration to limit the number of images to upload. For example, i want to limit a user to upload just 5 images for each product.

Thanks!
Lkn

How to access images without creating objects?

How can I access or retrieve image related to model, if it is non-object, but array? For example, I have Product model with galleryBehavior. But because of memory limitations I access to it in array mode:

$product = Product::find()->where(['id' => 325])->asArray()->one();

How can I get link for image, attached to this product? I know, that this extension creates folders for each model, naming them according to ID of model item. But there are some subfolders with another ID's (probably, with ID from database table of gallery_images) where images are located (original.jpg, preview.jpg etc.(.

Exception: Invalid Parameter named "photo" updating the model

Great extension!
I'm doing a test with one of my Models (Dealer) to get the extension up and running. I just add one "image" field cause some errors, but when everything seems to be working, and the files were generated, also all "gallery_image" fields were populated. (I can see the image rendered in the "view" action) but the "update" action is through me an Invalid Parameter – yii\base\InvalidParamException.
.... backend\models\Dealer has no relation named "photos".

I was checking the GalleryManagerAction/changeData action... and there you have the parameter photo, so what kind of changes I need to do or any other ideas to fix this Exception.

Thanks

Error when ajaxUpload Class 'common\models\Box' not found

Hello, i'm facing same trouble. when ajax
I'm using inspector chrome, and the error it's
Class 'common\models\Box' not found
in behavior i'm copy from your tutorial readme.md

return $img->copy()->thumbnail(new Box(200, 200));

When i'm open new tab it's change error to Trying to get property of non-object (maybe cause no file uploaded).

I didn't know what is Box Class ? and how to use it or include it ?

and I already correct code

use zxbodya\yii2\galleryManager\galleryBehavior;

to

use zxbodya\yii2\galleryManager\GalleryBehavior;

here my behavior

use zxbodya\yii2\galleryManager\GalleryBehavior;

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'galleryBehavior' => [
                 'class' => GalleryBehavior::className(),
                 'type' => 'toilet',
                 'extension' => 'jpg',
                 'directory' => Yii::getAlias('@webroot') . '/images/toilet/gallery',
                 'url' => Yii::getAlias('@web') . '/images/toilet/gallery',
                 'versions' => [
                     'small' => function ($img) {
                         /** @var ImageInterface $img */
                         return $img
                             ->copy()
                             ->thumbnail(new Box(200, 200));
                     },
                     'medium' => function ($img) {
                         /** @var ImageInterface $img */
                         $dstSize = $img->getSize();
                         $maxWidth = 800;
                         if ($dstSize->getWidth() > $maxWidth) {
                             $dstSize = $dstSize->widen($maxWidth);
                         }
                         return $img
                             ->copy()
                             ->resize($dstSize);
                     },
                 ]
             ]
        ]);
    }

Controller

use zxbodya\yii2\galleryManager\GalleryManagerAction;

public function actions()
    {
        return [
           'galleryApi' => [
               'class' => GalleryManagerAction::className(),
               // mappings between type names and model classes (should be the same as in behaviour)
               'types' => [
                   'toilet' => Toilet::className()
               ]
           ],
        ];
    }

_form.php

use zxbodya\yii2\galleryManager\GalleryManager;

        <?php 
    if ($model->isNewRecord) {
        echo 'Can not upload images for new record';
    } else {
        echo GalleryManager::widget(
            [
                'model' => $model,
                'behaviorName' => 'galleryBehavior',
                'apiRoute' => 'toilet/galleryApi'
            ]
        );
    }
    ?>


some Stack Trace while new tab

exception 'yii\base\ErrorException' with message 'Trying to get property of non-object' in E:\xampp\htdocs\web\advanced\vendor\zxbodya\yii2-gallery-manager\GalleryManagerAction.php:102
Stack trace:
#0 E:\xampp\htdocs\web\advanced\vendor\zxbodya\yii2-gallery-manager\GalleryManagerAction.php(102): yii\base\ErrorHandler->handleError(8, 'Trying to get p...', 'E:\\xampp\\htdocs...', 102, Array)
#1 E:\xampp\htdocs\web\advanced\vendor\zxbodya\yii2-gallery-manager\GalleryManagerAction.php(59): zxbodya\yii2\galleryManager\GalleryManagerAction->actionAjaxUpload()
#2 [internal function]: zxbodya\yii2\galleryManager\GalleryManagerAction->run('ajaxUpload')
#3 E:\xampp\htdocs\web\advanced\vendor\yiisoft\yii2\base\Action.php(92): call_user_func_array(Array, Array)
#4 E:\xampp\htdocs\web\advanced\vendor\yiisoft\yii2\base\Controller.php(151): yii\base\Action->runWithParams(Array)
#5 E:\xampp\htdocs\web\advanced\vendor\yiisoft\yii2\base\Module.php(455): yii\base\Controller->runAction('galleryApi', Array)
#6 E:\xampp\htdocs\web\advanced\vendor\yiisoft\yii2\web\Application.php(83): yii\base\Module->runAction('toilet/galleryA...', Array)
#7 E:\xampp\htdocs\web\advanced\vendor\yiisoft\yii2\base\Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))
#8 E:\xampp\htdocs\web\advanced\frontend\web\index.php(18): yii\base\Application->run()
#9 {main}

get Absolute URL of image ?

Hello again,
How i can generate Absolute URL directly from image with domain ?
$img->getUrl()
example with getUrl()

/images/model/gallery/1/34/small.jpg
/front/images/model/gallery/1/35/small.jpg?_=199223985

i want to get like this one.

www.domain.com/images/model/gallery/1/34/small.jpg
localhost/front/images/model/gallery/1/35/small.jpg?_=199223985

or

http://www.domain.com/images/model/gallery/1/34/small.jpg
http://localhost/front/images/model/gallery/1/35/small.jpg?_=199223985

i'm trying with Yii::$app->request->baseUrl but result like this

/images/model/gallery/1/34/small.jpg
front/front/images/model/gallery/1/35/small.jpg?_=199223985

trying with Yii::$app->urlManager->createAbsoluteUrl( $image->getUrl('small') ) result this

http://www.domain.com/index.php?r=images%2Fmodel%2Fgallery%2F1%2F33%2Fsmall.jpg%3F_%3D4172838988
http://localhost/front/index.php?r=front%2Fimages%2Fmodel%2Fgallery%2F1%2F35%2Fsmall.jpg%3F_%3D199223985

thank you.

PHP Warning - rename(...): Invalid argument

I've got this error. How to fix it? (PHP Warning - rename(...): Invalid argument . This happens when creating a model with attached galleryBehavior. Also, I'm using some another behaviors (translateableBehavoir by Creocoder, AdjacencyList Behavoir by Paulzi and Image Attachment by zxbodya). Maybe this is due to some behavours conflict? (for example, adjacency list behavour uses another method for creating new records, like 'prependTo', 'appendTo' etc)

Overwriting modal attributes

It's cool to change modal attributes while initializing a widget. Cause there are many conflicts with its id's and classes when initializing gallery widget in another modal form.

For example, close button closes "Edit information" modal + main modal, where gallery was initialized.

Error in actionAjaxUpload

When i add an image for upload gives the error "Trying to get property of non-object" in the line $image = $this->behavior->addImage($fileName)

I check it out in FireBug and i can see all the properties from the image , but in the addImage simples crash.

Не все фото загружаются

Установил на сайт ваш менеджер галереи, но вот скрин http://joxi.ru/Dr8PDWBckNaLLr в нем видно что не все фото загрузились, а в таблицы бд записи создались.
Какие именно фото загружались сказать не могу, возможно jpeg расширение. Просто в скрине не я загружал, а пользователи в личном кабинете.

Can't migrate

PHP Fatal error: Class 'm140930_003227_gallery_manager' not found in /var/www/vendor/yiisoft/yii2/console/controllers/MigrateController.php on line 170

Further update

Hello,
Thanks for making this extension. I am not very keen on working with git yet, so i'm writting here.
I made a fork: https://github.com/taskas/yii2-gallery-manager and also made more adaption for yii2 with improvements:

  • Fixed behavior to work in yii2
  • Propose to use alias for images Urls, so for example in yii2 advanced backend app config you can set:
    'aliases'=> [
        '@galleryManagerRoot'=>realpath(dirname(__FILE__).'/../../public/'),
        '@galleryManagerRootUrl'=>'/public/',
    ],
  • Made lame but still bit more useful implementation of image generation (see GalleryPhoto::updateImages function), so my model's behavior config looks like:
    public function behaviors()
    {
        return [
            'gallery' => [
                'class' => GalleryBehavior::className(),
                'idAttribute' => 'gallery_id',
                'extension'=>'png',
                'versions'=>[
                    'medium' => [
                        'widen' => [800],
                    ]
                ]
            ],
        ];
    }
  • Modified table gallery by adding this column: directory varchar(64) NOT NULL

Well, check my last commit. I sorta didn't know how to push to your repository. Still learning git stuff...
Hope it will help!

Вынести все шаблоны блоков разметки в виджет для изменения.

Я так понял, что ты русский, поэтому как бы пишу так.

Можешь вынести все шаблоны HTML разметки из js файла в виджет для изменения? Я бы даже сказал, в идеале, достаточно, чтобы можно было изменять аттрибуты div, где класс .photo, .image-preview.

500 Internal Server Error when I click add

It returns 500 Internal Server Error when I try to add an image. The error is : Call to a member function addImage() on null

  1. in C:\OpenServer\domains\azreal.az\vendor\zxbodya\yii2-gallery-manager\GalleryManagerAction.php at line 111
    102103104105106107108109110111112113114115116117118119120 *
    • @return string

    • @throws HttpException
      */
      public function actionAjaxUpload()
      {

      $imageFile = UploadedFile::getInstanceByName('image');
      $fileName = $imageFile->tempName;
      $image = $this->behavior->addImage($fileName);

      // not "application/json", because IE8 trying to save response as a file

      Yii::$app->response->headers->set('Content-Type', 'text/html');

      return Json::encode(
      array(
      'id' => $image->id,
      'rank' => $image->rank,

Call to a member function getImages() on null

image
Hello, after lots of time at last I can upload and see the images at least, but when I try to use:
foreach($model->getBehavior('galleryBehavior')->getImages() as $image) {
echo Html::img($image->getUrl('medium'));
}
I get that error, no idea what to do, please help

Getting unknown property: common\models\Product::isNewRecord

Hi, I'm getting this error and I don't know why.
Well, I think that I'm doing something wrong coz I don't understand some moments of usage instruction.
So, please if You have some examples of ready to use project with this extension, send it to me.

And my code:

SiteController.php:

<?php

namespace frontend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use common\models\LoginForm;
use common\models\ContactForm;
use common\models\Product;
use zxbodya\yii2\galleryManager\GalleryManagerAction;

class SiteController extends Controller
{
    /**
     * @inheritdoc
     */

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
            'galleryApi' => [
                'class' => GalleryManagerAction::className(),
                // mappings between type names and model classes (should be the same as in behaviour)
                'types' => [
                    'product' => Product::className()
                ]
            ],
        ];
    }
    public function actionContact()
    {
        $model = new Product();
        return $this->render('contact', [
            'model' => $model,
        ]);
    }
}

Product.php (model)

<?php

namespace common\models;

use Yii;
use yii\helpers\Html;
//use zxbodya\yii2\galleryManager\GalleryManager;
use yii\base\Model;
use yii\widgets\ActiveForm;
use yii\db\BaseActiveRecordInterface;
use zxbodya\yii2\galleryManager\GalleryBehavior;
use yii\base\Object;
//use zxbodya\yii2\galleryManager\ImageAttachmentWidget;

class Product extends Model {

    public function behaviors()
    {
        return [
            'galleryBehavior' => [
                'class' => GalleryBehavior::className(),
                'type' => 'product',
                'extension' => 'jpg',
                'directory' => Yii::getAlias('@webroot') . '/images/product/gallery',
                'url' => Yii::getAlias('@web') . '/images/product/gallery',
                'versions' => [
                    'small' => function ($img) {
                        /** @var \Imagine\Image\ImageInterface $img */
                        return $img
                            ->copy()
                            ->thumbnail(new \Imagine\Image\Box(200, 200));
                    },
                    'medium' => function ($img) {
                        /** @var Imagine\Image\ImageInterface $img */
                        $dstSize = $img->getSize();
                        $maxWidth = 800;
                        if ($dstSize->getWidth() > $maxWidth) {
                            $dstSize = $dstSize->widen($maxWidth);
                        }
                        return $img
                            ->copy()
                            ->resize($dstSize);
                    },
                ]
            ]
        ];
    }
}
?>

contact.php (action)

<?php

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model app\common\models\Product */

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\base\Object;
use yii\captcha\Captcha;
use zxbodya\yii2\galleryManager\GalleryManager;
use zxbodya\yii2\galleryManager\ImageAttachmentWidget;
use yii\helpers\ArrayHelper;

if ($model->isNewRecord) {
    echo 'Can not upload images for new record';
} else {
    echo GalleryManager::widget(
        [
            'model' => $model,
            'behaviorName' => 'galleryBehavior',
            'apiRoute' => 'product/galleryApi'
        ]
    );
}
?>

Thank You in advance for your attention.

Widget doesn't load photos. No ajax request has been sent.

Can't figure out why the widget in my form doesn't load images.
After choosing an image from my HDD the window just closes and nothing happens. At all.
I have no errors, no warnings, no ajax requests has been sent.
Two js files from module are included, widget renders fine.
Also, if I try to drag-n-drop image on top of the widget no message box appears (no gray dotted box Drop File Here...).
Console is clean, no errors.
Can you, please, suggest any possible reasons?
Thanks.

Use gallery-manager widget in bootstrap modal window

I use renderAjax to load form in modal window. Gallery widget render view (buttons etc..) but not works (don't upload files). It working OK without modal... Please help.

Controller:

public function actionAddAnnounce(){
$announce = new Announces();
return $this->renderAjax('add_announce', compact('announce'));
}

View (add_announce)

$form = ActiveForm::begin(['action' => '/user/add-announce', 'id' => 'new_announce']);
echo GalleryManager::widget(
[
'model' => $announce,
'behaviorName' => 'galleryBehavior',
'apiRoute' => 'user/galleryApi'
]);
ActiveForm::end();

Working Demo?

Downloadable working Demo would be great. Behaviours are sometimes hard to visualize.
Do you plan to have any?

WaterMark

Is it possible to create watermark for images?
Thanks

it can not upload photos yii2 basic

untitled
//my is Migration

createTable(
        $this->tableName,
        array(
        'id' => Schema::TYPE_PK,
        'type' => Schema::TYPE_STRING,
        'ownerId' => Schema::TYPE_STRING . ' NOT NULL',
        'rank' => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT 0',
        'name' => Schema::TYPE_STRING,
        'description' => Schema::TYPE_TEXT
        )
        );
    }
    public function down()
    {
        $this->dropTable($this->tableName);
    }
}

action is

     public function actions()
    {
        return [
           'galleryApi' => [
               'class' => GalleryManagerAction::className(),
               // mappings between type names and model classes (should be the same as in behaviour)
               'types' => [
                   'imggallery' => Imggallery::className()
               ]
           ],
        ];
    }

//model behavior is

 public function behaviors()
    {
        return [
             'galleryBehavior' => [
                 'class' => GalleryBehavior::className(),
                 'type' => 'imggallery',
                 'extension' => 'jpg',
                 'directory' => Yii::getAlias('@webroot') . '/uploads',
                 'url' => Yii::getAlias('@webroot') . '/uploads',
                 'versions' => [
                     'small' => function ($img) {
                         /** @var ImageInterface $img */
                         return $img
                             ->copy()
                             ->thumbnail(new Box(200, 200));
                     },
                     'medium' => function ($img) {
                         /** @var ImageInterface $img */
                         $dstSize = $img->getSize();
                         $maxWidth = 800;
                         if ($dstSize->getWidth() > $maxWidth) {
                             $dstSize = $dstSize->widen($maxWidth);
                         }
                         return $img
                             ->copy()
                             ->resize($dstSize);
                     },
                 ]
             ]
        ];
    }

view _form is

   if ($model->isNewRecord) {
            echo 'Can not upload images for new record';
        } else {
            echo GalleryManager::widget(
                [
                    'model' => $model,
                    'behaviorName' => 'galleryBehavior',
                    'apiRoute' => 'imggallery/galleryApi'
                ]
            );
        }

when i update the form it looks like this
untitled1

Adding a gallery to new records

The extension works great. I haven't had a deep look into the code, but how hard would it be to change some code around so images can be added to new records in this behavior and your image attachment one? Maybe AFTER_CREATE or AFTER_UPDATE events could be tuned up for this?

Thanks!

Calling getUrl() function from frontend returns NULL (in advanced app)

'directory' => Yii::getAlias('@webroot') . '/backend/media/transport/gallery',
'url' => Yii::getAlias('@web') . '/backend/media/transport/gallery',

The previous two properties read paths differently in backend & frontend.
My model in backend, so getUrl() returns true path in backend, but in frontend not working.
How can I fix this, Thanks.

Eager loading for images

There is a problem - because "images" is not a relation, we can not apply eager loading, for example, when displaying several products with their images. So, there will be a number of database queries executed. It is not good.

It gives 404 when I upload a photo

The following is my code.
In model:

     public function behaviors()
    {
        return [
             'galleryBehavior' => [
                 'class' => GalleryBehavior::className(),
                 'type' => 'product',
                 'extension' => 'jpg',
                 'directory' => Yii::getAlias('@webroot') . '/images/product/gallery',
                 'url' => Yii::getAlias('@web') . '/images/product/gallery',
                 'versions' => [
                     'small' => function ($img) {
                         /** @var \Imagine\Image\ImageInterface $img */
                         return $img
                             ->copy()
                             ->thumbnail(new \Imagine\Image\Box(200, 200));
                     },
                     'medium' => function ($img) {
                         /** @var Imagine\Image\ImageInterface $img */
                         $dstSize = $img->getSize();
                         $maxWidth = 800;
                         if ($dstSize->getWidth() > $maxWidth) {
                             $dstSize = $dstSize->widen($maxWidth);
                         }
                         return $img
                             ->copy()
                             ->resize($dstSize);
                     },
                 ]
             ]
        ];
    }

In controller:

            'galleryApi' => [
           'class' => GalleryManagerAction::className(),
           // mappings between type names and model classes (should be the same as in behaviour)
           'types' => [
               'product' => CreateNews::className()
           ]
       ],

When I try to add photo it gives the following error: POST http://azreal.az/admin/product/galleryApi?type=product&behaviorName=galleryBehavior&galleryId=10407&action=ajaxUpload 404 (Not Found)

Problem in create

Hello.

My english is very bad. I have next problem:
I create new page, after create I get next error:
rename(/var/www/rweb/www/web/files/product_gallery/,/var/www/rweb/www/web/files/product_gallery/11): Invalid argument
in /var/www/rweb/www/vendor/zxbodya/yii2-gallery-manager/GalleryBehavior.php line 159

Why? What i am doing not right? Please, help me.

gallery-manager recompress original images

Gallery-image save added file with original image size but not original file content. I want use original image files without recompression, its possible with native func of gallery-manager?

502 ошибка при аплоаде

при загрузке изображения с шаблоном advanced я получаю 502 ошибку. С чем это может быть связано ? Устанавливал из композера, из настроек сменил пути загрузки изображений. пробовал оставлять как есть, всё равно 502

Error Class yii\jui\JuiAsset does not exist

Hello, i'm trying to use your plugins in yii2. trying same as in readme.md when im trying to open Model/Update?id=1 I got error in while trying to echo widget GalleryManager. (Note im using yii2-advance-template)

ReflectionException
Class yii\jui\JuiAsset does not exist

here the details of my script.

frontend/config/main.php & backend/config.main.php

    'modules' => [
        'yii2images' => [
            'class' => 'rico\yii2images\Module',
            //be sure, that permissions ok 
            //if you cant avoid permission errors you have to create "images" folder in web root manually and set 777 permissions
            'imagesStorePath' => 'images/store', //path to origin images
            'imagesCachePath' => 'images/cache', //path to resized copies
            'graphicsLibrary' => 'GD', //but really its better to use 'Imagick' 
            'placeHolderPath' => '@webroot/images/placeHolder.png', // if you want to get placeholder when image not exists, string will be processed by Yii::getAlias
        ],
    ],

composer.json

"require": {
    "php": ">=5.4.0",
    "yiisoft/yii2": "*",
    "yiisoft/yii2-bootstrap": "*",
    "yiisoft/yii2-swiftmailer": "*",
    "yiisoft/yii2-gii": "*",
    "yiisoft/yii2-jui": "*",
    "costa-rico/yii2-images": "dev-master",
    "2amigos/yii2-file-input-widget":"~1.0",
    "zxbodya/yii2-gallery-manager": "*@dev"
},

also do composer install

_form.php

use zxbodya\yii2\galleryManager\GalleryManager;

if ($model->isNewRecord) {
    echo 'Can not upload images for new record';
} else {
    echo GalleryManager::widget(
        [
            'model' => $model,
            'behaviorName' => 'galleryBehavior',
            'apiRoute' => 'toilet/galleryApi'
        ]
    );
}

Toilet.php

use zxbodya\yii2\galleryManager\GalleryBehavior;

public function behaviors()
{
    return ArrayHelper::merge(parent::behaviors(), [
        'galleryBehavior' => [
             'class' => GalleryBehavior::className(),
             'type' => 'toilet',
             'extension' => 'jpg',
             'directory' => Yii::getAlias('@webroot') . '/images/toilet/gallery',
             'url' => Yii::getAlias('@web') . '/images/toilet/gallery',
             'versions' => [
                 'small' => function ($img) {
                     /** @var ImageInterface $img */
                     return $img
                         ->copy()
                         ->thumbnail(new Box(200, 200));
                 },
                 'medium' => function ($img) {
                     /** @var ImageInterface $img */
                     $dstSize = $img->getSize();
                     $maxWidth = 800;
                     if ($dstSize->getWidth() > $maxWidth) {
                         $dstSize = $dstSize->widen($maxWidth);
                     }
                     return $img
                         ->copy()
                         ->resize($dstSize);
                 },
             ]
         ]
    ]);
}

ToiletController.php

use zxbodya\yii2\galleryManager\GalleryManagerAction;

public function actions()
{
    return [
       'galleryApi' => [
           'class' => GalleryManagerAction::className(),
           // mappings between type names and model classes (should be the same as in behaviour)
           'types' => [
               'toilet' => Toilet::className()
           ]
       ],
    ];
}

also already done with migrate new Table gallery_image. (is there any column data of my Model must added too ?)
thank you.

Uncaught TypeError: $editorModal.modal is not a function

Everything works fine but when I try to edit picture error above appears.

This line to be precise:
jquery.galleryManager.js:130

$editorModal.modal('show');

My code(mainly from example):
migration:

<?php

use yii\db\Schema;
use yii\db\Migration;

class m150619_015846_gallery_manager extends Migration
{
    public $tableName = '{{%gallery_image}}';

    public function up()
    {
        $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';

        $this->createTable(
            $this->tableName,
            array(
                'id' => Schema::TYPE_PK,
                'type' => Schema::TYPE_STRING,
                'ownerId' => Schema::TYPE_STRING . ' NOT NULL',
                'rank' => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT 0',
                'name' => Schema::TYPE_STRING,
                'description' => Schema::TYPE_TEXT
            ), $tableOptions);
    }

    public function down()
    {
        $this->dropTable($this->tableName);
    }
}

model:

public function behaviors()
    {
        return [
           // ...
            'galleryBehavior' => [
                'class' => GalleryBehavior::className(),
                'type' => 'work-item',
                'extension' => 'jpg',
                'directory' => Yii::getAlias('@webroot') . '/uploads/work-gallery',
                'url' => Yii::getAlias('@web') . '/uploads/work-gallery',
                'versions' => [
                    'small' => function ($img) {
                     /** @var \Imagine\Image\ImageInterface $img */
                        return $img->copy()->thumbnail(new \Imagine\Image\Box(150, 100));
                    },

                    'medium' => function ($img) {
                     /** @var Imagine\Image\ImageInterface $img */
                        $dstSize = $img->getSize();
                        $maxWidth = 800;
                        if ($dstSize->getWidth() > $maxWidth) {
                            $dstSize = $dstSize->widen($maxWidth);
                        }
                        return $img->copy()->resize($dstSize);
                    },
                ],
            ],
            // ...
        ];
    }

controller:

public function actions()
    {
        return [
           'galleryApi' => [
               'class' => GalleryManagerAction::className(),
               // mappings between type names and model classes (should be the same as in behaviour)
               'types' => [
                   'work-item' => WorkItem::className()
               ]
           ],
        ];
    }

view(_form.php):

<?php 
        if ($model->isNewRecord) {
            echo 'Can not upload images for new record';
        } else {
            echo GalleryManager::widget(
                [
                    'model' => $model,
                    'behaviorName' => 'galleryBehavior',
                    'apiRoute' => 'work/galleryApi'
                ]
            );
        }
    ?>

How to create squared version of image?

Hello! Could you help me, please, to create squared version of uploaded image? It's hard to find examples for Imagine in Yii2, and I really don't get how it works in this behavior.
I need squared version of images, let's say 640x640 px, even if images has different aspect ratio (image should be centered, downscaled and filled with white background).
If I try this:

'versions' => [
    'squared' => function ($img) {
        return $img->copy()->thumbnail(new \Imagine\Image\Box(640, 640));
    },
]

it just creates image with max side of 640. What manipulations should I do to achieve the goal?

is there any example to use upload manually from another controller ?

I want try to find a way to Upload Image manually, any example ? let me explain the case:

  • Toilet Model -> Model with behavior using GalleryBehavior (normal use)
  • ToiletController -> of course this is the controller
  • Manual Model -> Model of Manual (manual upload)
  • ManualController -> Another Controller with manual upload image,
  • ManualController::actionAccept() -> when accept, image from manual moved / upload to Toilet Model

My Target is, using ManualController can I submit a image to Toilet Model, Image file (full path) already provide from ManualController ,

public function actionAccept($id)
{
    $model = $this->findModel($id);
    $model->status = Manual::STATUS_ACCEPTED;

    $modelToilet = Toilet::findModel($model->id_toilet);
    $modelFile = new ManualFile();
    $modelFile->manual = $model;
    $imagePath = $modelFile->getFilePath(true);
    if(!is_null($modelToilet)){
        //TODO save image ke Toilet

        $model->save();
    }else{
        throw new NotFoundHttpException('The requested page does not exist.');
    }
    return $this->redirect(['index']);
}

in section //TODO how to upload image to $modelToilet ?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.