How to fire "change" event on "Additional CSS Class" input

Viewed 59

I'm using JS to populate the Additional CSS Class input, which works fine (i.e. the value of the text input field is getting set), however it's not notifying Gutenberg that the value has been updated, and it doesn't save the programmatically-populated value. I've tried:

classField.trigger( 'change' );
classField.trigger( 'input' );

...which do fire but have no effect on Gutenberg. Any ideas?

*UPDATE (not working yet)

wp.domReady( function() {

jQuery('body').on( 'change', '.acf-field[data-name=col_size] select', function() {
  var clientId = jQuery(".wp-block.is-selected").attr("data-block");
  wp.data.dispatch( 'acf/column' ).updateBlockAttributes( clientId, { className:'my-style' } );
});

});
1 Answers

To update the blocks className attribute, using the target blocks clientId, dispatch a call to WordPress to save the change via:

wp.data.dispatch( 'core/block-editor' ).updateBlockAttributes( clientId, { className:'my-style' } );

The clientId is stored in the data-block value of the rendered HTML, eg. Table Block:

<figure 
    ... 
    data-block="{clientId}" 
    data-type="core/table" 
    data-title="Table"
>

Ref: https://developer.wordpress.org/block-editor/reference-guides/data/data-core-block-editor/

Related