Dynamically inserting a block from parent page area at runtime

Permalink
Hi,

I am trying to dynamically insert the a block form a the pages parent page.

What I am trying to do is if the an area of a page in empty, then it will use the blocks from the parent page in the same area. I thought I could do this in the page type controller but havent got as for as to add the block to the page.

This is what I have so far...

class InnerPageTypeController extends Controller {
    public function on_start() {
        $page = Page::getCurrentPage();
        $blocks = $page->getBlocks('Hero Image');
        if(count($blocks) == 0){
            $parentPage = Page::getByID($page->getCollectionParentID());
            $parentBlocks = $parentPage->getBlocks('Hero Image');
            // insert the parent blocks here??
        }
    }
}

 
JohntheFish replied on at Permalink Reply
JohntheFish
Try my Parent Area addon or Universal Content Puller addon.

Because they work on areas, you may need to tweak your them to have an area for just that one block. You may be able to use layouts to do similar (layouts create pseudo areas) - this is not something I have ever tried.
concrete5fan25 replied on at Permalink Reply
Thanks JohntheFish,

This is what I ended up doing. Seems to work perfectly so far.

My page type controller..
class CustomPageTypeController extends Controller {
    public function on_start() {
        $this->set('parentBlocks', false);
        $page = Page::getCurrentPage();
        $blocks = $page->getBlocks('Hero Image');
        if (count($blocks) == 0) {
            $this->set('parentBlocks', $this->getParentBlocks($page));
        }
    }
    private function getParentBlocks($page) {
        if ($page->getCollectionID() == null) {
            return false;
        }
        $parentPage = Page::getByID($page->getCollectionParentID());
        $parentBlocks = $parentPage->getBlocks('Hero Image');

In my template...
<?php
            if (!$c->isEditMode() && $parentBlocks) {
                foreach ($parentBlocks as $block) {
                    $block->display();
                }
            } else {
                $heroImage = new Area('Hero Image');
                $heroImage->display($c);
            }
            ?>