Compare commits

..
4 Commits
Author SHA1 Message Date
isabelle 635c13a0ed feat(main): Groups and blocks 2026-08-10 16:13:15 +02:00
isabelle 6aff506cd6 feat(main): conform to Websmid module standards 2026-06-23 13:18:57 +02:00
isabelle 9e6c26da38 feat(main):Use TinyMCEEditor 2026-06-23 12:02:18 +02:00
isabelle 9ee25402df feat(main): Initial Module 2026-06-23 10:36:51 +02:00
42 changed files with 2060 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
/vendor/
+25
View File
@@ -0,0 +1,25 @@
{
"name": "websmid/ws_customhtml",
"description": "Create and manage custom HTML blocks for PrestaShop frontend hooks",
"authors": [
{
"name": "Isabelle Oving-Anno - De Websmid BV",
"email": "isabelle@dewebsmid.nl"
}
],
"require": {},
"autoload": {
"psr-4": {
"Websmid\\CustomHtml\\": "src/"
},
"classmap": ["ws_customhtml.php"],
"exclude-from-classmap": []
},
"config": {
"preferred-install": "dist",
"prepend-autoloader": false
},
"type": "prestashop-module",
"author": "Isabelle Oving-Anno - De Websmid BV",
"license": "MIT"
}
Generated
+18
View File
@@ -0,0 +1,18 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "477c629bc0a02ebb297b14e975a6d2e5",
"packages": [],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": {},
"prefer-stable": false,
"prefer-lowest": false,
"platform": {},
"platform-dev": {},
"plugin-api-version": "2.6.0"
}
+70
View File
@@ -0,0 +1,70 @@
services:
websmid.customhtml.form.type.customhtml_group:
public: true
class: 'Websmid\CustomHtml\Form\Type\CustomHtmlGroupType'
parent: 'form.type.translatable.aware'
tags:
- { name: form.type }
websmid.customhtml.form.customhtmlgroup_data_provider:
public: true
class: 'Websmid\CustomHtml\Form\DataProvider\CustomHtmlGroupDataProvider'
websmid.customhtml.form.customhtmlgroup_data_form_builder:
public: true
class: 'PrestaShop\PrestaShop\Core\Form\IdentifiableObject\Builder\FormBuilder'
factory:
- '@prestashop.core.form.builder.form_builder_factory'
- 'create'
arguments:
- 'Websmid\CustomHtml\Form\Type\CustomHtmlGroupType'
- '@websmid.customhtml.form.customhtmlgroup_data_provider'
websmid.customhtml.form.customhtmlgroup_data_handler:
public: true
class: 'Websmid\CustomHtml\Form\DataHandler\CustomHtmlGroupDataHandler'
websmid.customhtml.form.customhtmlgroup_form_handler:
public: true
class: 'PrestaShop\PrestaShop\Core\Form\IdentifiableObject\Handler\FormHandler'
factory:
- '@prestashop.core.form.identifiable_object.handler.form_handler_factory'
- 'create'
arguments:
- '@websmid.customhtml.form.customhtmlgroup_data_handler'
websmid.customhtml.form.type.customhtml_block:
public: true
class: 'Websmid\CustomHtml\Form\Type\CustomHtmlBlockType'
parent: 'form.type.translatable.aware'
arguments:
- '@websmid.customhtml.form.choice_provider.customhtml_group_choice_provider'
tags:
- { name: form.type }
websmid.customhtml.form.customhtmlblock_data_provider:
public: true
class: 'Websmid\CustomHtml\Form\DataProvider\CustomHtmlBlockDataProvider'
websmid.customhtml.form.customhtmlblock_data_form_builder:
public: true
class: 'PrestaShop\PrestaShop\Core\Form\IdentifiableObject\Builder\FormBuilder'
factory:
- '@prestashop.core.form.builder.form_builder_factory'
- 'create'
arguments:
- 'Websmid\CustomHtml\Form\Type\CustomHtmlBlockType'
- '@websmid.customhtml.form.customhtmlblock_data_provider'
websmid.customhtml.form.customhtmlblock_data_handler:
public: true
class: 'Websmid\CustomHtml\Form\DataHandler\CustomHtmlBlockDataHandler'
websmid.customhtml.form.customhtmlblock_form_handler:
public: true
class: 'PrestaShop\PrestaShop\Core\Form\IdentifiableObject\Handler\FormHandler'
factory:
- '@prestashop.core.form.identifiable_object.handler.form_handler_factory'
- 'create'
arguments:
- '@websmid.customhtml.form.customhtmlblock_data_handler'
+70
View File
@@ -0,0 +1,70 @@
services:
websmid.customhtml.grid.definition.factory.customhtmlgroup_definition_factory:
public: true
class: 'Websmid\CustomHtml\Grid\Definition\Factory\CustomHtmlGroupGridDefinitionFactory'
parent: 'prestashop.core.grid.definition.factory.abstract_grid_definition'
websmid.customhtml.grid.query.customhtmlgroup_query_builder:
public: true
class: 'Websmid\CustomHtml\Grid\Query\CustomHtmlGroupQueryBuilder'
parent: 'prestashop.core.grid.abstract_query_builder'
arguments:
- '@prestashop.core.query.doctrine_search_criteria_applicator'
- "@=service('prestashop.adapter.legacy.context').getContext().language.id"
- "@=service('prestashop.adapter.legacy.context').getContext().shop.id"
- "@=service('prestashop.adapter.legacy.context').getContext().shop.id_shop_group"
- '@prestashop.core.grid.query.filter.doctrine_filter_applicator'
- '@prestashop.adapter.legacy.configuration'
websmid.customhtml.grid.data.factory.customhtmlgroup_data_factory:
public: true
class: '%prestashop.core.grid.data.factory.doctrine_grid_data_factory%'
arguments:
- '@websmid.customhtml.grid.query.customhtmlgroup_query_builder'
- '@prestashop.core.hook.dispatcher'
- '@prestashop.core.grid.query.doctrine_query_parser'
- 'customhtmlgroup'
websmid.customhtml.grid.customhtmlgroup_grid_factory:
public: true
class: 'PrestaShop\PrestaShop\Core\Grid\GridFactory'
arguments:
- '@websmid.customhtml.grid.definition.factory.customhtmlgroup_definition_factory'
- '@websmid.customhtml.grid.data.factory.customhtmlgroup_data_factory'
- '@prestashop.core.grid.filter.form_factory'
- '@prestashop.core.hook.dispatcher'
websmid.customhtml.grid.definition.factory.customhtmlblock_definition_factory:
public: true
class: 'Websmid\CustomHtml\Grid\Definition\Factory\CustomHtmlBlockGridDefinitionFactory'
parent: 'prestashop.core.grid.definition.factory.abstract_grid_definition'
websmid.customhtml.grid.query.customhtmlblock_query_builder:
public: true
class: 'Websmid\CustomHtml\Grid\Query\CustomHtmlBlockQueryBuilder'
parent: 'prestashop.core.grid.abstract_query_builder'
arguments:
- '@prestashop.core.query.doctrine_search_criteria_applicator'
- "@=service('prestashop.adapter.legacy.context').getContext().language.id"
- "@=service('prestashop.adapter.legacy.context').getContext().shop.id"
- "@=service('prestashop.adapter.legacy.context').getContext().shop.id_shop_group"
- '@prestashop.core.grid.query.filter.doctrine_filter_applicator'
- '@prestashop.adapter.legacy.configuration'
websmid.customhtml.grid.data.factory.customhtmlblock_data_factory:
public: true
class: '%prestashop.core.grid.data.factory.doctrine_grid_data_factory%'
arguments:
- '@websmid.customhtml.grid.query.customhtmlblock_query_builder'
- '@prestashop.core.hook.dispatcher'
- '@prestashop.core.grid.query.doctrine_query_parser'
- 'customhtmlblock'
websmid.customhtml.grid.customhtmlblock_grid_factory:
public: true
class: 'PrestaShop\PrestaShop\Core\Grid\GridFactory'
arguments:
- '@websmid.customhtml.grid.definition.factory.customhtmlblock_definition_factory'
- '@websmid.customhtml.grid.data.factory.customhtmlblock_data_factory'
- '@prestashop.core.grid.filter.form_factory'
- '@prestashop.core.hook.dispatcher'
+4
View File
@@ -0,0 +1,4 @@
services:
websmid.customhtml.form.choice_provider.customhtml_group_choice_provider:
public: true
class: 'Websmid\CustomHtml\Form\ChoiceProvider\CustomHtmlGroupChoiceProvider'
+73
View File
@@ -0,0 +1,73 @@
customhtml_index:
path: ws_customhtml
methods: [GET]
defaults:
_controller: 'Websmid\CustomHtml\Controller\CustomHtmlGroupController::indexAction'
_legacy_controller: AdminCustomHtmlParent
_legacy_link: AdminCustomHtmlParent:index
customhtmlgroup_index:
path: ws_customhtml/group
methods: [GET]
defaults:
_controller: 'Websmid\CustomHtml\Controller\CustomHtmlGroupController::indexAction'
_legacy_controller: AdminCustomHtmlOverview
_legacy_link: AdminCustomHtmlOverview:index
customhtmlgroup_search:
path: ws_customhtml/group
methods: [POST]
defaults:
_controller: 'Websmid\CustomHtml\Controller\CustomHtmlGroupController::searchAction'
_legacy_controller: AdminCustomHtmlOverview
customhtmlgroup_create:
path: ws_customhtml/group/create
methods: [POST, GET]
defaults:
_controller: 'Websmid\CustomHtml\Controller\CustomHtmlGroupController::createAction'
customhtmlgroup_edit:
path: ws_customhtml/group/edit/{idCustomHtmlGroup}
methods: [POST, GET]
defaults:
_controller: 'Websmid\CustomHtml\Controller\CustomHtmlGroupController::editAction'
customhtmlgroup_delete:
path: ws_customhtml/group/delete/{idCustomHtmlGroup}
methods: [DELETE, GET, POST]
defaults:
_controller: 'Websmid\CustomHtml\Controller\CustomHtmlGroupController::deleteAction'
customhtmlblock_index:
path: ws_customhtml/block
methods: [GET]
defaults:
_controller: 'Websmid\CustomHtml\Controller\CustomHtmlBlockController::indexAction'
_legacy_controller: AdminCustomHtmlBlockOverview
_legacy_link: AdminCustomHtmlBlockOverview:index
customhtmlblock_search:
path: ws_customhtml/block
methods: [POST]
defaults:
_controller: 'Websmid\CustomHtml\Controller\CustomHtmlBlockController::searchAction'
_legacy_controller: AdminCustomHtmlBlockOverview
customhtmlblock_create:
path: ws_customhtml/block/create
methods: [POST, GET]
defaults:
_controller: 'Websmid\CustomHtml\Controller\CustomHtmlBlockController::createAction'
customhtmlblock_edit:
path: ws_customhtml/block/edit/{idCustomHtmlBlock}
methods: [POST, GET]
defaults:
_controller: 'Websmid\CustomHtml\Controller\CustomHtmlBlockController::editAction'
customhtmlblock_delete:
path: ws_customhtml/block/delete/{idCustomHtmlBlock}
methods: [DELETE, GET, POST]
defaults:
_controller: 'Websmid\CustomHtml\Controller\CustomHtmlBlockController::deleteAction'
+4
View File
@@ -0,0 +1,4 @@
imports:
- { resource: form.yml }
- { resource: grid.yml }
- { resource: provider.yml }
+8
View File
@@ -0,0 +1,8 @@
<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

