Skip to content

Instantly share code, notes, and snippets.

@fului
Created April 11, 2024 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fului/dd989f9049791abf03e856e5e97c568c to your computer and use it in GitHub Desktop.
Save fului/dd989f9049791abf03e856e5e97c568c to your computer and use it in GitHub Desktop.
A way to make fields required in WordPress Gutenberg
useRequiredField(
'label',
__('You need to enter a label to save the post.', TEXTDOMAIN),
label && label.length > 0,
);
import { useEffect, useCallback } from "@wordpress/element";
import { dispatch, useDispatch } from "@wordpress/data";
import { store: noticesStore } from "@wordpress/notices";
export const useRequiredField = (field, message, isValid) => {
const { createErrorNotice, removeNotice } = useDispatch(noticesStore);
const { lockPostSaving, unlockPostSaving } = dispatch('core/editor');
const createNotice = useCallback(() => {
createErrorNotice(message, {
id: `${field}-empty`,
isDismissible: false,
});
}, [field, message, createErrorNotice]);
useEffect(() => {
if (!isValid) {
lockPostSaving(`${field}_lock`);
createNotice();
return;
}
removeNotice(`${field}-empty`);
unlockPostSaving(`${field}_lock`);
}, [field, isValid, lockPostSaving, unlockPostSaving, createNotice, removeNotice]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment