Adding a block and setting a template to a page in code

Permalink
Hello everybody. I´m trying to add a block to a page an then set a custom template to it. I managed to add the block to this page (which is a single page) but have no way of setting the template. I´ve tried almost everything, even copying code in process.php. When I log in as an admin I can see the block added to the page, but without Its template applied. This is the current code I´m using:
$p = Page::getCurrentPage();
        $bt_main = BlockType::getByHandle('baibuk_cart');
        $blocks = $p->getBlocks('Header');
        if (count($blocks) == 0) {
            $p->addBlock($bt_main, "Header", array());
            $blocks = $p->getBlocks('Header');
            //$a = Area::get($p, 'Header');
            //$b = Block::getByID($_GET['bID'], $c, $a);
            $b = $blocks[0];
            $permisos = new Permissions($b);
            // we're updating the groups for a particular block
            if ($permisos->canWrite()) {
                $nvc = $p->getVersionToModify();
                $b->loadNewCollection($nvc);
                $data = array("bFileName" => "cart");


Like I said, part of this code is from process.php, executed when you exit edit mode to approve a page version

Thanks in advance, any help would be much appreciated.

 
Guido replied on at Permalink Reply
Did you ever find a solution for this problem?
juliandale replied on at Permalink Reply
juliandale
It should be possible using the 'render' function. See this thread for some examples:
http://www.concrete5.org/community/forums/customizing_c5/hardcode-c...
Guido replied on at Permalink Reply
Thanks Julian. This is not about rendering a block programatically, but about programatically saving a block to a page and save the block's template. In the meanwhile I already found out how to do this.

The function to save the block returns a pointer to the new block object. Then you only have to call the 'setCustomTemplate' function on this object. Like this:

$newBlock = $p->addBlock($btContent, 'Content', $blockData);
$newBlock->setCustomTemplate('name_of_custom_template');


That's all!
stephendmalloy replied on at Permalink Reply
stephendmalloy
I just toyed with this for a while - so anyone wondering - when you call the setTemplate method you must include .php in the template name - so

$newBlock->setTemplate("template_name.php");


Otherwise it will not work. This is for 5.6.3.1 at least....
JohntheFish replied on at Permalink Reply
JohntheFish
It all depends on the way the template is declared.
/templates/template_name.php

or
/templates/template_name/view.php