sanity

How to set a field with options based on another reference field


To give you a bit of context, I have have a CTA type that can reference a page of the website, but I'd like to have the option to add an anchor and I am not sure what is the best way to achieve this.

So far the CTA has a reference field to a page document. One option would be to have anchors as documents as well. But once the page is selected, I want to make sure I only show the anchors used on this specific page. Not all anchors. I believe it is possible with a filter option using a client query but I don't find how to do this exactly.

I really I would rather keep anchors as objects and when a page is selected, I populate a string field option list with the anchor strings belonging to the specific page.

Sorry my explanation might not be great but I feel this seems like a common enough scenario, so I'd hope somebody has already found a good setup for this and share it with me.

For the moment I have a field roughly setup like this for my CTA link.

{
  title: 'Page / Anchor',
  name: 'page',
  type: 'reference',
  to: [
    { type: 'basicPage' },
    { type: 'anchor' },
  ],
  weak: true,
  options: {
    disableNew: true,
  },
},

And it means I let the person choose to link either a page or an anchor. This works alright when there is no 2 pages with the same anchor name because anchors need to be documents with a unique slug.

I can see scenarios where this could be limiting and I was wondering if there was a way to let the editor only pick a page. And once the page is selected, another field appears with the list of anchors on that page (which are stored in a field of the page) and we have the choice to either leave it blank or pick one in the list.

I could add a simple text field to add the slug of the anchor manually. But it is not great for non-technical people to have to remember a slug and spell it correctly.


Solution

  • I presume that you are wanting to link to the heading elements as landmarks so that you can add it to the site url i.e. /post1#heading

    If this is the case then you would need to create a custom component for the CTA. The component would have the referenced document within the props and the custom component would need to read through the portableText (yet again another presumption as this is typically how data is stored) and find the headings, then give you a list that you could select from. This would then be Set against another value.

    If this is not what you are wanting, then you will need to clarify your question possibly with some code examples of your CTA schema