Like what we’re doing? Star us on GitHub!

useAsTitle a field (not id) from a relationship

Lloyd
3 weeks ago
2

Hello guys, I was wondering if there is any built-in way to do this:



I have 2 collections, UserCourses and Courses.

UserCourses

has a relationship to

Courses

.



I wanted to use as the title for each

UserCourses

record, the title of the course it has a relationship for (example:

Course.title

instead of the ID of the

Course

).



I uploaded a couple of screenshots to explain better what I'm trying to do. Thank you!

2023-02-23_10-43.png
2023-02-23_10-44.png
  • jesschow
    Payload Team
    3 weeks ago

    Hi @Lloyd useAsTitle does not support nested fields currently, we will commonly use a virtual field to get specific data for your document title. For example:



        {
          name: 'title',
          type: 'text',
          admin: {
            hidden: true,
          },
          hooks: {
            beforeChange: [
              ({ data }) => {
                return data.course.title;
              }
            ],
          },
        },


    Then you would set

    useAsTitle: 'title'
  • Lloyd
    3 weeks ago

    Hi, it seems like a really good solution, thanks a lot!



    I've encountered only one problem, in my case

    data.course.title

    did not contain the title of the course, here's the output of

    data

    :


    {
      tier: 'base',
      user: '63c66090c20a548b1c0a325b',
      title: '',
      course: '63f4835d1c09415657bfccff'
    }

    But I fetched it like this


        {
          name: 'title',
          type: 'text',
          admin: {
            hidden: true
          },
          hooks: {
            beforeChange: [
              async ({data}) => {
                const req = await fetch(`${process.env.URL}/api/courses/${data.course}`)
                  .then(res => res.json())
                  .then(data => {
                    return data.title
                  })
                return req
              }
            ]
          }
        }


    And now everything works well

Open the post
Continue the discussion in Discord
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More