Custom button to create new entry in collection

default discord avatar
douggieo
8 months ago
3

I'm experimenting with a workaround for a "content staging" feature I'm trying to implement. Essentially I need to put a custom button (either in the list or the document edit screen) that when clicked, creates a new entry in a different collection based on the data in current document. What's the best way to do that?



I've created the button with a UI field and tried using the local API to do this, but I get an error

payload__WEBPACK_IMPORTED_MODULE_1__.default.create is not a function

. I think I'm not using it correctly, is this designed to only work with hooks? Should I use graphql instead? An entirely different approach?



Code below for the ui field custom component... any help/examples appreciated. Thanks!



import React from "react";
import { useDocumentInfo } from "payload/components/utilities";
import payload from "payload";

async function createStagePage(docData) {
  await payload.create({
    collection: "stagePage",
    data: {
      title: "testTitle",
    },
  });
}
type Props = { label: string };
const StageField: React.FC<Props> = (props) => {
  const docinfo = useDocumentInfo();
  const clickHandler = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
    const returnObj = {
      fields: docinfo.collection.fields,
      id: docinfo.id,
    };
    createStagePage(returnObj);
  };
  return <button onClick={clickHandler}>Content Stage</button>;
};
export default StageField;
  • discord user avatar
    denolfe
    Payload Team
    7 months ago

    The local API is server-side only, you'll need to hit the REST API using fetch.



    Here is a component that queries another collection that you may be able to use some code from:

    https://github.com/payloadcms/public-demo/blob/master/src/components/CategorySummary/index.tsx
  • default discord avatar
    hai_q_28
    last month

    I'm trying to implement something very similar, have you had any success with that and if yes how did you solve it?

  • default discord avatar
    douggieo
    last month

    We ended up going a different direction and I did not get anywhere with that, sorry.

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.