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

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();
                $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.

View Replies:
Guido replied on at Permalink Reply
Did you ever find a solution for this problem?
juliandale replied on at Permalink Reply
It should be possible using the 'render' function. See this thread for some examples:
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);

That's all!
stephendmalloy replied on at Permalink Reply
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


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