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.

Prefill create fields

default discord avatar
itsjxcklast year
1

Is it possible to open to the create page and prefill a field?



For example if I did

res.redirect(payload.getAdminURL() + "/collections/<collection>/create?slug=test")

I'd like the

slug

field to be pre-filled with the value passed in



For anyone wanting to do something similar, I achieved this behaviour with a custom component:


import React, { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { useField } from "payload/components/forms";
import { UIField } from "payload/types";

import qs from "qs";

const FieldPrefill: React.FC<UIField> = () => {
  const { search } = useLocation();
  const parsedSearch = qs.parse(search, { ignoreQueryPrefix: true });
  const fieldAccessors = Object.entries(parsedSearch).map(([key, value]) => ({
    value,
    field: useField({ path: key }),
  }));

  useEffect(() => {
    for (const { value: prefillValue, field } of fieldAccessors) {
      const { value, setValue } = field;
      if (value === undefined) {
        setValue(prefillValue);
      }
    }
  }, [fieldAccessors]);

  return (
    <code style={{ display: "none" }}>{JSON.stringify(parsedSearch)}</code>
  );
};

export default FieldPrefill;
    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..