Reorder images on Frontend

So I have an edit form on the frontend of the site for editing single tailor entries. I’ve gotten most of the functionality to work for uploading images, but I have no idea how to reorder images in the frontend like we do the backend.

I see that each image has a sort_order option, but I also noticed that it’s sorted by ALL the files uploaded. So I don’t want to touch that since I’m sure it would break things in the backend.

Can someone guide me in the right direction as to achieve this?

Hey @artistro08

This code might be a hint, it is the logic used in the FileUpload form widget:

public function onSortAttachments()
{
    if ($sortData = post('sortOrder')) {
        asort($sortData);
        $ids = array_keys($sortData);
        $orders = array_values($sortData);

        $fileModel = $this->getRelationModel();
        $fileModel->setSortableOrder($ids, $orders);
    }
}

It involves locating every ID for each file and passing the desired orders to the setSortableOrder method.

I hope this helps

1 Like

This does! Thank you. Much appreciated.

1 Like

I’m having trouble figuring out where this is in Tailor. Would you mind pointing me in the right direction?

I was actually able to sort things with this code via AJAX:

function onSortAttachments() {
    $rawSortData = input('sortData');
    $recipe_id  = input('recipe_id');
    $sortData = [];
    
    $images = EntryRecord::inSection('Content\Recipes')->find($recipe_id)->image;


    foreach(json_decode($rawSortData) as $index => $attachment) {
        $sortData[$attachment] = $index;

        $image = $images->find($attachment);
        if($image)
        {
            $image->sort_order = ($index+1);
            $image->save();
        }
    }

    Flash::success('Successfully Sorted Image!');
}

combined with some JavaScript on the frontend, things worked out!

1 Like