Gallery Manager extension

Форум вообщето англоязычный… желательно писать на английском.

  1. нет, многих проблем это не решит, все зависит от конкретного случая

  2. очевидно же - при создании галереи

  3. почитать код GalleryBehavior.php - там это уже есть

"тогда при возникновении проблем" - Для начала надо делать так чтобы таких проблем не возникало…

Потом - вообще-то в базе хранится информация о том какие фото и куда относятся, так что всегда можно разобраться… Если информации в базе все же не достаточно - ее туда не сложно добавить немного дописав расширение(например для того чтобы иметь дату загрузки фото, достаточно добавить к модели CTimestampBehavior и добавить соответствующее поле в базу )

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

Сейчас в расширении используется самый простой из возможных способов.

Да он имеет значительные недостатки, в отдельных случаях использования:

  • возможные лаги на некоторых файловых системах при очень большом количестве файлов

  • нет СЕО в именах картинок

  • есть возможность подбора url картинки

  • все файлы в галереях публичны …

В принципе его не сложно заменить - но для большинства случаев, его вполне достаточно, по этому пока что-то в целях сохранения совместимости я не хочу это менять.

Thanks Bogdan! Double click is launching browse dialog, though after selection of image, nothing happens.

I think this is the latest version of extension, if there is somewhere I can read to be sure, let me know.

Testing is done using IE 10.0.9200.16721

Many thanks!

Maybe, you are using not latest version. Just tried in IE 10.0.9200.16384 - it works. Try to upgrade extension, from here https://bitbucket.org/z_bodya/gallerymanager/get/tip.tar.gz and do not forget to clean assets.

Thanks Bogdan. You are right, it’s working with double click.

Cheers!

i user this extension but i can not know upload path and seem Nothing happens.

my controller action is:




        $gallery = Gallery::model()->findByPk(1);

        if (empty($gallery)) {

            $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->render('g6', array('gallery' => $gallery));




my view is:




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

                'gallery' => $gallery,

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

            ));




?>



4889

1.png

I have forked yii blog demo, and added some of my extensions to it.

So if need example how to use this extansion, there it is:

Hi Bogdan, your extension is great…you are a great!

i’m a newbie and i have some issue with the extension attached to my app.

some jquery doesen’t start, for example this if (l > 0)$editorModal.modal(‘show’); and other. To clarify my thoughts i want to test your demo blog (i have tested the old app), but how can i install with composer without a file composer.phar?

Thanks

You should not do this(of course you can download everything separately from repositories… - but is tedious task to do so)… Just go to http://getcomposer.org/download/ and download composer.phar.

About “some jquery doesen’t start, for example this if (l > 0)$editorModal.modal(‘show’); and other” - it looks like you need to include twitter bootstrap scripts on your page.

Thanks Bogdan, i solved partially with your demo blog.

But i have some problem with save the modal window.

It’s open when i click on pencil icon, but only close button works properly.

When i click on ‘x’ (top right) only class"modal-header" hide and doesn’t reopen ever after open a new window.

When i click on ‘Save changes’, the ajax seems doesn’t calling the action into the controller, the only difference than the other calls, it’s that the function call method $post. The Others call $ajax.

Strange…

Which bootstrap version are you using?

Originaly it was developed for bootstrap 2, and i have never tried to use it with bootstrap 3…

i’ve copied bootstrap folder from your demo blog, like all other files.

i’m think it’s strange but with this works:


  $('.save-changes', $editorModal).click(function (e) {

            e.preventDefault();

            /*

            

            $.post(opts.updateUrl, $('input, textarea', $editorForm).serialize() + csrfParams, function (data) {

                var count = data.length;

                for (var key = 0; key < count; key++) {

                    var p = data[key];

                    var photo = photos[p.id];

                    $('img', photo).attr('src', p['src']);

                    if (opts.hasName)

                        $('.caption h5', photo).text(p['name']);

                    if (opts.hasDesc)

                        $('.caption p', photo).text(p['description']);

                }

                $editorModal.modal('hide');

                //deselect all items after editing

                $('.photo.selected', $sorter).each(function () {

                    $('.photo-select', this).prop('checked', false);

                }).removeClass('selected');

                $('.select_all', $gallery).prop('checked', false);

                updateButtons();

            }, 'json');

            */

            

            $.ajax({

                type: 'POST',

                url: opts.updateUrl,

                //data: data.join('&') + csrfParams,

                data: $('input, textarea', $editorForm).serialize() + csrfParams,

                dataType: "json"

            }).done(function (data) {

	                var count = data.length;

	                for (var key = 0; key < count; key++) {

	                    var p = data[key];

	                    var photo = photos[p.id];

	                    $('img', photo).attr('src', p['src']);

	                    if (opts.hasName)

	                        $('.caption h5', photo).text(p['name']);

	                    if (opts.hasDesc)

	                        $('.caption p', photo).text(p['description']);

	                }

	                $editorModal.modal('hide');

	                //deselect all items after editing

	                $('.photo.selected', $sorter).each(function () {

	                    $('.photo-select', this).prop('checked', false);

	                }).removeClass('selected');

	                $('.select_all', $gallery).prop('checked', false);

	                updateButtons();

                    // order saved!

                    // we can inform user that order saved

                });

            

            


        });

