Best route for year entry in a document and handling height as input.

15 replies
Last updated: Dec 1, 2022
What would be the best route if I wanted an input in my document to be a year entry? Are there any helpers in Sanity for this? I tried searching
"year"
on the website and it isn't helpful when "year" is returning "learn" and "search" 😅 basically I want someone to be able to select a year from a dropdown or write a year in. However, I don't want to have to keep adding years and allowing just a string input seems dangerous in the sense that they could not enter a year
Dec 1, 2022, 2:18 AM
I think you’re wanting to have a drop down where users can select a year, upto and including the current year?
Dec 1, 2022, 2:42 AM
Correct and maybe even a future year
Dec 1, 2022, 2:43 AM
const lastTwentyYears = () => {
  const currentYear = new Date().getFullYear()

  let years = []
  for (var i = 0; i < 20; i++) {
    years.push((currentYear - i).toString())
  }

  return years.reverse()
}
Dec 1, 2022, 2:46 AM
This function would generate a list of the last 20 years (totally customizable to any number of years)
Dec 1, 2022, 2:46 AM
{
      type: "string",
      name: "year",
      title: "Year",
      options: {
        list: lastTwentyYears()
      }
    }
Dec 1, 2022, 2:46 AM
This field would use that list of years as options, creating a select item of the last 20 years
Dec 1, 2022, 2:47 AM
const yearsList = () => {
  const currentYear = new Date().getFullYear() + 20

  let years = []
  for (var i = 0; i < 40; i++) {
    years.push((currentYear - i).toString())
  }

  return years.reverse()
}
This example shows the last 20 years and the next 20 years
Dec 1, 2022, 2:48 AM
Ah that would work! I just need like to the last 5-6 and the next 5-6
Dec 1, 2022, 2:48 AM
I am making a dropdown for college recruiting class year so don't need to go that far
Dec 1, 2022, 2:49 AM
const yearsList = (future, past) => {
  const currentYear = new Date().getFullYear() + future

  let years = []
  for (var i = 0; i < (future + past); i++) {
    years.push((currentYear - i).toString())
  }

  return years.reverse()
}
Dec 1, 2022, 2:50 AM
Then you could call it as
yearsList(5, 5)
(5 years future, 5 years past)
Dec 1, 2022, 2:50 AM
Although “past” contains the current year, so it’s 10 years in total for this example
Dec 1, 2022, 2:51 AM
to ensure they select a year, you can add a validation rule,
validation: Rule => Rule.required()
Dec 1, 2022, 2:54 AM
Awesome! Thank you
Dec 1, 2022, 2:54 AM
Ok while I have you here, how would you handle a person's height as an input? A string or number 😅
Dec 1, 2022, 2:57 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?