I am able to create CMS Static Block from admin and display it on the homepage, but is there a way to do it programmatically so I can create custom widgets(basically custom HTML/CSS) and display it on the homepage? What's the best way to go about displaying Custom HTML/CSS on the homepage programmatically? Or is modifying the Content
in Content>Pages>Home Page
is the only way?
-
you can create block programmatically find here or this one, let me find to assign it into the homepage– HiteshCommented Oct 25, 2018 at 5:47
-
try this one, it maybe solve your problem, I think you just need to get first cms page content and after that update to it.– HiteshCommented Oct 25, 2018 at 5:51
Add a comment
|
1 Answer
Create InstallData.php file at /app/code/VendorName/ModuleName/Setup/InstallData.php
<?php
namespace VendorName\ModuleName\Setup;
use Magento\Cms\Model\BlockFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
private $blockFactory;
public function __construct(BlockFactory $blockFactory)
{
$this->blockFactory = $blockFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$cmsBlockData = [
'title' => 'Custom CMS Block',
'identifier' => 'custom_cms_block',
'content' => "<h1>Your content added here</h1>",
'is_active' => 1,
'stores' => [0],
'sort_order' => 0
];
$this->blockFactory->create()->setData($cmsBlockData)->save();
}
}
Then, remove your module value from setup_module table and related table also. Now, execute this below command.
php bin/magento s:up
php bin/magento s:s:d -f or php bin/magento s:s:d
php bin/magento c:c
Then, go to admin -> Content -> Blocks and find your static block will be created. Now, add your changes if you need.
Hope, it will helpful for you.
-
In the content part-
'content' => "<h1>Your content added here</h1>"
, can I call another phtml file so the contents of that phtml file gets displayed? Or should I write my entire html/CSS/JS in InstallData.php file? Commented Oct 25, 2018 at 6:06 -
Yes. You can add phtml like this 'content' => "<p>{{block class="VendorName\ModuleName\Block\BlockFileName" template="VendorName_ModuleName::yourphtml.phtml"}}</p>" Commented Oct 25, 2018 at 6:10