Adding Custom Template to a Block programmatically

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
$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?

View Replies: View Best Answer
daenu replied on at Permalink Reply
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

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

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