Gallery Manager extension

Hi Bogdan,

Congratulations on a fantastic extension!

I have installed your cms-app locally and the gallerManager extension works great. I have tried to include it in my project but I am having problems.

I have included the extension, models, controllers, views and gallery folder and I am not using an admin module but none of the functionality works for me in the widget. I am seeing the images that are referenced in the database (that I added before I put it in my app) but I cannot edit them, delete them or upload new ones. I don’t even see the image thumbnail in the modal popup.

Any ideas?

Many thanks

  1. Have you included bootstrap scripts and styles on your page?

  2. Does GalleryController added in controllerMap?

What do you have in log files, and browser console?

Also write more about your app configuration.

Недавно изучаю данный фреймверк. Все коленки уже искусал не соображу как подключить расширение, чтоб оно отобразилось на первой странице только что сгенерированного приложения. Не сооброжу что и в каком порядке делать.

Это для меня видно сложно. Расширение допусти пункт 1 я подключаю. 2-й пункт с китайскими иероглифами. Мне необходимо просто расширение без регистраций и администрирования, чтоб просто на базе него расширять и изучать.

Готовое тестовое приложение запустить удалось. Но пустое приложение запустить с этим расширение вкурить не могу, видно вреймверк не совсем понимаю. Есть где-то просто пример по пунктам как заставить просто завестись его?

Hello,

I have install your great extension.

Now I have only one question.

In the model GalleryPhoto, we can change the gallery directory :

public $galleryDir = 'images/pro';

Now, do we have a way to create on the fly sub-folder (in my example, I need a sub-folder for each categories of product) ??

Thanks.

JMS

Hello Bogdan,

I am using your extension, I would like to know how I can implement pagination using this extension? Let us say I would like to show only 5 images per view and if there are more in album, then provide pagination options. Please let me know if you have example code or how to implement pagination in your extension?

If you need any additional info on how i am using your extension, let me know I can provide code etc.

Thanks

You can easily do this using CPagination component and CLinkParer widget:

In controller something like:




$criteria = new CDbCriteria();

$criteria->condition = 'gallery_id = :gallery_id';

$criteria->params[':gallery_id'] = $gallery->id;

$pages = new CPagination(GalleryPhoto::model()->count($criteria));

$pages->pageSize = 5;

$pages->applyLimit($criteria);

$pagePhotos = GalleryPhoto:model()->findAll($criteria);

$this->render('index', array('photos'=>$pagePhotos, 'pages'=>$pages));



And in view:




foreach($photo in $photos) { .... }

$this->widget('CLinkPager', array( 'pages' => $pages));



Hi Bogdan,

I use your extension with lot of happiness :)

Now i am thinking about modifying the images. I found a method at the Behavior Class, called ‘changeConfig’. Is that method related to changing the images? If i am right, how to use this method?

Thanks, Laszlo from Hungary

Yes, it is.

I have updated extension, and added section in readme for this case.

So upgrade to latest version and use it ;)

http://www.yiiframework.com/extension/imagesgallerymanager/

How about this code at:

galleryManage/models/GalleryPhoto [line no.]195


$image->save(Yii::getPathOfAlias('webroot') . '/' .$this->galleryDir . '/' . $this->getFileName( $version=='original'?'':$version  ) . '.' . $this->galleryExt);

This way the user could also pass a parameter ‘original’ which will re-size the original image uploaded…




    $gallery->versions = array(

        'small' => array(

            'resize' => array(200, null),

        ),

        'medium' => array(

            'resize' => array(800, null),

        ),

        // 'original' has to be last

        'original' => array(

            'resize' => array(900, null),

        ),        

    );



I felt the need of this as the current digital cams produce images of 4-5 mb and we rarely need to keep such images on our website.

Hi Bogdan, i have finally made your extension updated in one of my yii projects to test it. It works fine! Well done job again! Thanks! :)

UPDATE: I think there is an issue anyway.

I tested a lot and found something in this code in the changeconfig() method of the GalleryBehavior class:


$gallery->name = $this->name;

            $gallery->description = $this->description;

            $gallery->versions = $this->versions;

            $gallery->save();


            foreach ($gallery->galleryPhotos as $photo) {

                $photo->updateImages();

            }

when saving the new versions with calling the save() function i think the $gallery object’s galleryPhotos property is not refreshing with this save. Therefore in the foreach section of this code the $photo variable has the old version’s data. You can see that in the GalleryPhoto class’s updateImages() method:


