Magento 2 + create widget via installData Script
-
23-01-2021 - |
Question
I need to custom requirement for creating a widget via Script. but I have facing an error when try to add a widget via below script
<?php
namespace Test\Xyz\Setup;
use Magento\Framework\Setup;
class InstallData implements Setup\InstallDataInterface
{
/**
* @var Setup\SampleData\Executor
*/
protected $executor;
/**
* @var Installer
*/
protected $installer;
private $widgetFactory;
public function __construct(
Setup\SampleData\Executor $executor,
Installer $installer,
\Magento\Widget\Model\Widget\InstanceFactory $widgetFactory
) {
$this->executor = $executor;
$this->installer = $installer;
$this->widgetFactory = $widgetFactory;
}
public function install(Setup\ModuleDataSetupInterface $setup, Setup\ModuleContextInterface $moduleContext)
{
$this->executor->exec($this->installer);
$instaFeedWidget = [
'instance_type' => 'Test\Xyz\Block\Widget\Instagram',
'theme_id' => 2,
'title' => 'Instagram',
'store_ids' => '0',
'widget_parameters' => '{"title":"Instagram ","numberimage":"16","resolution":"standard_resolution"}',
'sort_order' => 0,
'page_groups' => [[
'page_group' => 'pages',
'all_pages' => [
'page_id' => null,
//'group' => 'all_pages',
'layout_handle' => 'cms_index_index',
'block' => 'page.bottom',
'for' => 'all',
'template' => ''
]
]]
];
$this->widgetFactory->create()->setData($instaFeedWidget)->save();
}
}
But I am facing error Test\Xyz\Setup\Installer does not exist
Any ideas will be welcomed.
Solution
Try with this:
<?php
namespace Test\Xyz\Setup;
use Magento\Framework\Setup;
class InstallData implements Setup\InstallDataInterface
{
/**
* @var Setup\SampleData\Executor
*/
protected $executor;
private $widgetFactory;
public function __construct(
Setup\SampleData\Executor $executor,
\Magento\Widget\Model\Widget\InstanceFactory $widgetFactory
) {
$this->executor = $executor;
$this->widgetFactory = $widgetFactory;
}
public function install(Setup\ModuleDataSetupInterface $setup, Setup\ModuleContextInterface $moduleContext)
{
$instaFeedWidget = [
'instance_type' => 'Test\Xyz\Block\Widget\Instagram',
'theme_id' => 2,
'title' => 'Instagram',
'store_ids' => '0',
'widget_parameters' => '{"title":"Instagram ","numberimage":"16","resolution":"standard_resolution"}',
'sort_order' => 0,
'page_groups' => [[
'page_group' => 'pages',
'all_pages' => [
'page_id' => null,
//'group' => 'all_pages',
'layout_handle' => 'cms_index_index',
'block' => 'page.bottom',
'for' => 'all',
'template' => ''
]
]]
];
$this->widgetFactory->create()->setData($instaFeedWidget)->save();
}
}
I have removed Installer $installer,
and $this->installer = $installer;
also variable
/**
* @var Installer
*/
protected $installer;
OTHER TIPS
The reason to the error is Installer
argument in construct function. It needs to be connected with some class like how $widgetFactory
is done. After that clear code from generated/code
and run.
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange