Adding Custom Template to a Block programmatically

Permalink
So here's what I'm doing:
$data = array(
'formatting' => 'h1',
'bFilename' => 'byline.php',
'bIsActive' => '1',
'bName' => 'block_name');
$bt_title = BlockType::getByHandle('page_title');
$ax = Area\Area::getOrCreate($page, 'Main'); 
//$page is the page object
$page->addBlock($bt_title, $ax, $data);
// Or like that
$bt_title->add($data);
$page->addBlock($bt_title, $ax, array());

The formatting is working, bName too, bIsActive also, but bFilename is not rendered on the page. So how to set a custom template on that newly created block?

daenu
View Replies: View Best Answer
daenu replied on at Permalink Reply
daenu
After digging a bit in the source code I've got a solution. Not sure if it's the best one but it works.

The thing is that the block needs to be saved before adding a template:
// After
$entry->addBlock($bt_title, $ax, $data);
// Do a DB query to get the previously created block ID (bID)
// The blocks name must be unique, because we don't know the bID
$br = $db->getOne('select * from Blocks where bName = ?', array('block_name'));
$b = Block::getByID($br);
// Now we can assign a template to the block object
$b->setCustomTemplate('byline.php');

That's it
mnakalay replied on at Permalink Best Answer Reply
mnakalay
Actually
$page->addBlock($bt_title, $ax, $data);

Will return the block object so you can just do
$b = $page->addBlock($bt_title, $ax, $data);
$b->setCustomTemplate('byline.php');
daenu replied on at Permalink Reply
daenu
Oh Man I was making it real complicated... Thank you!