+57
View File
@@ -0,0 +1,57 @@
<?php
namespace Websmid\CustomHtml\Config;
class Config
{
const HOOKS = [
'actionAdminControllerSetMedia',
];
const ADMIN_CONTROLLERS = [
'AdminCustomHtmlParent',
'AdminCustomHtmlOverview',
'AdminCustomHtmlBlockOverview',
];
// Order matters: the parent tab must be registered before its children so
// Tab::getIdFromClassName('AdminCustomHtmlParent') resolves during install.
const TABS = [
[
'class_name' => 'AdminCustomHtmlParent',
'parent_class_name' => 'AdminParentThemes',
'name' => [
'en' => 'Custom HTML',
'nl' => 'Custom HTML',
],
'module' => 'ws_customhtml',
'icon' => 'code',
'route_name' => 'customhtml_index',
'active' => 1,
],
[
'class_name' => 'AdminCustomHtmlOverview',
'parent_class_name' => 'AdminCustomHtmlParent',
'name' => [
'en' => 'Groups',
'nl' => 'Groepen',
],
'module' => 'ws_customhtml',
'icon' => 'code',
'route_name' => 'customhtmlgroup_index',
'active' => 1,
],
[
'class_name' => 'AdminCustomHtmlBlockOverview',
'parent_class_name' => 'AdminCustomHtmlParent',
'name' => [
'en' => 'Blocks',
'nl' => 'Blokken',
],
'module' => 'ws_customhtml',
'icon' => 'view_module',
'route_name' => 'customhtmlblock_index',
'active' => 1,
],
];
}
@@ -0,0 +1,134 @@
<?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\CustomHtmlBlockGridDefinitionFactory;
use Websmid\CustomHtml\Grid\Filters\CustomHtmlBlockFilters;
use Websmid\CustomHtml\Model\CustomHtmlBlock;
use Validate;
class CustomHtmlBlockController extends FrameworkBundleAdminController
{
public function indexAction(Request $request, CustomHtmlBlockFilters $filters): Response
{
if ($request->query->has('idGroup')) {
$filters->addFilter(['id_ws_customhtml_group' => (int) $request->query->get('idGroup')]);
$filters->setNeedsToBePersisted(false);
}
$gridFactory = $this->get('websmid.customhtml.grid.customhtmlblock_grid_factory');
$grid = $gridFactory->getGrid($filters);
return $this->render('@Modules/ws_customhtml/views/templates/admin/grid/customhtmlblock.html.twig', [
'customHtmlBlockGrid' => $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.customhtmlblock_definition_factory'),
$request,
CustomHtmlBlockGridDefinitionFactory::GRID_ID,
'customhtmlblock_index'
);
}
public function createAction(Request $request): Response
{
$formBuilder = $this->get('websmid.customhtml.form.customhtmlblock_data_form_builder');
$formHandler = $this->get('websmid.customhtml.form.customhtmlblock_form_handler');
$form = $formBuilder->getForm();
if ($request->isMethod('GET') && $request->query->has('idGroup')) {
$form->get('id_ws_customhtml_group')->setData((int) $request->query->get('idGroup'));
}
$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('customhtmlblock_index');
}
} catch (Exception $e) {
$this->addFlash('error', $this->getErrorMessageForException($e, []));
}
return $this->render('@Modules/ws_customhtml/views/templates/admin/form/customhtmlblock_create.html.twig', [
'customHtmlBlockForm' => $form->createView(),
]);
}
public function editAction(Request $request, int $idCustomHtmlBlock): Response
{
$formBuilder = $this->get('websmid.customhtml.form.customhtmlblock_data_form_builder');
$formHandler = $this->get('websmid.customhtml.form.customhtmlblock_form_handler');
$form = $formBuilder->getFormFor($idCustomHtmlBlock);
try {
$form->handleRequest($request);
$handlerResult = $formHandler->handleFor($idCustomHtmlBlock, $form);
if ($handlerResult->isSubmitted() && $handlerResult->isValid()) {
$this->addFlash('success', $this->trans('Successful update.', 'Admin.Notifications.Success'));
return $this->redirectToRoute('customhtmlblock_index');
}
} catch (Exception $e) {
$this->addFlash('error', $this->getErrorMessageForException($e, []));
}
return $this->render('@Modules/ws_customhtml/views/templates/admin/form/customhtmlblock_edit.html.twig', [
'customHtmlBlockForm' => $form->createView(),
'idCustomHtmlBlock' => $idCustomHtmlBlock,
]);
}
public function deleteAction(Request $request, int $idCustomHtmlBlock): RedirectResponse
{
$block = new CustomHtmlBlock($idCustomHtmlBlock);
if (!Validate::isLoadedObject($block)) {
$this->addFlash('error', $this->trans('Unable to find the block.', 'Modules.Wscustomhtml.Admin'));
return $this->redirectToRoute('customhtmlblock_index');
}
$block->delete();
$this->addFlash('success', $this->trans('Successful deletion.', 'Admin.Notifications.Success'));
return $this->redirectToRoute('customhtmlblock_index');
}
private function getToolbarButtons(?string $securitySubject): array
{
$toolbarButtons = [];
if (!$securitySubject || !$this->isGranted(PageVoter::CREATE, $securitySubject)) {
return $toolbarButtons;
}
$toolbarButtons['customhtmlblock_create'] = [
'href' => $this->generateUrl('customhtmlblock_create'),
'desc' => $this->trans('New block', 'Admin.Actions'),
'icon' => 'add_circle_outline',
'class' => 'btn-primary',
'floating_class' => '',
];
return $toolbarButtons;
}
}
@@ -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\CustomHtmlGroupGridDefinitionFactory;
use Websmid\CustomHtml\Grid\Filters\CustomHtmlGroupFilters;
use Websmid\CustomHtml\Model\CustomHtmlGroup;
use Validate;
class CustomHtmlGroupController extends FrameworkBundleAdminController
{
public function indexAction(Request $request, CustomHtmlGroupFilters $filters): Response
{
$gridFactory = $this->get('websmid.customhtml.grid.customhtmlgroup_grid_factory');
$grid = $gridFactory->getGrid($filters);
return $this->render('@Modules/ws_customhtml/views/templates/admin/grid/customhtmlgroup.html.twig', [
'customHtmlGroupGrid' => $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.customhtmlgroup_definition_factory'),
$request,
CustomHtmlGroupGridDefinitionFactory::GRID_ID,
'customhtmlgroup_index'
);
}
public function createAction(Request $request): Response
{
$formBuilder = $this->get('websmid.customhtml.form.customhtmlgroup_data_form_builder');
$formHandler = $this->get('websmid.customhtml.form.customhtmlgroup_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('customhtmlgroup_index');
}
} catch (Exception $e) {
$this->addFlash('error', $this->getErrorMessageForException($e, []));
}
return $this->render('@Modules/ws_customhtml/views/templates/admin/form/customhtmlgroup_create.html.twig', [
'customHtmlGroupForm' => $form->createView(),
]);
}
public function editAction(Request $request, int $idCustomHtmlGroup): Response
{
$formBuilder = $this->get('websmid.customhtml.form.customhtmlgroup_data_form_builder');
$formHandler = $this->get('websmid.customhtml.form.customhtmlgroup_form_handler');
$form = $formBuilder->getFormFor($idCustomHtmlGroup);
try {
$form->handleRequest($request);
$handlerResult = $formHandler->handleFor($idCustomHtmlGroup, $form);
if ($handlerResult->isSubmitted() && $handlerResult->isValid()) {
$this->addFlash('success', $this->trans('Successful update.', 'Admin.Notifications.Success'));
return $this->redirectToRoute('customhtmlgroup_index');
}
} catch (Exception $e) {
$this->addFlash('error', $this->getErrorMessageForException($e, []));
}
return $this->render('@Modules/ws_customhtml/views/templates/admin/form/customhtmlgroup_edit.html.twig', [
'customHtmlGroupForm' => $form->createView(),
'idCustomHtmlGroup' => $idCustomHtmlGroup,
]);
}
public function deleteAction(Request $request, int $idCustomHtmlGroup): RedirectResponse
{
$group = new CustomHtmlGroup($idCustomHtmlGroup);
if (!Validate::isLoadedObject($group)) {
$this->addFlash('error', $this->trans('Unable to find the group.', 'Modules.Wscustomhtml.Admin'));
return $this->redirectToRoute('customhtmlgroup_index');
}
$group->delete();
$this->addFlash('success', $this->trans('Successful deletion.', 'Admin.Notifications.Success'));
return $this->redirectToRoute('customhtmlgroup_index');
}
private function getToolbarButtons(?string $securitySubject): array
{
$toolbarButtons = [];
if (!$securitySubject || !$this->isGranted(PageVoter::CREATE, $securitySubject)) {
return $toolbarButtons;
}
$toolbarButtons['customhtmlgroup_create'] = [
'href' => $this->generateUrl('customhtmlgroup_create'),
'desc' => $this->trans('New group', 'Admin.Actions'),
'icon' => 'add_circle_outline',
'class' => 'btn-primary',
'floating_class' => '',
];
return $toolbarButtons;
}
}
@@ -0,0 +1,36 @@
<?php
namespace Websmid\CustomHtml\Form\ChoiceProvider;
use PrestaShop\PrestaShop\Core\Form\ConfigurableFormChoiceProviderInterface;
use PrestaShop\PrestaShop\Core\Form\FormChoiceAttributeProviderInterface;
use PrestaShop\PrestaShop\Core\Form\FormChoiceProviderInterface;
use Db;
final class CustomHtmlGroupChoiceProvider implements
FormChoiceProviderInterface,
FormChoiceAttributeProviderInterface,
ConfigurableFormChoiceProviderInterface
{
public function getChoices(array $options = []): array
{
$groups = Db::getInstance()->executeS(
'SELECT `id_ws_customhtml_group`, `title`
FROM `' . _DB_PREFIX_ . 'ws_customhtml_group`
ORDER BY `title` ASC'
);
$choices = [];
foreach ($groups as $group) {
$choices[$group['title']] = (int) $group['id_ws_customhtml_group'];
}
return $choices;
}
public function getChoicesAttributes(): array
{
return [];
}
}
@@ -0,0 +1,44 @@
<?php
namespace Websmid\CustomHtml\Form\DataHandler;
use PrestaShop\PrestaShop\Core\Form\IdentifiableObject\DataHandler\FormDataHandlerInterface;
use Websmid\CustomHtml\Model\CustomHtmlBlock;
use Validate;
final class CustomHtmlBlockDataHandler implements FormDataHandlerInterface
{
public function create(array $formData)
{
$block = new CustomHtmlBlock();
$block->id_ws_customhtml_group = (int) $formData['id_ws_customhtml_group'];
$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;
}
return $block->id;
}
public function update($id, array $formData)
{
$block = new CustomHtmlBlock((int) $id);
if (!Validate::isLoadedObject($block)) {
return false;
}
$block->id_ws_customhtml_group = (int) $formData['id_ws_customhtml_group'];
$block->title = (string) $formData['title'];
$block->show_title = (int) $formData['show_title'];
$block->content = (string) $formData['content'];
$block->active = (int) $formData['active'];
return (bool) $block->update();
}
}
@@ -0,0 +1,61 @@
<?php
namespace Websmid\CustomHtml\Form\DataHandler;
use PrestaShop\PrestaShop\Core\Form\IdentifiableObject\DataHandler\FormDataHandlerInterface;
use Websmid\CustomHtml\Model\CustomHtmlGroup;
use Context;
use Hook;
use Module;
use Validate;
final class CustomHtmlGroupDataHandler implements FormDataHandlerInterface
{
public function create(array $formData)
{
$group = new CustomHtmlGroup();
$group->title = (string) $formData['title'];
$group->hook_name = (string) $formData['hook_name'];
$group->active = (int) $formData['active'];
$group->ordering = 0;
if (!$group->add()) {
return false;
}
$this->checkAndRegisterHookForModule((string) $formData['hook_name']);
return $group->id;
}
public function update($id, array $formData)
{
$group = new CustomHtmlGroup((int) $id);
if (!Validate::isLoadedObject($group)) {
return false;
}
$group->title = (string) $formData['title'];
$group->hook_name = (string) $formData['hook_name'];
$group->active = (int) $formData['active'];
if (!$group->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\CustomHtmlBlock;
use Validate;
final class CustomHtmlBlockDataProvider implements FormDataProviderInterface
{
public function getData($id)
{
$block = new CustomHtmlBlock((int) $id);
if (!Validate::isLoadedObject($block)) {
return $this->getDefaultData();
}
return [
'id_ws_customhtml_group' => (int) $block->id_ws_customhtml_group,
'title' => $block->title,
'show_title' => (bool) $block->show_title,
'content' => $block->content,
'active' => (bool) $block->active,
];
}
public function getDefaultData()
{
return [
'id_ws_customhtml_group' => 0,
'title' => '',
'show_title' => false,
'content' => '',
'active' => true,
];
}
}
@@ -0,0 +1,34 @@
<?php
namespace Websmid\CustomHtml\Form\DataProvider;
use PrestaShop\PrestaShop\Core\Form\IdentifiableObject\DataProvider\FormDataProviderInterface;
use Websmid\CustomHtml\Model\CustomHtmlGroup;
use Validate;
final class CustomHtmlGroupDataProvider implements FormDataProviderInterface
{
public function getData($id)
{
$group = new CustomHtmlGroup((int) $id);
if (!Validate::isLoadedObject($group)) {
return $this->getDefaultData();
}
return [
'title' => $group->title,
'hook_name' => $group->hook_name,
'active' => (bool) $group->active,
];
}
public function getDefaultData()
{
return [
'title' => '',
'hook_name' => '',
'active' => true,
];
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace Websmid\CustomHtml\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use PrestaShop\PrestaShop\Core\Form\ConfigurableFormChoiceProviderInterface;
use PrestaShopBundle\Form\Admin\Type\SwitchType;
use Symfony\Contracts\Translation\TranslatorInterface;
class CustomHtmlBlockType extends AbstractType
{
private $translator;
private $groupChoiceProvider;
public function __construct(
TranslatorInterface $translator,
array $locales,
ConfigurableFormChoiceProviderInterface $groupChoiceProvider
) {
$this->translator = $translator;
$this->groupChoiceProvider = $groupChoiceProvider;
}
public function buildForm(FormBuilderInterface $formBuilder, array $options): void
{
$formBuilder
->add('id_ws_customhtml_group', ChoiceType::class, [
'label' => $this->translator->trans('Group', [], 'Modules.Wscustomhtml.Admin'),
'choices' => $this->groupChoiceProvider->getChoices(),
'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,
]);
}
}
+36
View File
@@ -0,0 +1,36 @@
<?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 PrestaShopBundle\Form\Admin\Type\SwitchType;
use Symfony\Contracts\Translation\TranslatorInterface;
class CustomHtmlGroupType extends AbstractType
{
private $translator;
public function __construct(TranslatorInterface $translator, array $locales)
{
$this->translator = $translator;
}
public function buildForm(FormBuilderInterface $formBuilder, array $options): void
{
$formBuilder
->add('title', TextType::class, [
'label' => $this->translator->trans('Title', [], 'Modules.Wscustomhtml.Admin'),
'required' => true,
])
->add('hook_name', TextType::class, [
'label' => $this->translator->trans('Hook name', [], 'Modules.Wscustomhtml.Admin'),
'required' => true,
])
->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\Definition\Factory\DeleteActionTrait;
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 CustomHtmlBlockGridDefinitionFactory extends AbstractGridDefinitionFactory
{
use DeleteActionTrait;
const GRID_ID = 'customhtmlblock';
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('group_title'))
->setName($this->trans('Group', [], 'Modules.Wscustomhtml.Admin'))
->setOptions(['field' => 'group_title'])
)
->add(
(new DataColumn('active'))
->setName($this->trans('Active', [], 'Admin.Global'))
->setOptions(['field' => 'active'])
)
->add(
(new DataColumn('ordering'))
->setName($this->trans('Position', [], 'Modules.Wscustomhtml.Admin'))
->setOptions(['field' => 'ordering'])
)
->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('group_title', TextType::class))
->setAssociatedColumn('group_title')
->setTypeOptions([
'required' => false,
'attr' => ['placeholder' => $this->trans('Group', [], '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' => 'customhtmlblock_index',
])
);
}
private function buildRowActions(): RowActionCollection
{
return (new RowActionCollection())
->add(
(new LinkRowAction('edit'))
->setName($this->trans('Edit', [], 'Admin.Actions'))
->setIcon('edit')
->setOptions([
'route' => 'customhtmlblock_edit',
'route_param_name' => 'idCustomHtmlBlock',
'route_param_field' => 'id_ws_customhtml',
'use_inline_display' => true,
'clickable_row' => true,
])
)
->add(
$this->buildDeleteAction('customhtmlblock_delete', 'idCustomHtmlBlock', 'id_ws_customhtml')
);
}
}
@@ -0,0 +1,173 @@
<?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\Definition\Factory\DeleteActionTrait;
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 CustomHtmlGroupGridDefinitionFactory extends AbstractGridDefinitionFactory
{
use DeleteActionTrait;
const GRID_ID = 'customhtmlgroup';
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 Groups', [], '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_group'))
->setName($this->trans('ID', [], 'Admin.Global'))
->setOptions(['field' => 'id_ws_customhtml_group'])
)
->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('blocks_count'))
->setName($this->trans('Blocks', [], 'Modules.Wscustomhtml.Admin'))
->setOptions(['field' => 'blocks_count', 'sortable' => false])
)
->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_group', TextType::class))
->setAssociatedColumn('id_ws_customhtml_group')
->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' => 'customhtmlgroup_index',
])
);
}
private function buildRowActions(): RowActionCollection
{
return (new RowActionCollection())
->add(
(new LinkRowAction('view_blocks'))
->setName($this->trans('View blocks', [], 'Modules.Wscustomhtml.Admin'))
->setIcon('visibility')
->setOptions([
'route' => 'customhtmlblock_index',
'route_param_name' => 'idGroup',
'route_param_field' => 'id_ws_customhtml_group',
])
)
->add(
(new LinkRowAction('add_block'))
->setName($this->trans('Add block', [], 'Modules.Wscustomhtml.Admin'))
->setIcon('note_add')
->setOptions([
'route' => 'customhtmlblock_create',
'route_param_name' => 'idGroup',
'route_param_field' => 'id_ws_customhtml_group',
])
)
->add(
(new LinkRowAction('edit'))
->setName($this->trans('Edit', [], 'Admin.Actions'))
->setIcon('edit')
->setOptions([
'route' => 'customhtmlgroup_edit',
'route_param_name' => 'idCustomHtmlGroup',
'route_param_field' => 'id_ws_customhtml_group',
'use_inline_display' => true,
'clickable_row' => true,
])
)
->add(
$this->buildDeleteAction('customhtmlgroup_delete', 'idCustomHtmlGroup', 'id_ws_customhtml_group')
);
}
}
@@ -0,0 +1,22 @@
<?php
namespace Websmid\CustomHtml\Grid\Filters;
use PrestaShop\PrestaShop\Core\Search\Filters;
use Websmid\CustomHtml\Grid\Definition\Factory\CustomHtmlBlockGridDefinitionFactory;
final class CustomHtmlBlockFilters extends Filters
{
protected $filterId = CustomHtmlBlockGridDefinitionFactory::GRID_ID;
public static function getDefaults(): array
{
return [
'limit' => 10,
'offset' => 0,
'orderBy' => 'wchb.id_ws_customhtml',
'sortOrder' => 'asc',
'filters' => [],
];
}
}
@@ -0,0 +1,22 @@
<?php
namespace Websmid\CustomHtml\Grid\Filters;
use PrestaShop\PrestaShop\Core\Search\Filters;
use Websmid\CustomHtml\Grid\Definition\Factory\CustomHtmlGroupGridDefinitionFactory;
final class CustomHtmlGroupFilters extends Filters
{
protected $filterId = CustomHtmlGroupGridDefinitionFactory::GRID_ID;
public static function getDefaults(): array
{
return [
'limit' => 10,
'offset' => 0,
'orderBy' => 'wchg.id_ws_customhtml_group',
'sortOrder' => 'asc',
'filters' => [],
];
}
}
@@ -0,0 +1,115 @@
<?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 CustomHtmlBlockQueryBuilder 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(
'wchb.`id_ws_customhtml`',
'wchb.`title`',
'wchg.`title` AS group_title',
'wchb.`active`',
'wchb.`ordering`',
'wchb.`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(wchb.`id_ws_customhtml`)');
$this->applyFilters($qb, $searchCriteria);
return $qb;
}
private function getBaseQuery()
{
return $this->connection
->createQueryBuilder()
->from($this->dbPrefix . 'ws_customhtml', 'wchb')
->leftJoin(
'wchb',
$this->dbPrefix . 'ws_customhtml_group',
'wchg',
'wchg.`id_ws_customhtml_group` = wchb.`id_ws_customhtml_group`'
);
}
private function applyFilters($qb, SearchCriteriaInterface $searchCriteria): void
{
foreach ($searchCriteria->getFilters() as $filterName => $filterValue) {
if ($filterName === 'actions') {
continue;
}
if ($filterName === 'id_ws_customhtml') {
$qb->andWhere('wchb.`id_ws_customhtml` = :id_ws_customhtml')
->setParameter('id_ws_customhtml', (int) $filterValue);
continue;
}
if ($filterName === 'id_ws_customhtml_group') {
$qb->andWhere('wchb.`id_ws_customhtml_group` = :id_ws_customhtml_group')
->setParameter('id_ws_customhtml_group', (int) $filterValue);
continue;
}
if ($filterName === 'group_title') {
$qb->andWhere('wchg.`title` LIKE :group_title')
->setParameter('group_title', '%' . pSQL($filterValue) . '%');
continue;
}
$qb->andWhere('wchb.`' . $filterName . '` LIKE :' . $filterName)
->setParameter($filterName, '%' . pSQL($filterValue) . '%');
}
}
}
@@ -0,0 +1,98 @@
<?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 CustomHtmlGroupQueryBuilder 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(
'wchg.`id_ws_customhtml_group`',
'wchg.`title`',
'wchg.`hook_name`',
'wchg.`active`',
'wchg.`date_add`',
'(SELECT COUNT(*) FROM `' . $this->dbPrefix . 'ws_customhtml` wch
WHERE wch.`id_ws_customhtml_group` = wchg.`id_ws_customhtml_group`) AS blocks_count'
);
$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(wchg.`id_ws_customhtml_group`)');
$this->applyFilters($qb, $searchCriteria);
return $qb;
}
private function getBaseQuery()
{
return $this->connection
->createQueryBuilder()
->from($this->dbPrefix . 'ws_customhtml_group', 'wchg');
}
private function applyFilters($qb, SearchCriteriaInterface $searchCriteria): void
{
foreach ($searchCriteria->getFilters() as $filterName => $filterValue) {
if ($filterName === 'actions') {
continue;
}
if ($filterName === 'id_ws_customhtml_group') {
$qb->andWhere('wchg.`id_ws_customhtml_group` = :id_ws_customhtml_group')
->setParameter('id_ws_customhtml_group', (int) $filterValue);
continue;
}
$qb->andWhere('wchg.`' . $filterName . '` LIKE :' . $filterName)
->setParameter($filterName, '%' . pSQL($filterValue) . '%');
}
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace Websmid\CustomHtml\Model;
use ObjectModel;
use Db;
class CustomHtmlBlock extends ObjectModel
{
/** @var int */
public $id;
/** @var int */
public $id_ws_customhtml_group;
/** @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' => [
'id_ws_customhtml_group' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true],
'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 getActiveByGroupIds(array $groupIds): array
{
$groupIds = array_map('intval', $groupIds);
if (empty($groupIds)) {
return [];
}
$result = Db::getInstance()->executeS(
'SELECT `id_ws_customhtml`, `id_ws_customhtml_group`, `title`, `content`, `active`, `show_title`, `ordering`
FROM `' . _DB_PREFIX_ . 'ws_customhtml`
WHERE `id_ws_customhtml_group` IN (' . implode(',', $groupIds) . ')
AND `active` = 1
ORDER BY `ordering` ASC'
);
$blocksByGroup = [];
foreach ($result as $row) {
$blocksByGroup[(int) $row['id_ws_customhtml_group']][] = $row;
}
return $blocksByGroup;
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace Websmid\CustomHtml\Model;
use ObjectModel;
use Db;
class CustomHtmlGroup extends ObjectModel
{
/** @var int */
public $id;
/** @var string */
public $hook_name = '';
/** @var string */
public $title = '';
/** @var int */
public $active = 1;
/** @var int */
public $ordering = 0;
/** @var string */
public $date_add;
/** @var string */
public $date_upd;
public static $definition = [
'table' => 'ws_customhtml_group',
'primary' => 'id_ws_customhtml_group',
'fields' => [
'hook_name' => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true, 'size' => 64],
'title' => ['type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true, 'size' => 256],
'active' => ['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_group`, `title`, `active`, `ordering`
FROM `' . _DB_PREFIX_ . 'ws_customhtml_group`
WHERE `hook_name` = \'' . pSQL($hookName) . '\'
AND `active` = 1
ORDER BY `ordering` ASC'
);
return $result ?: [];
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace Websmid\CustomHtml\Module;
use Websmid\CustomHtml\Config\Config;
use Tools;
trait AdminHooks
{
public function isUsingNewTranslationSystem(): bool
{
return true;
}
public function getContent()
{
Tools::redirectAdmin($this->get('router')->generate('customhtmlgroup_index'));
}
public function hookActionAdminControllerSetMedia(): void
{
$controllerName = $this->context->controller->controller_name ?? '';
if (!in_array($controllerName, Config::ADMIN_CONTROLLERS, true)) {
return;
}
$this->context->controller->addCSS($this->getPathUri() . 'views/css/admin/grid.css');
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace Websmid\CustomHtml\Module;
use Websmid\CustomHtml\Model\CustomHtmlBlock;
use Websmid\CustomHtml\Model\CustomHtmlGroup;
use Context;
trait DisplayHooks
{
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 = [])
{
$groupList = $this->loadActiveGroupsWithBlocks((string) $hookName);
if (empty($groupList)) {
return [];
}
return [
'hookName' => $hookName,
'groupList' => $groupList,
];
}
private function loadActiveGroupsWithBlocks(string $hookName): array
{
$groups = CustomHtmlGroup::getActiveByHookName($hookName);
if (empty($groups)) {
return [];
}
$blocksByGroup = CustomHtmlBlock::getActiveByGroupIds(array_column($groups, 'id_ws_customhtml_group'));
$groups = array_map(static function (array $group) use ($blocksByGroup) {
$group['blocks'] = $blocksByGroup[(int) $group['id_ws_customhtml_group']] ?? [];
return $group;
}, $groups);
return array_values(array_filter($groups, static function (array $group) {
return !empty($group['blocks']);
}));
}
}
+131
View File
@@ -0,0 +1,131 @@
<?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_group (
`id_ws_customhtml_group` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`hook_name` VARCHAR(64) NOT NULL,
`title` VARCHAR(256) NOT NULL DEFAULT \'\',
`active` TINYINT(1) NOT NULL DEFAULT 1,
`ordering` INT(11) NOT NULL DEFAULT 0,
`date_add` DATETIME NOT NULL,
`date_upd` DATETIME NOT NULL
);
';
$sqlToExec[] = '
CREATE TABLE IF NOT EXISTS ' . _DB_PREFIX_ . 'ws_customhtml (
`id_ws_customhtml` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`id_ws_customhtml_group` INT(11) 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,
KEY `id_ws_customhtml_group` (`id_ws_customhtml_group`)
);
';
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;
}
}
+11
View File
@@ -0,0 +1,11 @@
td.action-type {
display: flex;
align-items: center;
justify-content: center;
}
td.action-type .btn-group-action {
display: flex;
align-items: center;
justify-content: center;
}
@@ -0,0 +1,25 @@
{% import '@PrestaShop/Admin/macros.html.twig' as ps %}
{% form_theme customHtmlBlockForm '@PrestaShop/Admin/TwigTemplateForm/prestashop_ui_kit.html.twig' %}
{% block customhtmlblock_form_block %}
<div class="card">
{{ form_start(customHtmlBlockForm) }}
<div class="card-header">
<h3 class="card-header-title">
{{ 'Custom HTML Block'|trans({}, 'Modules.Wscustomhtml.Admin') }}
</h3>
</div>
<div class="card-body">
{{ form_rest(customHtmlBlockForm) }}
</div>
<div class="card-footer">
<a href="{{ path('customhtmlblock_index') }}" class="btn btn-outline-secondary">
{{ 'Cancel'|trans({}, 'Admin.Actions') }}
</a>
<button class="btn btn-primary float-right">
{{ 'Save'|trans({}, 'Admin.Actions') }}
</button>
</div>
{{ form_end(customHtmlBlockForm) }}
</div>
{% endblock %}
@@ -0,0 +1,30 @@
{% import '@PrestaShop/Admin/macros.html.twig' as ps %}
{% form_theme customHtmlGroupForm '@PrestaShop/Admin/TwigTemplateForm/prestashop_ui_kit.html.twig' %}
{% block customhtmlgroup_form_block %}
<div class="card">
{{ form_start(customHtmlGroupForm) }}
<div class="card-header">
<h3 class="card-header-title">
{{ 'Custom HTML Group'|trans({}, 'Modules.Wscustomhtml.Admin') }}
</h3>
</div>
<div class="card-body">
{{ form_rest(customHtmlGroupForm) }}
</div>
<div class="card-footer">
<a href="{{ path('customhtmlgroup_index') }}" class="btn btn-outline-secondary">
{{ 'Cancel'|trans({}, 'Admin.Actions') }}
</a>
{% if idCustomHtmlGroup is defined %}
<a href="{{ path('customhtmlblock_create', {'idGroup': idCustomHtmlGroup}) }}" class="btn btn-outline-primary">
{{ 'Add block'|trans({}, 'Modules.Wscustomhtml.Admin') }}
</a>
{% endif %}
<button class="btn btn-primary float-right">
{{ 'Save'|trans({}, 'Admin.Actions') }}
</button>
</div>
{{ form_end(customHtmlGroupForm) }}
</div>
{% endblock %}
@@ -0,0 +1,18 @@
{% extends '@PrestaShop/Admin/layout.html.twig' %}
{% block content %}
{% block customhtmlblock_create_form %}
{% include '@Modules/ws_customhtml/views/templates/admin/form/blocks/block_form.html.twig' %}
{% endblock %}
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script>
$(document).ready(function () {
window.prestashop.component.initComponents([
'TinyMCEEditor',
]);
});
</script>
{% endblock %}
@@ -0,0 +1,18 @@
{% extends '@PrestaShop/Admin/layout.html.twig' %}
{% block content %}
{% block customhtmlblock_edit_form %}
{% include '@Modules/ws_customhtml/views/templates/admin/form/blocks/block_form.html.twig' %}
{% endblock %}
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script>
$(document).ready(function () {
window.prestashop.component.initComponents([
'TinyMCEEditor',
]);
});
</script>
{% endblock %}
@@ -0,0 +1,7 @@
{% extends '@PrestaShop/Admin/layout.html.twig' %}
{% block content %}
{% block customhtmlgroup_create_form %}
{% include '@Modules/ws_customhtml/views/templates/admin/form/blocks/group_form.html.twig' %}
{% endblock %}
{% endblock %}
@@ -0,0 +1,7 @@
{% extends '@PrestaShop/Admin/layout.html.twig' %}
{% block content %}
{% block customhtmlgroup_edit_form %}
{% include '@Modules/ws_customhtml/views/templates/admin/form/blocks/group_form.html.twig' %}
{% endblock %}
{% endblock %}
@@ -0,0 +1,25 @@
{% extends '@PrestaShop/Admin/layout.html.twig' %}
{% block content %}
{% block customhtmlblock_list %}
<div class="row">
<div class="col">
{% include '@PrestaShop/Admin/Common/Grid/grid_panel.html.twig' with {'grid': customHtmlBlockGrid} %}
</div>
</div>
{% endblock %}
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script>
$(document).ready(function () {
const customhtmlblockGrid = new window.prestashop.component.Grid('customhtmlblock');
customhtmlblockGrid.addExtension(new window.prestashop.component.GridExtensions.SortingExtension());
customhtmlblockGrid.addExtension(new window.prestashop.component.GridExtensions.FiltersResetExtension());
customhtmlblockGrid.addExtension(new window.prestashop.component.GridExtensions.ColumnTogglingExtension());
customhtmlblockGrid.addExtension(new window.prestashop.component.GridExtensions.SubmitRowActionExtension());
});
</script>
{% endblock %}
@@ -0,0 +1,25 @@
{% extends '@PrestaShop/Admin/layout.html.twig' %}
{% block content %}
{% block customhtmlgroup_list %}
<div class="row">
<div class="col">
{% include '@PrestaShop/Admin/Common/Grid/grid_panel.html.twig' with {'grid': customHtmlGroupGrid} %}
</div>
</div>
{% endblock %}
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script>
$(document).ready(function () {
const customhtmlgroupGrid = new window.prestashop.component.Grid('customhtmlgroup');
customhtmlgroupGrid.addExtension(new window.prestashop.component.GridExtensions.SortingExtension());
customhtmlgroupGrid.addExtension(new window.prestashop.component.GridExtensions.FiltersResetExtension());
customhtmlgroupGrid.addExtension(new window.prestashop.component.GridExtensions.ColumnTogglingExtension());
customhtmlgroupGrid.addExtension(new window.prestashop.component.GridExtensions.SubmitRowActionExtension());
});
</script>
{% endblock %}
+16
View File
@@ -0,0 +1,16 @@
{if !empty($groupList)}
<div class="customhtml-container {$hookName|escape:'html':'UTF-8'}--container">
{foreach from=$groupList item="group"}
<div class="customhtml-group">
{foreach from=$group.blocks item="block"}
<div class="customhtml-block">
{if $block.show_title && !empty($block.title)}
<div class="customhtml-title">{$block.title|escape:'html':'UTF-8'}</div>
{/if}
<div class="customhtml-content">{$block.content nofilter}</div>
</div>
{/foreach}
</div>
{/foreach}
</div>
{/if}
+43
View File
@@ -0,0 +1,43 @@
<?php
/**
* 2007-2024 De Websmid BV
*
* @author Isabelle Oving-Anno | De Websmid BV <isabelle@dewebsmid.nl>
* @copyright 2007-2024 De Websmid BV
* @license MIT
*/
use Websmid\CustomHtml\Module\Install;
use Websmid\CustomHtml\Module\AdminHooks;
use Websmid\CustomHtml\Module\DisplayHooks;
use PrestaShop\PrestaShop\Core\Module\WidgetInterface;
if (!defined('_PS_VERSION_')) {
exit;
}
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once __DIR__ . '/vendor/autoload.php';
}
class Ws_CustomHtml extends Module implements WidgetInterface
{
use Install;
use AdminHooks;
use DisplayHooks;
public function __construct()
{
$this->name = 'ws_customhtml';
$this->version = '1.1.0';
$this->author = 'Isabelle Oving-Anno | De Websmid BV';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->trans('Custom HTML', [], 'Modules.Wscustomhtml.Admin');
$this->description = $this->trans('Create and manage custom HTML blocks for frontend hooks.', [], 'Modules.Wscustomhtml.Admin');
$this->ps_versions_compliancy = ['min' => '1.7.0.0', 'max' => _PS_VERSION_];
}
}