Sorting by month name

,

How do I sort a collection in month order (calendar sequence, not alphabetic order)?

Product:
Wix Editor

What are you trying to achieve:
I have a site with monthly newsletters in a CMS collection. I want those to appear in date order (newest to oldest). I’m trying to keep it simple for the newsletter editor so they upload each month’s newsletter through a form supplying year and month. Sorting the collection by year (Z->A) is easy but the secondary sort, by month, is not (the alphabetic sequence is NOT the calendar sequence).

What have you already tried:
I have added a field “month number” with a two digit sort key but that is subject to data entry error. Can I derive this value from the month name somehow (editor selects January in Month field, background process enters “01” in the sort key field)?

Needs a bit of code. Create a backend hook to save the monthindex number when the form is saved.

something like this


export function Newsletters_beforeInsert(item, context) {
  return setMonthIndex(item);
}

export function Newsletters_beforeUpdate(item, context) {
  return setMonthIndex(item);
}

function setMonthIndex(item) {
  const monthMap = {
    january:   1,
    february:  2,
    march:     3,
    april:     4,
    may:       5,
    june:      6,
    july:      7,
    august:    8,
    september: 9,
    october:  10,
    november: 11,
    december: 12
  };
  
  if (item.monthName) {
    const key = item.monthName.toString().trim().toLowerCase();
    const idx = monthMap[key] || null;
    item.monthIndex = idx;
    
  }
  
  return item;
}

Thanks Dan. The code looks straightforward enough and I’m confident with managing that. The bit I don’t know about (never even really looked at it) is “Create a backend hook…”. I understand the concept (I’d have called it an “exit” before I retired but what’s in a name?). What I don’t know is how to link that into my form or data collection (both?) when using the simple Wix Editor. Is there a tutorial you could point me to?

here are some documents that may help

Thank you again Dan. That process has worked perfectly after a few tweaks to field ids (not field names as I learned) to match my collection. Just what I needed and simple enough to be able to hand over to my club where the level of IT knowledge is limited.

2 Likes

G’day Dan. Just for the record, I was creating another collection with the same requirement. I built a form to add the month and chose a different “dropdown” input element for that. While it won’t enforce the rule when adding records manually, this dropdown had two-part entries for each choice - a name and a value so it was possible to build it as January=1, February=2 etc., so the user sees the month name and the insertion process stores the sort index number in the collection.
Cheers, Murray