Jump to content

Sorting images in Backend


HannaP
 Share

Recommended Posts

Hello all,

My page has a lot of images. I created a gallery_image field to upload and display them. Unfortunately they are sort of unordered in the backend, though the filenames are numbered sequentially. I understand that this reflects the order of finished uploads. I figured out how to sort them on the frontend, but is there a way to do the same in backend?

I guess this HookAfterPagesSave.module
found here https://processwire-recipes.com/recipes/extending-page-save-process/
might do the trick but I'm too new to processwire and too unexperienced in coding to see what code to write.

Anyone can help?
Thanks in advance
Hanna

Link to comment
Share on other sites

This is what would need to be in the afterSaveReady function. But keep in mind that this will deny any attempt to sort images in the backend manually. 

// Get the soon to be saved page object from the given event
$page = $event->arguments[0]; 

// Sample condition and changes
if($page->fields->has("images")){
    $page->images = $page->images->sort("basename");
    // Page will be saved right after this hook, so no need to call save().
    // Every other page you load and edit here needs to be saved manually.
    $this->message("Images have been sorted");
}
  • Like 1
Link to comment
Share on other sites

Hi Hanna,

I have used another approach on a site with many images where the user want his images sorted in alphabetical order only initially, but want to be able to reorder them manually later on a bit.

Maybe this sounds a bit clumpsy now, but we have added a link for the imagesorting to the frontpage only for superusers or imageauthors, like with the common edit-this-page link in PW's default site-profiles:

if ($page->editable()) {  // add edit link(s) to it, if the current user has edit rights
    $s .= "<li class='left'><a id='editpage' title='diese Seite bearbeiten' href='" . wire('config')->urls->admin . "page/edit/?id={$page->id}'><i class='fa fa-edit fa-lg'></i></a></li>\n";
    if ('gallery' == $page->template) {  // add an imagesort-link to it, if it is a gallery page
        $s .= "<li class='left'><a id='editpageSortimages' onclick=\"return areUreallySure('Bilder für dieses Archiv ({$page->archivnummer}) jetzt alphabetisch sortieren?');\" title='sortiere Bilder alphabetisch' href='/pwSortPageimages.php?id={$page->id}'><i class='fa fa-sort-alpha-asc'></i></a></li>\n";
    }
}

So, from the backend the user has to click on the view button first, then in frontend click the sort-my-images button, which calls the following bootstrap-script which resides in the pw root (pwSortPageimages.php):

<?php

// define userroles that are allowed to work with this script, like: superuser|editor|author
$userRolesSelector = 'superuser|publisher|author';

//-------------------------------------------------------------------------------------------//

// check if we have got an id
$pageId = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : false;
if (false===$pageId) {
	header('HTTP/1.1 403 Forbidden');
	exit(3);
}

// bootstrap PW
require_once(dirname(__FILE__) . '/index.php');

// check user-account
$validUser = false;
$roles = explode('|', $userRolesSelector);
foreach($roles as $role) {
    if (wire('user')->hasRole($role)) $validUser = true;
}
if (!$validUser) {
	header('HTTP/1.1 403 Forbidden');
	exit(2);
}

// check if id points to a valid page
$p = wire('pages')->get($pageId);
if ($p->id != $pageId || 'gallery' != $p->template) {   // check for a valid page id and also if the template matches the a gallery page
	header('HTTP/1.1 403 Forbidden');
	exit(1);
}

// now we reset the order for the images field (change the name of your field if it is not named: images)
$p->of(false);
$p->images->sort('name');
$p->save();

// and redirect to the page edit screen
$url = wire('pages')->get(2)->url . "page/edit/?id=$pageId";
header("location: $url");
exit(0);

This way the user has to click two times more if he want to sort his images in alphabetical order, but it gets only triggered on demand, plus the user can reorder them afterwards.

The link to start the sorting can also be injected into the admin-editscreen, what would be a bit nicer and saves one click.

Link to comment
Share on other sites

@horst

That sounds definitely clumpsy. What about some buttons in the page editor? Put this as is in /site/ready.php:

$wire->addHookAfter("ProcessPageEdit::buildForm", function(HookEvent $event){
	$process = $event->object;
	$form = $event->return;
	$page = $process->getPage();

	// Update to fit your fieldnames
	$imageFields = array("images");

	$multiple = $page->fields->find("name=" . implode($imageFields))->count() > 1;

	foreach ($imageFields as $field) {
		if($page->fields->has($field) && $page->editable($field)){

			if(wire('input')->post("hook_sort_$field")){
				$page->of(false);
				$page->set($field, $page->get($field)->sort("basename"));
				$page->save($field);
			}
			
			$button = wire('modules')->get("InputfieldSubmit");
			$button->attr("id+name", "hook_sort_$field");
			$button->value = __("Bilder Sortieren");
			$button->value .= ($multiple ? " (" . $field->get("label|name") . ")" : "");
			$button->icon = "sort-alpha-asc";
			$button->addClass("ui-priority-secondary");

			$form->insertBefore($button, $form->get("id"));
		}
	}
});
Edited by LostKobrakai
Small changes to the order
  • Like 6
Link to comment
Share on other sites

@LostKobrakai,

yes its definetly clumpsy, it is a solution from my early PW days where I wasn't able to inject buttons into the admin and I believe the ready.php wasn't introduced. :)

Your code is the perfect, none-clumpsy addition to the bootstrap-sorting-script. ^-^

Link to comment
Share on other sites

@LostKobrakai

This is awsome!

Thanks so much for this piece of code. I still have to learn a lot till I can do this on my own.

Works like a charm ... I only had to update my PW from master 2.6.1 to the dev branch (Use of ready.php requires at least PW 2.6.7 I guess).

The module code you helped me with in your first answer would probably do, but adding an extra button is of course much nicer.

@horst

Thank you very much for your code as well.

I'll take it to study how things work in PW. Maybe it helps me with other tasks later on ...

Again ... Thanks to both of you.

  • Like 3
Link to comment
Share on other sites

I only had to update my PW from master 2.6.1 to the dev branch (Use of ready.php requires at least PW 2.6.7 I guess).

You could still create a simple module to implement the functionality without using ready.php. Just replace the hook and the function in the save snippet you linked. Further information about hooks are also to be found here: http://processwire.com/api/hooks/

  • Like 1
Link to comment
Share on other sites

  • 4 weeks later...

hi LostKobrakai,

thanks for that cool snippet of code! I will use it on my next project. unfortunately the button appears an all tabs of the admin (also on children, delete, settings...).

how can we hide the button on the other tabs?

Link to comment
Share on other sites

ah, of course! thank you :)

changed it to this:

$form->insertAfter($button, $form->get($field));

edit: got an error on unpublished pages so i excluded the button there:

$process = $event->object;
$form = $event->return;
$page = $process->getPage();

if($page->is(Page::statusUnpublished)) return; // added this line
Link to comment
Share on other sites

  • 2 weeks later...

I'm using it with insertBefore the image field and it works fine, regardless of PageStatus.

I also have added two lines to the AdminCustomFiles/AdminThemeXXXXX.css files to move it to the right:

#wrap_hook_sort_images { float: right; }
#wrap_hook_sort_images:after { clear: both; }

post-1041-0-86200700-1447064457_thumb.jp

Such a nice and helpful snippet from @LostKobrakai, I really love it.  ^-^:lol:

  • Like 4
Link to comment
Share on other sites

  • 2 months later...

@lostkobrakai

can you confirm that when clicking this button the page is NOT saved. so if you edit other fields the changes will get lost. any way to change this behaviour?

the reason is i created a button "create invoice" for a client and if he changes some fields (address for example) and clicks the button "create invoice" without saving the page before this changes will get lost :(

Link to comment
Share on other sites

  • 1 month later...

ok last time it was not critical but now it was, so i implemented this little hook to check unsaved changes via javascript when clicking on the button defined at line

var buttons = '#button_example_id';

when the user clicks the button the confirm-dialog appears

post-2137-0-40176400-1456174163_thumb.pn

code:

/**
 * show warning message on button click if there are unsaved changes in the form
 **/
public function confirmUnsavedChanges($event) {
    $page = $event->object;
    // only add this to admin pages
    if($page->template != 'admin') return;

    ob_start(); ?>
    <script type="text/javascript">
        $( document ).ready(function() {
            
            // buttons to observe
            var buttons = '#sendLoginLinkButton, #newInvoice';

            $('body').on('click', buttons, function(e) {
                var msg = InputfieldFormBeforeUnloadEvent(true);
                if(typeof msg != "undefined" && msg.length) {
                    if(!confirm(msg)) {
                        e.preventDefault();
                        return false;
                    }
                }
            });

        });
    </script>
    <?php
    $script = ob_get_clean();
    $event->return = str_replace("</body>", $script."</body>", $event->return); 
}
  • Like 1
Link to comment
Share on other sites

  • 1 month later...
  • 4 years later...
On 11/9/2015 at 11:25 AM, horst said:

I'm using it with insertBefore the image field and it works fine, regardless of PageStatus.

I also have added two lines to the AdminCustomFiles/AdminThemeXXXXX.css files to move it to the right:


#wrap_hook_sort_images { float: right; }
#wrap_hook_sort_images:after { clear: both; }

 

@horst

are you still using this hook with the latest PW version?
I'm trying to display the button on the right like you, but it's just not displayed on the right. 🤔

I must confess I do not use the module "AdminCustomFiles" now however it should go with this Hook nevertheless also?

$wire->addHookAfter('AdminTheme::getExtraMarkup', function (HookEvent $event) {
	$parts = $event->return;
	$parts['head'] .= '<style type="text/css">
		#hook_sort_images { float: right; }
		#hook_sort_images:after { clear: both; }
	</style>';
	$event->return = $parts;
});

But it does not currently...

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...