Wednesday, July 21, 2010

Changing the Order of Fields in Archetypes

I wish I knew this 4 years ago.

When creating new content based on archetypes, I usually start by copying the base schema, or one of my own base schemas with something like MyNewSchema = BaseSchema.copy(). One thing that has been historically hard in my case is that the schema order in the code directly correlates to the order in which its displayed. This means that the base copied data always goes first when displayed, which was not always what I wanted. The solution was custom templates and blech all over.

Apparently you can just reorder these things. Deep in the bowels of archetypes there is a function called moveField. Now, reordering the schema can me as easy as MyNewSchema.moveField('description', pos='bottom').  Hot dog! Pasting the interface for reference.

6 comments:

  1. Looking for this was the impetus for one of my first forays into reading the Archetypes source code...I knew it *had* to exist somewhere. Thanks for mentioning. I see it's also now documented at the bottom of http://plone.org/documentation/manual/developer-manual/archetypes/introduction/archetypes-schemas

    ReplyDelete
  2. I always end up wrapping a tiny convenience function around this to pass a partial list of just the field names I want first, given some schema:

    def order_schema(schema, spec=[]):
    order = [name for name in spec] #partial list of fieldnames
    while len(order) > 0:
    #pop last fieldname, move to top, repeat
    schema.moveField(field_order.pop(), pos='top')

    ReplyDelete
  3. Well, comment formatting and a variable name was incorrect in code in my post above, but you get the idea.

    ReplyDelete
  4. @davisagli: It's amazing how nice documentation has become over the year. Thanks for the actual link!

    @Sean: I hope you know that in the very tiny plone community in San Diego you were like a yeti - often talked about but rarely seen :) Sounds like you are still bangin out plone sites - glad to hear it. And I'll def steal that snippet!

    ReplyDelete
  5. gist is the new hotness! Anyone for forwarding paste.plone.org to gist (instead of pastie.org)? :-)

    ReplyDelete
  6. @aclark I didn't even know we had that... big +1 for me!

    ReplyDelete