feat(main): Initial Module

This commit is contained in:
2026-06-23 10:36:51 +02:00
parent d84aa7c701
commit 9ee25402df
26 changed files with 1121 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace Websmid\CustomHtml\Config;
class Config
{
const HOOKS = [];
const TABS = [
[
'class_name' => 'AdminCustomHtmlOverview',
'parent_class_name' => 'AdminParentThemes',
'name' => [
'en' => 'Custom HTML',
'nl' => 'Custom HTML',
],
'module' => 'ws_customhtml',
'icon' => 'code',
'route_name' => 'customhtml_index',
'active' => 1,
],
];
}
+124
View File
@@ -0,0 +1,124 @@
<?php
namespace Websmid\CustomHtml\Controller;
use Exception;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use PrestaShopBundle\Security\Voter\PageVoter;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Websmid\CustomHtml\Grid\Definition\Factory\CustomHtmlGridDefinitionFactory;
use Websmid\CustomHtml\Grid\Filters\CustomHtmlFilters;
use Websmid\CustomHtml\Model\CustomHtml;
use Validate;
class CustomHtmlController extends FrameworkBundleAdminController
{
public function indexAction(Request $request, CustomHtmlFilters $filters): Response
{
$gridFactory = $this->get('websmid.customhtml.grid.customhtml_grid_factory');
$grid = $gridFactory->getGrid($filters);
return $this->render('@Modules/ws_customhtml/views/templates/admin/grid/customhtml.html.twig', [
'customHtmlGrid' => $this->presentGrid($grid),
'layoutHeaderToolbarBtn' => $this->getToolbarButtons($request->get('_legacy_controller')),
]);
}
public function searchAction(Request $request): RedirectResponse
{
return $this->get('prestashop.bundle.grid.response_builder')->buildSearchResponse(
$this->get('websmid.customhtml.grid.definition.factory.customhtml_definition_factory'),
$request,
CustomHtmlGridDefinitionFactory::GRID_ID,
'customhtml_index'
);
}
public function createAction(Request $request): Response
{
$formBuilder = $this->get('websmid.customhtml.form.customhtml_data_form_builder');
$formHandler = $this->get('websmid.customhtml.form.customhtml_form_handler');
$form = $formBuilder->getForm();
$form->handleRequest($request);
try {
$handlerResult = $formHandler->handle($form);
if (null !== $handlerResult->getIdentifiableObjectId()) {
$this->addFlash('success', $this->trans('Successful creation.', 'Admin.Notifications.Success'));
return $this->redirectToRoute('customhtml_index');
}
} catch (Exception $e) {
$this->addFlash('error', $this->getErrorMessageForException($e, []));
}
return $this->render('@Modules/ws_customhtml/views/templates/admin/form/customhtml_create.html.twig', [
'customHtmlForm' => $form->createView(),
]);
}
public function editAction(Request $request, int $idCustomHtml): Response
{
$formBuilder = $this->get('websmid.customhtml.form.customhtml_data_form_builder');
$formHandler = $this->get('websmid.customhtml.form.customhtml_form_handler');
$form = $formBuilder->getFormFor($idCustomHtml);
try {
$form->handleRequest($request);
$handlerResult = $formHandler->handleFor($idCustomHtml, $form);
if ($handlerResult->isSubmitted() && $handlerResult->isValid()) {
$this->addFlash('success', $this->trans('Successful update.', 'Admin.Notifications.Success'));
return $this->redirectToRoute('customhtml_index');
}
} catch (Exception $e) {
$this->addFlash('error', $this->getErrorMessageForException($e, []));
}
return $this->render('@Modules/ws_customhtml/views/templates/admin/form/customhtml_edit.html.twig', [
'customHtmlForm' => $form->createView(),
'idCustomHtml' => $idCustomHtml,
]);
}
public function deleteAction(Request $request, int $idCustomHtml): RedirectResponse
{
$block = new CustomHtml($idCustomHtml);
if (!Validate::isLoadedObject($block)) {
$this->addFlash('error', $this->trans('Unable to find the block.', 'Modules.Wscustomhtml.Admin'));
return $this->redirectToRoute('customhtml_index');
}
$block->delete();
$this->addFlash('success', $this->trans('Successful deletion.', 'Admin.Notifications.Success'));
return $this->redirectToRoute('customhtml_index');
}
private function getToolbarButtons(?string $securitySubject): array
{
$toolbarButtons = [];
if (!$securitySubject || !$this->isGranted(PageVoter::CREATE, $securitySubject)) {
return $toolbarButtons;
}
$toolbarButtons['customhtml_create'] = [
'href' => $this->generateUrl('customhtml_create'),
'desc' => $this->trans('New block', 'Admin.Actions'),
'icon' => 'add_circle_outline',
'class' => 'btn-primary',
'floating_class' => '',
];
return $toolbarButtons;
}
}
@@ -0,0 +1,65 @@
<?php
namespace Websmid\CustomHtml\Form\DataHandler;
use PrestaShop\PrestaShop\Core\Form\IdentifiableObject\DataHandler\FormDataHandlerInterface;
use Websmid\CustomHtml\Model\CustomHtml;
use Context;
use Hook;
use Module;
use Validate;
final class CustomHtmlDataHandler implements FormDataHandlerInterface
{
public function create(array $formData)
{
$block = new CustomHtml();
$block->hook_name = (string) $formData['hook_name'];
$block->title = (string) $formData['title'];
$block->show_title = (int) $formData['show_title'];
$block->content = (string) $formData['content'];
$block->active = (int) $formData['active'];
$block->ordering = 0;
if (!$block->add()) {
return false;
}
$this->checkAndRegisterHookForModule((string) $formData['hook_name']);
return $block->id;
}
public function update($id, array $formData)
{
$block = new CustomHtml((int) $id);
if (!Validate::isLoadedObject($block)) {
return false;
}
$block->hook_name = (string) $formData['hook_name'];
$block->title = (string) $formData['title'];
$block->show_title = (int) $formData['show_title'];
$block->content = (string) $formData['content'];
$block->active = (int) $formData['active'];
if (!$block->update()) {
return false;
}
$this->checkAndRegisterHookForModule((string) $formData['hook_name']);
return true;
}
private function checkAndRegisterHookForModule(string $hookName): void
{
$module = Module::getInstanceByName('ws_customhtml');
$idShop = (int) Context::getContext()->shop->id;
if (!Hook::isModuleRegisteredOnHook($module, $hookName, $idShop)) {
Hook::registerHook($module, $hookName);
}
}
}
@@ -0,0 +1,38 @@
<?php
namespace Websmid\CustomHtml\Form\DataProvider;
use PrestaShop\PrestaShop\Core\Form\IdentifiableObject\DataProvider\FormDataProviderInterface;
use Websmid\CustomHtml\Model\CustomHtml;
use Validate;
final class CustomHtmlDataProvider implements FormDataProviderInterface
{
public function getData($id)
{
$block = new CustomHtml((int) $id);
if (!Validate::isLoadedObject($block)) {
return $this->getDefaultData();
}
return [
'hook_name' => $block->hook_name,
'title' => $block->title,
'show_title' => (bool) $block->show_title,
'content' => $block->content,
'active' => (bool) $block->active,
];
}
public function getDefaultData()
{
return [
'hook_name' => '',
'title' => '',
'show_title' => false,
'content' => '',
'active' => true,
];
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace Websmid\CustomHtml\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use PrestaShopBundle\Form\Admin\Type\SwitchType;
use Symfony\Contracts\Translation\TranslatorInterface;
class CustomHtmlType extends AbstractType
{
private $translator;
public function __construct(TranslatorInterface $translator, array $locales)
{
$this->translator = $translator;
}
public function buildForm(FormBuilderInterface $formBuilder, array $options): void
{
$formBuilder
->add('hook_name', TextType::class, [
'label' => $this->translator->trans('Hook name', [], 'Modules.Wscustomhtml.Admin'),
'required' => true,
])
->add('title', TextType::class, [
'label' => $this->translator->trans('Title', [], 'Modules.Wscustomhtml.Admin'),
'required' => true,
])
->add('show_title', SwitchType::class, [
'label' => $this->translator->trans('Show title', [], 'Modules.Wscustomhtml.Admin'),
'required' => false,
])
->add('content', TextareaType::class, [
'label' => $this->translator->trans('Content', [], 'Modules.Wscustomhtml.Admin'),
'required' => false,
'attr' => ['class' => 'autoload_rte'],
])
->add('active', SwitchType::class, [
'label' => $this->translator->trans('Active', [], 'Modules.Wscustomhtml.Admin'),
'required' => false,
]);
}
}
@@ -0,0 +1,153 @@
<?php
namespace Websmid\CustomHtml\Grid\Definition\Factory;
use PrestaShop\PrestaShop\Core\Grid\Action\GridActionCollection;
use PrestaShop\PrestaShop\Core\Grid\Action\Row\RowActionCollection;
use PrestaShop\PrestaShop\Core\Grid\Action\Row\Type\LinkRowAction;
use PrestaShop\PrestaShop\Core\Grid\Action\Type\SimpleGridAction;
use PrestaShop\PrestaShop\Core\Grid\Column\ColumnCollection;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\Common\ActionColumn;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\DataColumn;
use PrestaShop\PrestaShop\Core\Grid\Definition\Factory\AbstractGridDefinitionFactory;
use PrestaShop\PrestaShop\Core\Grid\Filter\Filter;
use PrestaShop\PrestaShop\Core\Grid\Filter\FilterCollection;
use PrestaShop\PrestaShop\Core\Hook\HookDispatcherInterface;
use PrestaShopBundle\Form\Admin\Type\SearchAndResetType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
final class CustomHtmlGridDefinitionFactory extends AbstractGridDefinitionFactory
{
const GRID_ID = 'customhtml';
public function __construct(HookDispatcherInterface $dispatcher)
{
parent::__construct($dispatcher);
}
protected function getId(): string
{
return self::GRID_ID;
}
protected function getName(): string
{
return $this->trans('Custom HTML Blocks', [], 'Modules.Wscustomhtml.Admin');
}
protected function getGridActions()
{
return (new GridActionCollection())
->add(
(new SimpleGridAction('common_refresh_list'))
->setName($this->trans('Refresh list', [], 'Admin.Catalog.Feature'))
->setIcon('refresh')
)
->add(
(new SimpleGridAction('common_show_query'))
->setName($this->trans('Show SQL query', [], 'Admin.Catalog.Feature'))
->setIcon('code')
);
}
protected function getColumns()
{
return (new ColumnCollection())
->add(
(new DataColumn('id_ws_customhtml'))
->setName($this->trans('ID', [], 'Admin.Global'))
->setOptions(['field' => 'id_ws_customhtml'])
)
->add(
(new DataColumn('title'))
->setName($this->trans('Title', [], 'Modules.Wscustomhtml.Admin'))
->setOptions(['field' => 'title'])
)
->add(
(new DataColumn('hook_name'))
->setName($this->trans('Hook', [], 'Modules.Wscustomhtml.Admin'))
->setOptions(['field' => 'hook_name'])
)
->add(
(new DataColumn('active'))
->setName($this->trans('Active', [], 'Admin.Global'))
->setOptions(['field' => 'active'])
)
->add(
(new DataColumn('date_add'))
->setName($this->trans('Date added', [], 'Admin.Global'))
->setOptions(['field' => 'date_add'])
)
->add(
(new ActionColumn('actions'))
->setName($this->trans('Actions', [], 'Admin.Global'))
->setOptions(['actions' => $this->buildRowActions()])
);
}
protected function getFilters()
{
return (new FilterCollection())
->add(
(new Filter('id_ws_customhtml', TextType::class))
->setAssociatedColumn('id_ws_customhtml')
->setTypeOptions([
'required' => false,
'attr' => ['placeholder' => $this->trans('ID', [], 'Admin.Global')],
])
)
->add(
(new Filter('title', TextType::class))
->setAssociatedColumn('title')
->setTypeOptions([
'required' => false,
'attr' => ['placeholder' => $this->trans('Title', [], 'Modules.Wscustomhtml.Admin')],
])
)
->add(
(new Filter('hook_name', TextType::class))
->setAssociatedColumn('hook_name')
->setTypeOptions([
'required' => false,
'attr' => ['placeholder' => $this->trans('Hook', [], 'Modules.Wscustomhtml.Admin')],
])
)
->add(
(new Filter('actions', SearchAndResetType::class))
->setAssociatedColumn('actions')
->setTypeOptions([
'reset_route' => 'admin_common_reset_search_by_filter_id',
'reset_route_params' => ['filterId' => self::GRID_ID],
'redirect_route' => 'customhtml_index',
])
);
}
private function buildRowActions(): RowActionCollection
{
return (new RowActionCollection())
->add(
(new LinkRowAction('edit'))
->setName($this->trans('Edit', [], 'Admin.Actions'))
->setIcon('edit')
->setOptions([
'route' => 'customhtml_edit',
'route_param_name' => 'idCustomHtml',
'route_param_field' => 'id_ws_customhtml',
'use_inline_display' => true,
'clickable_row' => true,
])
)
->add(
(new LinkRowAction('delete'))
->setName($this->trans('Delete', [], 'Admin.Actions'))
->setIcon('delete')
->setOptions([
'route' => 'customhtml_delete',
'route_param_name' => 'idCustomHtml',
'route_param_field' => 'id_ws_customhtml',
'use_inline_display' => true,
])
);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace Websmid\CustomHtml\Grid\Filters;
use PrestaShop\PrestaShop\Core\Search\Filters;
use Websmid\CustomHtml\Grid\Definition\Factory\CustomHtmlGridDefinitionFactory;
final class CustomHtmlFilters extends Filters
{
protected $filterId = CustomHtmlGridDefinitionFactory::GRID_ID;
public static function getDefaults(): array
{
return [
'limit' => 10,
'offset' => 0,
'orderBy' => 'wch.id_ws_customhtml',
'sortOrder' => 'asc',
'filters' => [],
];
}
}
+96
View File
@@ -0,0 +1,96 @@
<?php
namespace Websmid\CustomHtml\Grid\Query;
use Doctrine\DBAL\Connection;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Grid\Query\AbstractDoctrineQueryBuilder;
use PrestaShop\PrestaShop\Core\Grid\Query\DoctrineSearchCriteriaApplicatorInterface;
use PrestaShop\PrestaShop\Core\Grid\Query\Filter\DoctrineFilterApplicatorInterface;
use PrestaShop\PrestaShop\Core\Grid\Search\SearchCriteriaInterface;
final class CustomHtmlQueryBuilder extends AbstractDoctrineQueryBuilder
{
private $searchCriteriaApplicator;
private $contextLanguageId;
private $contextShopId;
private $contextShopGroupId;
private $filterApplicator;
private $configuration;
public function __construct(
Connection $connection,
string $dbPrefix,
DoctrineSearchCriteriaApplicatorInterface $searchCriteriaApplicator,
int $contextLanguageId,
int $contextShopId,
int $contextShopGroupId,
DoctrineFilterApplicatorInterface $filterApplicator,
Configuration $configuration
) {
parent::__construct($connection, $dbPrefix);
$this->searchCriteriaApplicator = $searchCriteriaApplicator;
$this->contextLanguageId = $contextLanguageId;
$this->contextShopId = $contextShopId;
$this->contextShopGroupId = $contextShopGroupId;
$this->filterApplicator = $filterApplicator;
$this->configuration = $configuration;
}
public function getSearchQueryBuilder(SearchCriteriaInterface $searchCriteria)
{
$qb = $this->getBaseQuery();
$qb->select(
'wch.`id_ws_customhtml`',
'wch.`title`',
'wch.`hook_name`',
'wch.`active`',
'wch.`date_add`'
);
$this->applyFilters($qb, $searchCriteria);
$qb
->orderBy($searchCriteria->getOrderBy(), $searchCriteria->getOrderWay())
->setFirstResult($searchCriteria->getOffset() ?? 0)
->setMaxResults($searchCriteria->getLimit());
return $qb;
}
public function getCountQueryBuilder(SearchCriteriaInterface $searchCriteria)
{
$qb = $this->getBaseQuery();
$qb->select('COUNT(wch.`id_ws_customhtml`)');
$this->applyFilters($qb, $searchCriteria);
return $qb;
}
private function getBaseQuery()
{
return $this->connection
->createQueryBuilder()
->from($this->dbPrefix . 'ws_customhtml', 'wch');
}
private function applyFilters($qb, SearchCriteriaInterface $searchCriteria): void
{
foreach ($searchCriteria->getFilters() as $filterName => $filterValue) {
if ($filterName === 'actions') {
continue;
}
if ($filterName === 'id_ws_customhtml') {
$qb->andWhere('wch.`id_ws_customhtml` = :id_ws_customhtml')
->setParameter('id_ws_customhtml', (int) $filterValue);
continue;
}
$qb->andWhere('wch.`' . $filterName . '` LIKE :' . $filterName)
->setParameter($filterName, '%' . pSQL($filterValue) . '%');
}
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace Websmid\CustomHtml\Model;
use ObjectModel;
use Db;
class CustomHtml extends ObjectModel
{
/** @var int */
public $id;
/** @var string */
public $hook_name = '';
/** @var string */
public $title = '';
/** @var string */
public $content = '';
/** @var int */
public $active = 1;
/** @var int */
public $show_title = 0;
/** @var int */
public $ordering = 0;
/** @var string */
public $date_add;
/** @var string */
public $date_upd;
public static $definition = [
'table' => 'ws_customhtml',
'primary' => 'id_ws_customhtml',
'fields' => [
'hook_name' => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true, 'size' => 64],
'title' => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true, 'size' => 256],
'content' => ['type' => self::TYPE_HTML, 'validate' => 'isCleanHtml'],
'active' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'show_title' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'ordering' => ['type' => self::TYPE_INT, 'validate' => 'isInt'],
'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
'date_upd' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
],
];
public static function getActiveByHookName(string $hookName): array
{
$result = Db::getInstance()->executeS(
'SELECT `id_ws_customhtml`, `title`, `content`, `active`, `show_title`, `ordering`
FROM `' . _DB_PREFIX_ . 'ws_customhtml`
WHERE `hook_name` = \'' . pSQL($hookName) . '\'
AND `active` = 1
ORDER BY `ordering` ASC'
);
return $result ?: [];
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace Websmid\CustomHtml\Module;
trait AdminHooks
{
public function isUsingNewTranslationSystem(): bool
{
return true;
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace Websmid\CustomHtml\Module;
use Websmid\CustomHtml\Model\CustomHtml;
use Context;
trait FrontHooks
{
public function renderWidget($hookName = null, array $configuration = [])
{
if (empty($hookName)) {
return false;
}
$idLang = (int) Context::getContext()->language->id;
$templateFile = 'module:ws_customhtml/views/templates/hook/customhtml_block.tpl';
$cacheId = $this->getCacheId('ws_customhtml_' . $idLang . '_' . $hookName);
if (!$this->isCached($templateFile, $cacheId)) {
$variables = $this->getWidgetVariables($hookName, $configuration);
if (empty($variables)) {
return false;
}
$this->smarty->assign($variables);
}
return $this->fetch($templateFile, $cacheId);
}
public function getWidgetVariables($hookName = null, array $configuration = [])
{
$blockList = CustomHtml::getActiveByHookName((string) $hookName);
if (empty($blockList)) {
return [];
}
return [
'hookName' => $hookName,
'blockList' => $blockList,
];
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
namespace Websmid\CustomHtml\Module;
use Websmid\CustomHtml\Config\Config;
use Db;
use Language;
use Tab;
trait Install
{
public function install()
{
if (!parent::install()) {
error_log('[ws_customhtml] parent::install() failed');
return false;
}
if (!$this->createTables()) {
error_log('[ws_customhtml] createTables() failed — DB error: ' . Db::getInstance()->getMsgError());
return false;
}
if (!$this->registerTabs(Config::TABS)) {
error_log('[ws_customhtml] registerTabs() failed');
return false;
}
if (!$this->registerHooks()) {
error_log('[ws_customhtml] registerHooks() failed');
return false;
}
return true;
}
private function createTables(): bool
{
$sqlToExec = [];
$sqlToExec[] = '
CREATE TABLE IF NOT EXISTS ' . _DB_PREFIX_ . 'ws_customhtml (
`id_ws_customhtml` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`hook_name` VARCHAR(64) NOT NULL,
`title` VARCHAR(256) NOT NULL DEFAULT \'\',
`content` LONGTEXT,
`active` TINYINT(1) NOT NULL DEFAULT 1,
`show_title` TINYINT(1) NOT NULL DEFAULT 0,
`ordering` INT(11) NOT NULL DEFAULT 0,
`date_add` DATETIME NOT NULL,
`date_upd` DATETIME NOT NULL
);
';
foreach ($sqlToExec as $sqlBlock) {
Db::getInstance()->execute(trim($sqlBlock));
}
return true;
}
private function registerHooks(): bool
{
foreach (Config::HOOKS as $hook) {
if (!$this->registerHook($hook)) {
return false;
}
}
return true;
}
private function registerTabs(array $moduleTabs): bool
{
$languages = Language::getLanguages(false);
foreach ($moduleTabs as $moduleTab) {
if (Tab::getIdFromClassName($moduleTab['class_name'])) {
continue;
}
$tab = new Tab();
$tab->class_name = $moduleTab['class_name'];
$tab->module = $moduleTab['module'];
$tab->active = 1;
$tab->route_name = $moduleTab['route_name'];
if (isset($moduleTab['icon'])) {
$tab->icon = $moduleTab['icon'];
}
foreach ($languages as $language) {
if (is_array($moduleTab['name'])) {
$tab->name[$language['id_lang']] = $moduleTab['name'][$language['iso_code']]
?? $moduleTab['name']['en'];
} else {
$tab->name[$language['id_lang']] = $moduleTab['name'];
}
}
if (isset($moduleTab['parent_class_name'])) {
$tab->id_parent = (int) Tab::getIdFromClassName($moduleTab['parent_class_name']);
} elseif (isset($moduleTab['id_parent'])) {
$tab->id_parent = (int) $moduleTab['id_parent'];
} else {
$tab->id_parent = -1;
}
$tab->add();
if (!$tab->id) {
return false;
}
}
return true;
}
}