Netlify CMS relation widget with a list
As I was using Netlify CMS, I wanted to use a relation widget that would dynamically add content depending on the other collection title field.
It's really easy to do this, but I struggled a little bit with it because the documentation wasn't so explicit, and I could not find something useful on the internet.
So here's how you do it:
This is the collection that will have dynamic content, depending on how many call-to-actions you'll create.
- name: 'call-to-action'
label: 'Call to action'
path: "{{slug}}"
create: true
folder: 'content/call-to-action'
fields:
- {label: 'CTA Category', name: 'ctaCategory', widget: 'string'}
- label: 'CTA Content'
name: 'cta'
widget: 'list'
fields:
- {label: 'Title', name: 'title', widget: 'string' }
- {label: 'Content', name: 'content', widget: 'string' }
- {label: 'cover', name: 'cover', widget: 'image', media_folder: '/assets/images/covers/'}
- label: 'Button'
name: 'button'
widget: 'object'
fields:
- {label: 'url', name: 'url', widget: 'string'}
- {label: 'title', name: 'title', widget: 'string'}
And now we have to link this collection to a field in the blog collection. The field in the blog collection looks like this :
- { label: 'Call to action category',
name: 'ctaCategory',
widget: 'relation',
collection: 'call-to-action',
search_fields: ["ctaCategory"],
value_field: "cta.*",
display_fields: ["ctaCategory"]}
The search will be done depending on what "ctaCategory" you select, and to get all the items in the list widget from the "call-to-action" collection, we need to specify in the value field that we want to get every item, and you do this with ".*".
That's all .