Created
April 11, 2024 07:04
-
-
Save fului/dd989f9049791abf03e856e5e97c568c to your computer and use it in GitHub Desktop.
A way to make fields required in WordPress Gutenberg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
useRequiredField( | |
'label', | |
__('You need to enter a label to save the post.', TEXTDOMAIN), | |
label && label.length > 0, | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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