pestle
pestle copied to clipboard
Use view_model in generated adminhtml block
While reading https://alanstorm.com/magento_2_admin_mvcmvvm_endpoints/ , it's pointed out that an adminhtml block must extend \Magento\Backend\Block\Template . When I went and opened that class, the comments prefer another method for a custom adminhtml block:
Standard admin block. Adds admin-specific behavior and event. Should be used when you declare a block in admin layout handle.
Avoid extending this class if possible.
If you need custom presentation logic in your blocks, use this class as block, and declare custom view models in block arguments in layout handle file.
Example:
<block name="my.block" class="Magento\Backend\Block\Template" template="My_Module::template.phtml" > <arguments> <argument name="view_model" xsi:type="object">My\Module\ViewModel\Custom</argument> </arguments> </block>
Your class object can then be accessed by doing $block->getViewModel()
I think it's better Pestle generates this setup.
@evs-xsarus Thanks for opening the issue and engaging!
I've seen this view model within a block (which is also a sort of view model) setup recommended before -- however given how almost none of Magento itself is implemented using this pattern the recommendation has always run a little hollow to me. Because of that we likely won't be changing any core pestle behavior.
We would be supportive of Pull Requests that added a --base-block option to magento2:generate:view
to change/set the base block used in the layout handle. We'd also be supportive of PRs for a new command that could add arguments to a block's definition in a layout file.
Thank you for the explanation. I might create a PR, but won't expect one soon.