Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeystoneJS relationship type, limit available items by field value

Is it possible to limit available displayed options in a relationship type of KeystoneJS by specifying a value condition?

Basically, a model has two sets of array fields, instead of letting the admin user select any item from the field, I would like to restrict to only the items that are part of a specific collection _id.

like image 948
code_burgar Avatar asked May 14 '14 22:05

code_burgar


1 Answers

Not sure if this is exactly the feature you're looking for, but you can specify a filter option on the Relationship field as an object and it will filter results so only those that match are displayed.

Each property in the filter object should either be a value to match in the related schema, or it can be a dynamic value matching the value of another path in the schema (you prefix the path with a :).

For example:

User Schema

User.add({
    state: { type: Types.Select, options: 'enabled, disabled' }
});

Post Schema

// Only allow enabled users to be selected as the author
Post.add({
    author: { type: Types.Relationship, ref: 'User', filter: { state: 'enabled' } }
});

Or for a dynamic example, imagine you have a role setting for both Posts and Users. You only want to match authors who have the same role as the post.

User Schema

User.add({
    userRole: { type: Types.Select, options: 'frontEnd, backEnd' }
});

Post Schema

Post.add({
    postRole: { type: Types.Select, options: 'frontEnd, backEnd' },
    // only allow users with the same role value as the post to be selected
    author: { type: Types.Relationship, ref: 'User', filter: { userRole: ':postRole' } }
});

Note that this isn't actually implemented as back-end validation, it is just implemented in the Admin UI. So it's more of a usability enhancement than a restriction.

like image 64
Jed Watson Avatar answered Oct 15 '22 12:10

Jed Watson