Search code examples
apostrophe-cms

Title field for joinByOne


I've used both joinByOne and joinByMany schema fields before, and was wondering if there is an equivalent to the titleField in the array type for the join types. Specifically, there are multiple places in my application where I am using a joinByOne to select a user (apostrophe-users type) for a particular page or piece. It would be great if there was a way to show a field (for example, their name or email) in the join field that shows up in the editor modal. Currently, the only things that are there are the edit/remove/rearrange buttons, with no text present in the rest of the grey box. Is there a way to specify a field to display in the join field in the editor modal? (example image below)

Example

Thanks!


Solution

  • First, I am surprised that you don't see anything at all as a label in the list. That suggests to me that you have either:

    (a) Used the projection filter to eliminate a lot of the properties of the joined documents, and left out title, or

    (b) Actually eliminated title from the schema for users.

    If you are doing (a), just add title to the projection. It won't impact speed in any significant way, really only areas and joins do that.

    If you are doing (b), you should add a beforeSave handler to construct title from the fields you prefer, i.e. firstName and lastName. Apostrophe expects title to exist for all types in many places, and there's no reason to fight it - you don't have to let the user edit it, but you do need to populate it in beforeSave. You can write a migration to fix this field for any existing users for which it currently is missing or just resave them.

    But having said that, what you want can be done directly as well in this case. Just create lib/modules/apostrophe-users/views/chooserChoice.html and populate it, like this:

    {% extends "chooserChoiceBase.html" %}
    
    {% block title %}{{ choice.firstName }}{{ choice.lastName}}{% endblock %}
    

    This is a great technique because it allows you to do fancier things like including images when the choice is an image, etc. Just bear in mind that you'll likely run into many other places where a title property just makes sense and you should always populate it and include it in projections.