Programmatically reorder children in a folder (Plone 5)

I'm looking for a way to programmatically set the order of items in a folder, assume Plone 5 with dexterity based containers/folders. I think this is called Position in parent.

1 Like

Adapt the folder with IExplicitOrdering - using the adapter you can move things around.
Look at https://github.com/plone/plone.folder/blob/master/src/plone/folder/interfaces.py#L48 for its API
I'am not sure if this is in docs.plone.org - google does not give any result (I tend to look at the interfaces for such things).
If not it would be great if you or someone else could write some lines about it so we can point in future people to the docs.

Thanks @jensens, will look at this. Feels like a good candidate for adding to the Plone API.

In Plone 4 there was a product that did this: https://github.com/collective/collective.sortmyfolder
Maybe there is something you can reuse from there?

In Plone 5, you have the reaarange button in /folder_contents
I am not sure where this code is, but try plone.app.content/browser/folder.py, maybe or https://github.com/plone/plone.app.toolbar/blob/master/plone/app/toolbar/browser/folder.py#L516

I am not sure, it sounds more like to be part of the stuff Plone developers do 20% of the time
But it would be nice if you document your findings in the docs

1 Like

Yeah, it's a really rare use case, probably not worth cluttering up (and having to maintain) in the API

Reasonable.

It was suprisingly easy (at least for my use case). I needed to reorder folders that were part of my navigation bar after creating them programmatically, I wanted to make sure they were in the order that I wanted.
It turns out that the portal object has a built in method called "moveObjectsToTop".

Here's the hardcoded version::

def order_items():
    portal = api.portal.get()
    navbar_items = ['about-us','services','forum','contact']
    navbar_items.reverse()
    for item in navbar_items:
        portal.moveObjectsToTop([item])

To improve on this you'd want to abstract out the hardcoding of the navbar_items. But this is good enough for me as part of an installation script.

2 Likes

Wrote some code to make our life easier when need to reorder menu:

Delayed question, but why not just create them in the order you want them to appear?

I'm sure there was a sane reason at the time.

2 Likes