Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fix Gutenberg and ACF validation issue
function enhancement_gutenberg_isu(){
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
wp.domReady(function(){
//acf Custom Validation for Gutenberg
var postSaveButtonClasses = '.editor-post-publish-button';
$(document).on('click', postSaveButtonClasses , function(e){
e.stopPropagation();
e.preventDefault();
var $button = $(this)
acf_validate_fields($button);
})
})
function acf_validate_fields($button){
var editorInfo = wp.data.select( 'core/editor' );
var isPublishSidebarOpened = wp.data.select('core/edit-post').isPublishSidebarOpened();
var tmpButtonText = $button.text();
wp.data.dispatch( 'core/editor' ).lockPostSaving( 'acfValidateFields' );
$button.text('Fields validation ...');
return acf.validateForm({
form: jQuery('#editor'),
reset: true,
failure: function( $form, validator ){
var notice = validator.get('notice').data.text
wp.data.dispatch( 'core/notices' ).createErrorNotice( notice, { id: 'ACF_VALIDATION', isDismissible: true} );
if(isPublishSidebarOpened){
wp.data.dispatch('core/edit-post').closePublishSidebar()
}
},
complete: function( $form, validator ){
$button.text(tmpButtonText)
wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'acfValidateFields' );
},
success: function(){
//remove notices if there are any from acf validation
wp.data.dispatch( 'core/notices' ).removeNotice('ACF_VALIDATION');
//save post if is ok to save
if(editorInfo.isEditedPostSaveable()){
if(!editorInfo.isCurrentPostPublished() && editorInfo.getEditedPostAttribute( 'status' ) === 'draft'){
//for some reason if post is draft we must update manually post status
//otherwise post will be saved but not published;
wp.data.dispatch('core/editor').editPost({status: 'publish'})
}
wp.data.dispatch( 'core/editor' ).savePost()
}
}
})
}
});
</script>
<?php
}
add_action('admin_footer', 'enhancement_gutenberg_isu');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment