Passing data with provides_context and uses_context
Hello,
I was wondering if it's possible to send data from a parent block to the child block using the context. Found this https://www.advancedcustomfields.com/resources/using-context-with-acf-blocks/ but i'm not able to get it working.
Not sure if it's possible or maybe you have an example how to pass the data correctly.
Thanks in advance!
I haven't used context so maybe someone else can chime in.
It's been previously discussed here which might help.
ACF Fields
If you only need to pass the ACF field, you can use the method described in your link. I tested this and it works just fine.
In your parent block: public $provides_context = ['acf/fields' => 'data'];
In your child block: public $uses_context = ['acf/fields'];
In your child-block.blade.php file: {{ $block->context['acf/fields']['field_name'] }}
Custom data
If you want to pass custom data, you can try this method:
I have a block acf/tabs with multiple innerBlocks acf/tab-item. I need to pass data from / to innerblock siblings.
I added public $uses_context = ['sage/parentData']; to my acf/tab-item (child) block.
No need to add the $provides_context property to the parent block since we are adding the value with a filter.
Add the filter:
add_filter('render_block_context', function ($context, $parsedBlock, $parentBlock) {
if ('acf/tabs' === $parsedBlock['blockName']) {
$firstTabTitle = collect($parsedBlock['innerBlocks'])
->map(function ($block) {
return $block['attrs']['data']['title'];
})
->first();
$context['sage/parentData'] = [
'firstTabTitle' => $firstTabTitle,
];
}
return $context;
}, 10, 3);
Now I can use the value in my tab-item.blade.php file:
{{ $block->context['sage/parentData']['firstTabTitle'] }}