i’m using this cms VinceG with some tricks, because there’s some issues and nobody keeps.

I’m sorry for my bad english

galleryManager.php


<a class="close" data-dismiss="modal">×</a>

The class close depends by bootstrap?

Yes, it is used to align close button in model heading.

About bootstrap from my demo - probably you did not noticed, but it is modified because of conflicts with yii demo styles…

So to use it - all bootstrap markup should be placed in container with "bootstrap" class.

Yep Bogdan, you terribly right!!

I had noticed after some code inspection.

I have a page like your demo with two extensions:

yii-image-gallery

yii-image-attachment

But now i have some problem with the progress bar during the upload.

It seems to be at the first step for all uploading and then closing when the modal window it’s opening.

Why?

Solved!!! There were some classes identical with your.

Не могу понять в чём дело…

Хочу вывести одну картинку:


<?php

class GalleryViewerItem extends CWidget

{

    /** @var Gallery Model of gallery to manage */

    public $gallery;

    /** @var string Route to gallery controller */

    public $controllerRoute = false;

    public $assets;

    public $gallerypath;

    public $htmlOptions = array();


    /** Render widget */


    public function run()

    {


        $this->render('galleryViewerItem', array('photos'=>$this->gallery->galleryPhotos, 'groupalias'=>$this->gallerypath));

    }


}

galleryViewerItem:




<ul class="thumbnails">

    <?php foreach($photos as $photo): ?>

        <li class="span3"><a class="<?php echo $groupalias; ?> thumbnail" href="<?php echo $photo->url; ?>"><img src="<?php echo $photo->getUrl("small"); ?>" alt="<?php echo $photo->name; ?>" /></a></li>

    <?php endforeach; ?>

</ul>



Всё окей, всё хорошо.

Но если в виде я напишу так:


<ul class="thumbnails">

    <li class="span3"><a class="<?php echo $groupalias; ?> thumbnail" href="<?php echo $photos[0]->url; ?>"><img

                src="<?php echo $photos[0]->getUrl("small"); ?>" alt="<?php echo $photos[0]->name; ?>"/></a></li>

</ul>

У меня слетает макет. Картинка выводится, всё хорошо, но макет (layout) слетает. Почему так происходит?

Как именно он "слетает"? Что в логах?

Скорее всего: $photos - или пустой или в нем нет элемента с нулевым индексом.

первый элемент незная его ключ можно получить например так: "array_shift(array_values($photos))"

В runtime/application.log — чисто.

В данный момент вызываю вот так:




<?php

$photo = array_shift(array_values($photos));

?>

<a class="<?php echo $groupalias; ?> thumbnail" href="<?php echo $photos->url; ?>">

    <img src="<?php echo $photo->getUrl("small"); ?>" alt="<?php echo $photo->name; ?>"/>

</a>



И тоже макет слетает.

Под «слетает» я имею ввиду, что не показывает вид из папки layouts. Т.е. генерируется всё (у самого контроллера данные показываются), а всё что указано в layout — не выводит.

Методом тыка убрал функцию getUrl из вывода — макет возвращается. Возвращаю функцию — макет слетает. Признаков конфлитка не нашёл. Может, когда мы вытаскиваем отдельный массив, функция как-то иначе работает? К сожалению, не силён в php, новичок.

Ладно, не знаю, рационально ли, но сделал в следующем виде (может кому-нибудь понадобится).

В своей модели:




 'photos' => array(self::HAS_MANY, 'GalleryPhoto', array('gallery_id'=>'gallery_id'), 'order' => '`rank` asc'),



У каждой записи есть gallery_id, который одинаков с таблицей gallery_photo.

Ну и вывожу:




$photos = $data->photos;

$photo = $photos[0];

echo '<img src="/' . $photo->galleryDir . '/' . $photo->id . 'small.jpg" />'

echo 'Количество фотографий: '.count($photos)



Конечно, прощай функция getUrl и остальные функции, но не страшно. А получаю все картинки по простой причине — нужно знать количество (хотя, можно производить поиск через find по модели GallerPhoto — но что производительнее: получать через жадную загрузку с помощью связей, или ещё отдельный запрос (find)?).

Hello Bogdan, nice extension, I have it working fine in my project.

I don’t know if you are still maintaining it, but I have a question about the galleryDir. Actually my galleryDir is in ‘webroot’/images/galleries, which is a folder accessible for Apache (so it can save/read files on that directory), but this makes files accessible via web without any kind of security.

I have these requirement: I have different "groups" of users, and files have to be accessible ONLY for logged users of the corresponding group.

Based on your experience what would you recommend me to do?

Creating a directory inside the protected directory and managing images as assets?