Skip to content

registerBlockBindingsSource seems to require matching label to register_block_bindings_source #66031

@ryanwelcher

Description

@ryanwelcher

Description

During my livestream today, I was registering a custom block binding source to be able to edit the post excerpt.

My server side code worked correctly but when adding the client side, it would not register until I added the label property.

@SantosGuillamot and @artemiomorales were both on the stream and confirmed that if the server side registered the label and uses_context values that they should not be required for the client side. However, I was not able to get this working until I added the label property to the client.

When I dropped the client side code into the console it worked correctly without needing the label property which might indicate an order of operations issue.

You can see the section of the live stream where we discover the "fix" here

Server side code

add_action(
	'init',
	function() {
		register_block_bindings_source(
			'twitch/excerpt',
			array(
				'label'              => __( 'Excerpt', 'custom-bindings' ),
				'get_value_callback' => 'twitch_excerpt_bindings',
				'uses_context'       => array( 'postId', 'postType' ),
			)
		);
	}
);

function twitch_excerpt_bindings( $source_args, $block_instance ) {
	$post_id      = $block_instance->context['postId'];
	$post_type    = $block_instance->context['postType'];
	$current_post = get_post( $post_id );
	return $current_post->post_excerpt;
}

Client side

Enqueued on the enqueue_block_editor_assets hook.

registerBlockBindingsSource( {
	label: __( 'Excerpt' ), // This was required to make the code work.
	name: 'twitch/excerpt',
	getValues( { select, context, bindings } ) {
		return {
			content:
				select( 'core/editor' ).getEditedPostAttribute( 'excerpt' ),
		};
	},

	setValues( { select, dispatch, context, bindings } ) {
		dispatch( 'core/editor' ).editPost( {
			excerpt: bindings?.content?.newValue,
		} );
	},

	canUserEditValue( { select, context } ) {
		return true;
	},
} );

Step-by-step reproduction instructions

  1. Use the code examples above
  2. Confirm that the binding is editable
  3. Remove the label property from the JS
  4. Confirm the binding is no longer editable.

Screenshots, screen recording, code snippet

https://www.youtube.com/live/NIDS4PFUHBI?feature=shared&t=5709

Environment info

No response

Please confirm that you have searched existing issues in the repo.

  • Yes

Please confirm that you have tested with all plugins deactivated except Gutenberg.

  • Yes

Metadata

Metadata

Type

No type
No fields configured for issues without a type.

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions