Auto-Populate Fields #471
-
I am currently building a personal blog using Payload and, honestly, it's been an enjoyable process. The config structure is clean and easily understandable, and the documentation is fantastic. However, I can't seem to find any documentation on how I should go about creating fields that can be generated through JavaScript. I have created a custom field to serve as the URL slug of a post, currently its used by manually typing out the title of the post in a URL safe format in the custom field. Though ideally it would use JavaScript to analyse the title and convert it to a URL safe string, auto-populating the slug and displaying it in the admin UI in a disabled text field. So basically my question is how to set the value of a field in JavaScript based on the value of another field? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Hey @peniswafflexd Glad to hear of your successes so far. Fortunately, what you describe is a common feature and pretty simple to setup. Since you already have a custom field, you're half way there. To read the current value of another field in your document, use the To go the extra mile, you can also import Payload's import React from 'react';
import { useWatchForm } from 'payload/components/forms';
import CopyToClipboard from 'payload/dist/admin/components/elements/CopyToClipboard';
import { UIField } from 'payload/dist/fields/config/types';
export const AppUrlField: React.FC<UIField> = () => {
const { getDataByPath } = useWatchForm();
const title = getDataByPath('title');
const kebabTitle = title; // convert your title to a kebab-case string here, there are many ways to do this
const href = `https://yourapp.com/${kebabTitle}`; // swap in your own top-level domain here
return (
<div>
<div>
<span>
APP URL
</span>
<CopyToClipboard value={href} />
</div>
<div>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
>
{href}
</a>
</div>
</div>
);
}; |
Beta Was this translation helpful? Give feedback.
Hey @peniswafflexd
Glad to hear of your successes so far. Fortunately, what you describe is a common feature and pretty simple to setup. Since you already have a custom field, you're half way there.
To read the current value of another field in your document, use the
getDataByPath
method from theuseWatchForm
hook. Just send it the name of the field your are looking for. In your case, this is probablytitle
. Now you can format the href using this value, and render an anchor tag on the page.To go the extra mile, you can also import Payload's
CopyToClipboard
component and enhance the user experience.