Jump to content

Change image order through frontend


ttttim
 Share

Recommended Posts

I'm building an upload form for user to add images to a page. I would like for the user to change the image order after they add the images. Basically how the image field in the backend works. So users can drag and drop the image order. 

The problem is that I don't know how to rearrange the data of my image field based on the order a user submits?

 

Link to comment
Share on other sites

@ttttim

I haven't done it by myself, but there is $image->sort property.


// loop over images and set new sort position
foreach($page->images as $image) {
 $image->sort = $newSortPosition
}

// sort by the field 'sort'
$page->images->sort('sort'); 

$page->save();

 

  • Like 1
Link to comment
Share on other sites

17 hours ago, ttttim said:

I would like for the user to change the image order after they add the images.

If you mean the user sorts the new images before the form is submitted then you would add() the images to the field in the same order as they are arranged in your form and the order will be maintained.

If you mean it is a two step process...

  1. The user uploads images and they are added to the field
  2. The images that are in the field are listed and the user sorts them and submits the new sort

...then you can use the key (which is the image filename) of each image in the Pageimages WireArray to identify it. Your form would send an array (say it's named 'images_sorted') with each filename as key and sort order integer as value. Then when you process the form you would get each image in the field by key and add a new property to the image to hold its sort order (there isn't actually an existing property called 'sort' but you can add one). Then you sort the field by that property as @Zeka suggested.

$page->of(false);
foreach($images_sorted as $key => $value) {
    $page->images->get($key)->sort = $value;
}
$page->images->sort('sort');
$page->save();

 

Link to comment
Share on other sites

Thank, that worked like a charm!

I had to switch $key and $value though. 

$page->of(false);
foreach($images_sorted as $key => $value) {
    $page->images->get($value)->sort = $key;
}
$page->images->sort('sort');
$page->save();

 

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...