Last active
July 16, 2024 12:23
-
-
Save tyteen4a03/2708e1b57c8f2c904032cc1cceb9b007 to your computer and use it in GitHub Desktop.
PayloadCMS Listener Field Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
name: "jobStopsListener", | |
type: "ui", | |
admin: { | |
components: { | |
Field: JobStopsListenerField, | |
}, | |
}, | |
}, |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { gql, useQuery } from "@apollo/client"; | |
import { useForm } from "payload/components/forms"; | |
import { useDocumentInfo } from "payload/dist/admin/components/utilities/DocumentInfo"; | |
import { Job } from "payload/generated-types"; | |
import { useEffect } from "react"; | |
import React from "react"; | |
const WarehouseIdQuery = gql(/* GraphQL */ ` | |
query WarehouseIdQuery { | |
Addresses(where: { type: { equals: warehouse } }) { | |
docs { | |
id | |
contactName | |
contactPhoneNumber | |
} | |
} | |
} | |
`); | |
const JobStopsListenerField = () => { | |
const { getDataByPath, addFieldRow } = useForm(); | |
const stopsField: number | Job["stops"] = getDataByPath("stops"); | |
const { versions } = useDocumentInfo(); | |
const warehouseQuery = useQuery(WarehouseIdQuery); | |
useEffect(() => { | |
const warehouseId = warehouseQuery.data?.Addresses.docs[0].id; | |
// check stopsField for being a number; workaround for https://github.com/payloadcms/payload/issues/4477 | |
if (!versions && (stopsField === 0 || (stopsField as Job["stops"]).length === 0) && warehouseId) { | |
// insert Warehouse as the first row, if no stops exist | |
addFieldRow({ | |
data: { | |
address: warehouseId, | |
contactName: warehouseQuery.data?.Addresses.docs[0].contactName, | |
contactPhoneNumber: warehouseQuery.data?.Addresses.docs[0].contactPhoneNumber, | |
}, | |
path: "stops", | |
}); | |
} | |
}, [addFieldRow, warehouseQuery, stopsField, versions]); | |
return <></>; | |
}; | |
export default JobStopsListenerField; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment