Search code examples
pluginskeystonejs

Sample code for KeystoneJS 5 custom fields?


I'm interested in writing custom fields for KeystoneJS 5. The documentation is here, but I find it somewhat opaque (i.e., not fully explicatory). Is there sample code available? I looked in 'demo projects' and 'test projects' in the Keystone repo, but didn't see anything.


Solution

  • KeystoneJs custom fields are poorly documented and not easily accessible. in fact the whole concept of writing the whole custom field may be overkill.

    here is the example one core team member has put copied form the test-project. - https://github.com/MadeByMike/keystone-custom-field/blob/7caf0139c189eadda1884a86073c6945bdd6ff05/index.js#L15

    this is what you need to do: 1. you need to create a folder for the field 2. you can copy the Text field implementation to start with 3. there index.js file must export specific object (default export) like this ( I have added some comment for each line)

    {
      type: 'Stars', // name of the implementation
      implementation: Stars, // implementation itself
      views: { // all views are required you can copy the implementation from Text field)
        Controller: Integer.views.Controller, // it is using controller from Integer field type
        Field: require.resolve('./views/Field'), // field which goes into edit page or create dialog
        Filter: Integer.views.Filter, // this adds filters in the list page
        Cell: require.resolve('./views/Cell'), // view for list page where you usually see the text, for Relationship it is rendered as link.
      },
      adapters: {
        mongoose: MongoIntegerInterface, // mongoose adapter specific inplementation
        knex: KnexIntegerInterface, // knex adapter specific implementation,.
      },
    }
    
    1. create views for each type (Field, Filter, Cell etc.)
    2. import the field (default import) in the schema definition and use it like regular field. any custom option is passed on to the custom implementation.