Kamal
Kamal

Reputation: 1954

concrete5 how to disconnect a block from it's master block on page defaults programmatically

I'm building a new single page composer with it's own controller to edit some of my specialized page for some specific users. Those pages have some default blocks already set up on it via the page type defaults.

All I want is to edit the content of Content Block via my new single page edit form. That Content Block is already predefined on the page type defaults. It's placed as the first block on the Main Area.

For that, I made a function on my controller like this

/* $p = the page object that I want to edit */
private function saveData($p){
        // get all blocks fromt the Main area
    $blocks = $p->getBlocks('Main');

        // setup $data with a POST variable 'contentBody'
    $data = array('content' => $this->post('contentBody'));

        // instantiate block with Content Block type
    $bt = BlockType::getByHandle('content');

        // try to iterate all the blocks obtained and update only the first block  
        foreach( $blocks as $b){
        $b->update($data);
                break;
    }
}

I thought that simple function should be enough to make it work just like what I want. But apparently it's not. the $b->update($data) function seems to be updating the master block on its page type defaults, not only this particular block on this particular page I'm editing. So it update all of my pages which contain that defaults Content Block.

So how can I really disconnect that block from it's master default. So that I could edit it just for this particular page. The built in concrete5 block editing functionality is able to disconnect the block. But I can't find any clue or documentation anywhere about how to disconnect that block. I also have no clue what concrete5 core files to dig to find out how to disconnect it.

Upvotes: 1

Views: 495

Answers (1)

James S
James S

Reputation: 3374

You're right. Before the block has been edited (using the c5 editing interface -- not the APIs), the block is actually a reference to the page type's default block. This code should work for you:

$blocks = $page->getBlocks('Main');
foreach ($blocks as $block) {
    if ($block->getBlockTypeHandle() == 'content') {
        $newblock = $block->duplicate($page);
        $block->delete();

        $newblock->update($data);
        break;
    }
}

Upvotes: 2

Related Questions