Skip to content

Instantly share code, notes, and snippets.

@JedWatson
Last active April 18, 2020 05:50
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save JedWatson/11218381 to your computer and use it in GitHub Desktop.
Save JedWatson/11218381 to your computer and use it in GitHub Desktop.
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
Copy link

jlopezr commented May 8, 2014

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

@starsinmypockets
Copy link

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

@jjakshay
Copy link

jjakshay commented Feb 2, 2016

Will it populate cities in Admin UI without update script ?

@metinata
Copy link

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

Could you provide an update or fix?

@JedWatson

@phiricharles101
Copy link

phiricharles101 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

@codehunter12345
Copy link

codehunter12345 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