#Custom virtual field not working in Relationship select field (Create/Edit view)

10 messages · Page 1 of 1 (latest)

gray furnace
#

Hi everyone, I need help with customizing the display of a relationship field in the Admin UI.

I have a Classes collection with a relationship field pointing to the Users collection. I created a virtual field named *displayTitle *in the Users collection and set it as useAsTitle.

However, when I try to select a user within the Classes (Create/Edit view), the virtual field doesn't seem to work/display.

Here is my displayTitle field configuration:

gray furnace
#

`{
name: "displayTitle",
type: "text",
virtual: "lead.fullName",
admin: {
hidden: true,
},
hooks: {
afterRead: [
({ data, req: { user }, value }) => {
if (!data) return "";

        const fullName = value || "";
        const username = data.username || "";
        const isViewerTeacher =
          user?.role === ROLES.TEACHER_FULL_TIME ||
          user?.role === ROLES.TEACHER_PART_TIME;

        if (isViewerTeacher) {
          return fullName || data.id;
        }

        if (!fullName) return username || data.id;

        return username ? `${fullName} - ${username}` : fullName;
      },
    ],
  },
},`
violet dagger
#

this could be a simple depth issue

since your afterRead hook relies on value coming from virtual: "lead.fullName" —lead must be populated when the Users collection is queried

so when payload is trying to fetch the options for the relationship—its using limited depth, and if lead is not populated you get value of undefined

#

so I would check the depth on your Users collection query

gray furnace
#

I already check everything worked fine in the Cell View of that collection, but when i used Relationship Field "Users" in "Classes" Collection (Create/Edit view). The Relationship display at Select Input , the option in it only show the "lead.fullName"

violet dagger
#

ahhh—this is because the relationship field has no depth admin option, and the maxDepth field-level property is ignored by the UI component entirely, and in turn the lead relationship on the User is never populated.

The only workaround would to avoid relying on a nested relationship inside useAsTitle. Instead of virtual: lead.fullName, convert it into a real stored/computed field that gets written on save

e.g. an afterChange hook that copies lead.fullName into a flat displayTitle field. That way depth 0 is sufficient since the value is already on the document itself.

gray furnace
violet dagger
#

There's no better architectural approach at this time —so a migration script is unavoidable, but it's not bad at all with Payload's local API

#

Dump prod → import locally
Run the script against local copy
Verify the results look correct
Run against prod
Profit