Magento2 Blocks – Append Block to Specific Container Programmatically

blocksmagento-2.1magento2

I need to display the block in product detail page for bundle product only
so I just add preference to overwrite Magento/Catalog/Controller/Product/View

Then alter the product detail page controller execute method like below.

// Render page
$page = $this->resultPageFactory->create();

if($this->_type->getById($productId)->getTypeId()=='bundle')
{
    $block=$page->getLayout()->createBlock('Vendor\Module\Block\Index\Index');
    $page->getLayout()->getBlock('content')->append($block);
}      

$this->viewHelper->prepareAndRender($page, $productId, $this, $params);
return $page;

but it always throws error like

PHP Fatal error: Call to a member function append() on boolean

I need to add my block to <referenceContainer name="content">

Best Answer

Why not just add your layout update to catalog_product_view_type_bundle.xml?

But in answer to your problem: You're creating a new $page from a factory. This page has not been added any child elements yet; other methods do that further on in the chain. That's why $page->getLayout()->getBlock('content') returns false: the 'content'-container does not yet exist.