Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of how to use the filters option for Relationship fields
// A global file to provide the countries and cities
exports.countries = [{
name: 'Australia',
cities: ['Melbourne', 'Sydney', 'Canberra']
}, {
name: 'España',
cities: ['Madrid', 'Barcelona', 'Sevilla']
}, {
name: 'Italia',
cities: ['Roma', 'Venecia', 'Turin']
}];
// Shorthand code to create models with a filtered relationship.
var _ = require('underscore'),
countries = require('countries').countries;
new keystone.List('City').add({
name: String,
country: { Types.Select, options: _.pluck(countries, 'name') }
}).register();
new keystone.List('Person').add({
name: String,
country: { Types.Select, options: _.pluck(countries, 'name') },
city: { type: Types.Relationship, ref: 'City', filters: { country: ':country' }
}).register();
// Example of an update script that will populate the Cities model
var _ = require('underscore'),
countries = require('countries').countries;
var cities = exports.cities = _.flatten(countries.map(function(country) {
return country.cities.map(function(city) {
return { country: country.name, name: city.name };
});
}));
exports.create = {
City: cities
}
@jlopezr

This comment has been minimized.

Copy link

commented May 8, 2014

Nice example! It is just what I was looking for. This deserves to be in the documentation.

@starsinmypockets

This comment has been minimized.

Copy link

commented Mar 27, 2015

Think you're missing a semicolon at Model.js line 14 ;)

@jjakshay

This comment has been minimized.

Copy link

commented Feb 2, 2016

Will it populate cities in Admin UI without update script ?

@metinata

This comment has been minimized.

Copy link

commented Jul 22, 2017

Filters option has broken in Admin UI.
This example doesnt work.

Could you provide an update or fix?

@JedWatson

@phiricharles101

This comment has been minimized.

Copy link

commented Dec 1, 2017

This example did not work for me.
And for the update.js line 8, it needs to be
return { country: country.name, name: city };
As cities does not have attribute name in Countries.js
@JedWatson

@vahidahmad

This comment has been minimized.

Copy link

commented Jul 24, 2019

@JedWatson what if I want to get the list of countries from a database? How to asynchronously get data from the database before keystone start?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.