I was able to create the install script by simply inserting the data into the two tables which store the static block details.
It could get a bit messy if you are installing many blocks but on the small scale this seems to be fine:
<?php
namespace MyVendor\MyModule\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
const TABLE_CMS_BLOCK = 'cms_block';
const TABLE_CMS_BLOCK_STORE = 'cms_block_store';
const STORE_ID = 0;
private $testBlockDetails = [
'title' => 'Test Block',
'identifier' => 'test-block',
'content' => "<h1>This is a test block piece of content</h1>",
'is_active' => true
];
/**
* @param ModuleDataSetupInterface $setup
* @param ModuleContextInterface $context
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$testBlockId = $this->createTestBlockEntry($setup);
if ($testBlockId) {
$this->createTestBlockStoreAssociation($setup, $testBlockId);
}
}
/**
* @param ModuleDataSetupInterface $setup
* @return bool
*/
private function createTestBlockEntry(ModuleDataSetupInterface $setup)
{
$setup->startSetup();
$cmsBlockTable = $setup->getTable(self::TABLE_CMS_BLOCK);
$connection = $setup->getConnection();
$connection->insertForce($cmsBlockTable, $this->testBlockDetails);
$setup->endSetup();
return $this->getBlockId($connection, $cmsBlockTable);
}
/**
* @param $connection
* @param $cmsBlockTable
* @return bool
*/
private function getBlockId($connection, $cmsBlockTable)
{
$select = $connection->select()
->from(['o' => $cmsBlockTable])
->where('o.identifier=?', $this->testBlockDetails['identifier'])
->limit(1);
$row = $connection->fetchRow($select);
if ($row) {
return $row['block_id'];
}
return false;
}
/**
* @param ModuleDataSetupInterface $setup
* @param $testBlockId
*/
private function createTestBlockStoreAssociation(ModuleDataSetupInterface $setup, $testBlockId)
{
$setup->getConnection()->insertForce(
$setup->getTable(self::TABLE_CMS_BLOCK_STORE), [
'store_id' => self::STORE_ID,
'block_id' => $testBlockId
]
);
}
}
Once installed you should have a test block added with the details of the $testBlockDetails property. Will need to look at splitting this out into more classes for multiple blocks.