Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get repeater data via providesContext/usesContext #710

Open
JiveDig opened this issue Sep 19, 2022 · 1 comment
Open

Get repeater data via providesContext/usesContext #710

JiveDig opened this issue Sep 19, 2022 · 1 comment

Comments

@JiveDig
Copy link

JiveDig commented Sep 19, 2022

Originally brought up via #654 (comment)

It seems we only have access to the raw data, which is understandable, but it would be great to get the return value as expected via get_field().

@lgladdy originally posted:

In the future, I'd expect we'll get some kind of acf_build_context_data() function into core for you, but given this context was just a quick thing I managed to get into the 6.0 release as an MVP, we'll work more on this over our next few releases.

This is a new issue to keep the discussion focused on this specific FR.

@JiveDig
Copy link
Author

JiveDig commented Sep 19, 2022

FWIW, this works but is messy:

// $context is the acf/fields data.

// Key => Default.
$repeaters    = [
	'arrangement'    => '1/4',
	'arrangement_md' => '1/3',
	'arrangement_sm' => '1/2',
	'arrangement_xs' => '1/1',
];

$args = [];

foreach ( $repeaters as $name => $default ) {
	$args[ $name ] = [];

	$value = isset( $context[ $name ] ) ? $context[ $name ] : null;

	if ( is_null( $value ) ) {
		$args[ $name ][] = $default;
		continue;
	}

	// Array starts with 0 but rows count starts with 1.
	for ( $i = 0; $i < (int) $value; $i++ ) {
		$sub_key         = sprintf( '%s_%s_columns', $name, $i );
		$sub_value       = isset( $context[ $sub_key ] ) ? $context[ $sub_key ] : [ $default ];
		$args[ $name ][] = $sub_value;
	}
}

While this is cleaner but only gets the first row, or at least I think that's what's happening:

// $context is the acf/fields data.
$setup = acf_setup_meta( $context, 'block_context' );

// Key => Default.
$repeaters    = [
	'arrangement'    => '1/4',
	'arrangement_md' => '1/3',
	'arrangement_sm' => '1/2',
	'arrangement_xs' => '1/1',
];

$args = [];

foreach ( $repeaters as $name => $default ) {
	$args[ $name ] = [];
	$values        = get_field( $name, 'block_context' );

	if ( ! $values ) {
		$args[ $name ][] = $default;
		continue;
	}

	foreach ( (array) $values as $value ) {
		$args[ $name ][] = isset( $value['columns'] ) ? $value['columns'] : $default;
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant