M2: Using LayoutProcessor, block taking up entire block instead of being a child
Question
I am trying to use LayoutProcessor
to include a block within the section before-place-order
on the M2 Checkout.
Currently, I already have two blocks within there (a comments block and an order attachment block), both of those use the standard layout.xml
inclusion so no issues with additional blocks and sorting.
However being new to using the LayoutProcessor
, whenever I try to include the new block, it ends up taking the entire block over, removing the other two blocks.
The setup I am using:
$jsLayout['components']['checkout']['children']['steps']['children']['billing-step']
['children']['payment']['children']['payments-list']['children']['before-place-order'] =
[
'component' => 'uiComponent',
'displayArea' => 'before-place-order',
'children' =>
[
...
]
]
I believe it looks obvious to me that I am declaring it to essentially take up the before-place-order
spot instead of telling it to be a child of it, but any method I've tried to change that to being a child, doesn't work.
Any ideas?
Solution
We can try with the simple function array_merge_recursive
.
Example code:
/**
* Checkout LayoutProcessor after process plugin.
*
* @param LayoutProcessor $processor
* @param array $jsLayout
* @return array
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterProcess(LayoutProcessor $processor, $jsLayout)
{
$beforePlaceOrderLayout = $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']
['children']['payment']['children']['payments-list']['children']['before-place-order']['children'];
//Your custom field
$fields['custom_info_note'] = [
'component' => 'Magento_Ui/js/form/element/textarea',
'config' => [
'customScope' => 'custom_info_note',
'template' => 'ui/form/field',
'elementTmpl' => 'ui/form/element/textarea',
'options' => [],
'id' => 'delivery_comment'
],
'dataScope' => 'custom_info_note.custom_info_note',
'label' => 'Comment',
'provider' => 'checkoutProvider',
'visible' => true,
'validation' => [],
'sortOrder' => 20,
'id' => 'custom_info_note'
];
//Array Merge
$additionalLayout = array_merge_recursive($beforePlaceOrderLayout, $fields);
$jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
['payment']['children']['payments-list']['children']['before-place-order']['children'] = $additionalLayout;
return $jsLayout;
}
Result: