Search code examples
wordpresswordpress-gutenberg

How to e.preventDefault() when clicking on Update in Gutenberg, WordPress


How to e.preventDefault() when clicking on Update in Gutenberg, WordPress?

What I'm trying to do is check something and if there is any error, I will prevent the update process and show the error.

My code:

$(document).on('click', '#editor .editor-post-publish-button', function (e) {
    e.preventDefault();
    // Show Errors...
});

However, the e.preventDefault() is not preventing the process and the post is getting updated.


Solution

  • With JavaScript, you can use the core WordPress Block API to issue error notices if your own validation logic detects any issues and prevent the post from saving if errors are present, eg:

    JavaScript

    // Create error notice
    wp.data.dispatch('core/notices').createErrorNotice(
        'A value is required', // Message displayed to User
        {
            id: 'my-field', // Used to remove notice and check if notice is present
            isDismissible: false,
        }
    );
    
    // Remove notice
    wp.data.dispatch('core/notices').removeNotice('my-field'); // unique id 'my-field'
    
    // Prevent post from saving
    wp.data.dispatch( 'core/editor' ).lockPostSaving( 'my-field' );
    
    // Enable post saving
    wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'my-field' );
    

    By using native WordPress API, displaying and styling of the notices is taken care of and keeps the UX consistent. The Documentation also has an example of preventing a post from publishing which may be helpful as well.