I couldn't get PatchEvent.from
to work at all for other fields inside a custom input component but useDocumentOperation combined with withDocument
from part:@sanity/form-builder
This is a rough working example using a custom component:
import React from "react";
import FormField from "part:@sanity/components/formfields/default";
import { withDocument } from "part:@sanity/form-builder";
import { useDocumentOperation } from "@sanity/react-hooks";
import PatchEvent, { set, unset } from "part:@sanity/form-builder/patch-event";
// tried .from(value, ["slug"]) and a million variations to upate the slug but to no avail
const createPatchFrom = (value) => {
return PatchEvent.from(value === "" ? unset() : set(value));
};
const ref = React.createRef();
const RefInput = React.forwardRef((props, ref) => {
const { onChange, document } = props;
// drafts. cause an error so remove
const {patch} = useDocumentOperation(
document._id.replace("drafts.", ""), document._type)
const setValue = (value) => {
patch.execute([{set: {slug: value.toLowerCase().replace(/\s+/g, "-")}}])
onChange(createPatchFrom(value));
// OR call patch this way
patch.execute([{set: {title: value}}])
};
return (
<input
value={document.title}
ref={ref}
onChange={(e) => setValue(e.target.value)}
/>
);
});
class CustomInput extends React.Component {
// this._input is called in HOC
focus = () => {
ref.current.focus();
};
render() {
const { title } = this.props.type;
return (
<FormField label={title}>
<RefInput ref={ref} {...this.props} />
</FormField>
);
}
}
export default withDocument(CustomInput);