How can i Send collections id to custom component ?

default discord avatar
anisulislampranto
2 months ago
14

So this is a field of a collection. Now what i want is to send the id of the a collection let's say i have collection buses now id of a bus i want to send to the custom component.



like we can get data of fields using const [fields, dispatchFields] = useAllFormFields();



here i also want the id. which is not here.

  • default discord avatar
    notchr
    2 months ago

    This may be a scenario for a collection hook, like beforeUpdate or beforeRead



    Because you won't know the ID ahead of time



    Then again, in this case, if the collection isn't changing, you could just manually pass the collection ID

  • default discord avatar
    anisulislampranto
    2 months ago

    how can i do that ?

  • default discord avatar
    notchr
    2 months ago

    Well once you make the collection, you can view the ID in payload



    So if you just need the ID for this instance - create the collection, view it in payload to grab the ID

  • default discord avatar
    anisulislampranto
    2 months ago

    ahh get it. but this is not the way i want. because i'll have more then one collection for sure.

  • default discord avatar
    notchr
    2 months ago

    @anisulislampranto How about a virtual field



    const getCollectionID: FieldHook = async ({ data }) => (
      `${data.id} // maybe _id?
    );


          hooks: {
            afterRead: [
              getCollectionID,
            ],
          },


    err



    {
      name: 'collectionId',
      type: 'text',
      hooks: {
        beforeChange: [
          ({ siblingData }) => {
            // ensures data is not stored in DB
            delete siblingData['collectionId']
          }
        ],
        afterRead: [
          ({ data }) => {  
            return `${data._id}`; // might be .id, i forget
          }
        ],
      },
    }
          


    Not the best example, but hooks I think can help you out

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

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