Linking field values #397
-
Is it possible to link fields in a way where the input event on one can trigger the value to change in another field? It looks likes it's possible using Collection hooks, but it wouldn't be reactive and the target field would only update on save. My use case is I want to populate a As an aside, is it possible to set attributes on a field's Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey @slavanossar — this is absolutely possible. You're right in that you can use collection hooks to modify field values on the server-side, on save, but for your case, you're likely to benefit more from client-side component-based implementation. Yep - custom components are the way to go. Something like this: import React, { useEffect } from 'react';
// You can import the text input on its own if you have [email protected]
import { TextInput, useWatchForm, useField } from 'payload/components/forms';
const CustomTextInput = ({ name, path, label }) => {
// This will be documented more fully once we have the API solidified
// But for now, you can take a look at Payload's source code or use TS to see what
// is available here.
// `useWatchForm` is going to update every time **any** field changes so you'll always
// have an up-to-date copy of your title field's data
const { getDataByPath } = useWatchForm();
const {
showError,
value,
setValue,
} = useField({
path,
enableDebouncedValue: true,
});
// Grab your title's field value
const titleValue = getDataByPath('title');
// When your title field changes, set the value of your field
useEffect(() => {
setValue(titleValue);
}, [setValue, titleValue]);
return (
<TextInput
path={path}
name={name}
value={value as string || ''}
label={label}
showError={showError}
/>
);
};
export default CustomTextInput; How's that? Note, Payload's built-in |
Beta Was this translation helpful? Give feedback.
Hey @slavanossar — this is absolutely possible. You're right in that you can use collection hooks to modify field values on the server-side, on save, but for your case, you're likely to benefit more from client-side component-based implementation.
Yep - custom components are the way to go. Something like this: