useAsTitle a field (not id) from a relationship

default discord avatar
Lloydlast year
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!

  • discord user avatar
    jesschow
    last year

    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'
  • default discord avatar
    Lloydlast year

    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

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.