public function updateImages() {

        

        foreach ($this->gallery->versions as $version => $actions) {

$this->removeFile(Yii::getPathOfAlias('webroot') . '/' . $this->galleryDir . '/' . $this->getFileName($version) . '.' . $this->galleryExt);


            $image = Yii::app()->image->load(Yii::getPathOfAlias('webroot') . '/' . $this->galleryDir . '/' . $this->getFileName('') . '.' . $this->galleryExt);

            foreach ($actions as $method => $args) {

                call_user_func_array(array($image, $method), is_array($args) ? $args : array($args));

            }

            $image->save(Yii::getPathOfAlias('webroot') . '/' . $this->galleryDir . '/' . $this->getFileName($version) . '.' . $this->galleryExt);

}

So in this method


$this

is the


$photo

object which has the gallery property unchanged with it’s version_data. Therefore the


$image->save()

call saves the image in the earlier version.

I tried to repair it but i don’t know why


$photo->gallery

has the older version of data.

UPDATE AGAIN: oops I found a solution i think. Maybe this helps in the changeConfig() method(calling $this->getGallery again but before that you have to null the private _gallery property):


foreach ($gallery->galleryPhotos as $photo) {

                $photo->removeImages();

            }


            $gallery->name = $this->name;

            $gallery->description = $this->description;

            $gallery->versions = $this->versions;

            $gallery->save();


            $this->_gallery = null;

            $gallery = $this->getGallery();


            if ($gallery == null)

                return;


            foreach ($gallery->galleryPhotos as $photo) {

                $photo->updateImages();

            }

If I am right with all of these of course :)

Laszlo from Hungary

Hi bogdan ,

why the display view does not appear ?

what’s the solution?

//Controller

$gallery = new Gallery();

    $gallery->name = true;


    $gallery->description = true;


    $gallery->versions = array(


        'small' => array(


            'resize' => array(200, null),


        ),


        'medium' => array(


            'resize' => array(800, null),


        )


    );


    $gallery->save();


    $this->widget('ext.galleryManager.GalleryManager', array(


        'gallery' => $gallery,


        'controllerRoute' => 'gallery', //route to gallery controller


    ));

what is wrong?

thx

Багдан , здорова!

Классное расширение, твоя галлерея, я Фраймвор мало знаю месяц от силы, может что-то пропустил, подскажи пожайлуста.

На форме сейчас вообще ни на что не реагирует

4819

26-10-2013 23-09-28.png

Импортировал Расширение в главном config/main.php:

4820

2.png

Вот мои папки в проекте, там у меня Админ панель как бы, реализованая типа как Модуль.

4821

моя иерархия папок.png

Расширель Модуль Админа

4822

ррасширил АдмиМодуль.png

Добавил актионГаллерея в контроллер User

4823

actionGallery.png

Вставил виджет на форму:

4824

элемент на форме.png

Заголовок формы




<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'user-form',

    'htmlOptions'=>array('autocomplete'=>'off',

    'enctype'=>'multipart/form-data',

        ),

	// Please note: When you enable ajax validation, make sure the corresponding

	// controller action is handling ajax validation correctly.

	// There is a call to performAjaxValidation() commented in generated controller code.

	// See class documentation of CActiveForm for details on this.

	'enableAjaxValidation'=>true,

)); ?>

	<p class="note">Fields with <span class="required">*</span> are required.</p>

	<?php echo $form->errorSummary($model); ?>



еще в шаблон шил стили и js bootstrapa




    <script src="<?php echo Yii::app()->request->baseUrl; ?>/js/bootstrap.js"></script>

    <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/bootstrap.css" />



соответсвенно создал таблицы в БД

в какой-то момент они даже заполнялись.

добавил права на выполнение




        public function accessRules()

        {

        return array(

            array('allow',

            	'actions'=>array('index','view', 'create','profile', 'savecoords', 'update',

                         'delete','password','index', 'admin',

                         'updatecity', 'updateregion', 'upload','search', 'gallery'),

                'roles'=>array('role_admin'),

            ),

            

            array('allow',

            	'actions'=>array('index','view', 'create','profile', 'savecoords', 

                          'update','delete','password','index', 'admin',

                          'updatecity', 'updateregion', 'upload','search', 'gallery'),

                'roles'=>array('role_user'),

            ),

            

            array('allow',

            	'actions'=>array('updatecity', 'updateregion', 'upload','search', 'gallery'),

                'roles'=>array('role_guest'),

            ),

            

            array('allow',  // allow all users to access 'index' and 'view' actions.

				'actions'=>array('index','view','search','gallery'),

				'users'=>array('*'),

			),

            

            array('deny',

                'users'=>array('*'),

            ),

        );

        }



