Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

useAsTitle a field (not id) from a relationship

default discord avatar
___lloyd2 years 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!

  • default discord avatar
    jessrynkar2 years ago

    Hi

    @765140200438366209

    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
    ___lloyd2 years 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

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.