I have hit a problem when trying to create a block in a controller in so much as I need the block created in the controller to also create a ViewModel type object.

What I am trying to achieve but I wish to do this via code in the controller rather than using the layout file:-

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        <referenceBlock name="product.info.details">
            <Block name="expert.reviews.tab" class="Bub\AdvancedReview\Block\ExpertReview\ExpertReviews" template="Bub\AdvancedReview::expert_reviews.phtml">
                    <argument name="advanced-review-helper" xsi:type="object">Bub\AdvancedReview\Helper\BlockHelper</argument>

My code in the controller is as follows:-

 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.

namespace Bub\AdvancedReview\Controller\Product;

use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\View\Result\Layout;
use Magento\Review\Controller\Product as ProductController;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;

class ExpListAjax extends ProductController implements HttpGetActionInterface
     * Show list of product's reviews
     * @return ResponseInterface|ResultInterface|Layout
    public function execute()
        /** @var \Magento\Framework\View\Layout $layout */
        $layout = $this->_view->getLayout();

        /** @var \Bub\AdvancedReview\Block\ExpertReview\ExpertReviews $block */
        $block = $layout->createBlock(\Bub\AdvancedReview\Block\ExpertReview\ExpertReviews::class,null,['advanced-review-helper' => 'Bub\AdvancedReview\Helper\BlockHelper']);

        return $this->getResponse()->setBody($block->toHtml());

Does anybody know if this can be done?

Thankyou in Advance

1 Answer 1


You will have to inject an instance of the Bub\AdvancedReview\Helper\BlockHelper via the contsructor (di) and pass it as an object instead of a string:

$block = $layout->createBlock(
        'data' => [
            'advanced-review-helper' => $this->bubsHelper

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.