если выключить стиль бутстрап

то пишет в БД, а вот отобржает не очень

4825

print.png

Вообще-то, со стилями что-то не так - посмотри скриншоты на странице расширения…

Если что-то не работает на клиентской части - в первую очередь надо смотреть в логи(например в Chrome Developer Tools если используется Chrome).

Прочитай документацию еще раз - сейчас у тебя во вью код для использования GalleryBehaviour а в контроллере нет(у тебя вообще $model во вью не передается).

Здорова!

Как жизнь?!

Я Бутсрап 2 версии подключил.

Ты какую рекомендуешь?

JS файлы обязательно в бутстрапа подлючать? или достаточно ограничется CSS.

Галерея сделана для второго бутстрепа. Да, JS подключать обязательно - без него не будет работать попап редактирвания информации о фото.

Не могу решить:(((

youtube .com watch?v=FtOsRcsC6XY - сылки не дает постить :))

вдруг станет понятнее,

на видео плохо видно

4834

30-10-2013 22-12-27.png

=========================================

В модель User вставил функцию


public function behaviors()

        {

            return array(

                'galleryBehavior' => array(

...



  • все таки планирую галлерею использовать во все возможных моделях (типа страны, регионы, новости)

вид формы модели User - пользователь имеет свою галлерею




    <?php

    if ($model->galleryBehavior->getGallery() === null) {

        echo '<p>Before add photos to product gallery, you need to save product</p>';

    } else {

        $this->widget('ext.galleryManager.GalleryManager', array(

                'gallery' => $model->galleryBehavior->getGallery(),

                'controllerRoute' => 'admin/gallery', //route to gallery controller

            ));

    }

    ?>



все это находиться в папке modules/admin - может с путями что перепутал???

Возможно ли права надо прописать в GalleryController?

например, в контроллере User прописано всякое




public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

			//'postOnly + delete', // we only allow deletion via POST request

        ...

        public function accessRules()

        {

        ...

           return array(

            array('allow',

            	'actions'=>array('index','view', 'create','profile', 'savecoords', 'update',

                         'delete','password','index', 'admin',

                         'updatecity', 'updateregion', 'upload','search', 'gallery'),

                'roles'=>array('role_admin'),

            ),

            ...




Может прав не хватает?

Ошибка там 500, мой этот хтасес




AddDefaultCharset UTF-8


RewriteEngine on


# if a directory or a file exists, use it directly

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d


# otherwise forward it to index.php

RewriteRule . index.php



ну и наконец, форма походу делает следующее,

берет фотографии, записывает имена в БД и все

не может копировать в папку и в конце требует файлы формта _**.jpg

получается не переименовывает

ничего не понял…

500 - это ошибка сервера, надо смотреть в логи (лог приложения и лог веб сервера).

Ну и вообще-то - сначала надо смотреть на ответ сервера(там же во вкладке Network если выделить запрос с ошибкой, можно посмотреть что пришло с сервера)

По ошибке - по видимому нет директории для сохранения фото (galleries в корне сайта).

Hello Bogdan,

First of I’m amazed how much effort you gave to this and still giving to support people using it.

We’ve developed a custom app and using your extension. It works flawlessly everywhere part from Internet Explorer where Add is not clickable at all, not even triggering browse dialog. I tried to exclude file input from span and everything else to have it lay there as default but then ajax is not triggering.

Any clue?

Thank you!

Доброго дня!

Подскажите люди добрые как можно модифицировать,

что бы он фотки как-то по папкам расскидывал.

Предположим все фотки будут в одной папке, храниться тогда при возникновении проблем, там такая каша будет капец.

поэтому, идельный вариант конечно, в папках по времени т.е.

год/месяц/ , но тоже как я понимаю проблемно,

поэтому может хотя бы по id gallery

вид будет что-то наподобии: gallery/1, gallery/2,

как вам идея,

в голову приход такое

public $galleryDir = ‘gallery/’.$this->gallery_id; // в модель добавть ID

  1. Но возникает вопрос достаточно ли этого?

  2. В какой момент создавать папку соответсвующую ID?

  3. Как привязать удаление фото и папок при удаление например статьи?

Hello,

Some time ago I have fixed bug with this button for ie10 (it was working only by using double-click) - which version of extension you are using?

Also, can you provide details about IE version? - I will try to reproduce, and maybe fix it.