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.

Custom button to create new entry in collection

default discord avatar
douggieo2 years 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
    2 years 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_28last year

    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
    douggieolast year

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

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.