Prefill create fields

default discord avatar
itsjxck
last month
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;
    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.