### Module Configuration via YAML Source: https://devdocs.prestashop-project.org/8/modules/testing/resources Example of a YAML configuration file used to automate module settings, SQL execution, file copying, and complex PHP logic during module setup. ```yaml configuration: update: PAYPAL_SANDBOX: 1 delete: - "PAYPAL_ONBOARDING" sql: - "sql/default-config.sql" files: - source: "/path/to/source/file.txt" dest: "/module/path/docs/file.txt" php: - file: "path/to/file.php" params: - myParam1: 1 ``` -------------------------------- ### Advanced install() Method with Configuration and Multistore Source: https://devdocs.prestashop-project.org/8/modules/creation/tutorial An advanced implementation of the install() method that includes checks for the Multistore feature and sets the context to all shops if enabled. It also updates a configuration value using Configuration::updateValue(). The method returns true only if the parent install process and the configuration update are successful, otherwise, it returns false, aborting the installation. ```php public function install() { if (Shop::isFeatureActive()) { Shop::setContext(Shop::CONTEXT_ALL); } return ( parent::install() && Configuration::updateValue('MYMODULE_NAME', 'my module') ); } ``` -------------------------------- ### Execute PrestaShop Installation with Arguments Source: https://devdocs.prestashop-project.org/8/basics/installation/advanced/install-from-cli Demonstrates how to run the CLI installer with mandatory configuration arguments such as domain, database credentials, and admin account details. ```bash php index_cli.php \ --domain=example.com \ --db_server=sql.example.com \ --db_name=myshop \ --db_user=root \ --db_password=123456789 \ --prefix=myshop_ \ --email=me@example.com \ --password=mystrongpassword ``` -------------------------------- ### PHP Webservice Library Example Source: https://devdocs.prestashop-project.org/8/webservice/tutorials/advanced-use/manage-configuration Example demonstrating how to use the PrestaShop Webservice library in PHP to manage configuration settings, including checking, creating, and updating. ```APIDOC ## PHP Webservice Library Usage ### Description This code snippet demonstrates how to use the PrestaShop Webservice PHP library to dynamically manage a configuration setting (`PS_MULTISHOP_FEATURE_ACTIVE`). It first checks if the configuration exists, then either creates it using a POST request or updates it using a PUT request based on the existence check. ### Language PHP ### Code Example ```php get([ 'resource' => 'configurations', 'filter[name]' => '['. $configurationName . ']', ]); $configurationId = null; if ($xml->configurations->configuration->count() > 0) { $configurationId = (int) $xml->configurations->configuration[0]->attributes()['id']; } // Get the base XML, either a blank one or the existing one if (null === $configurationId) { // Fetch a blank XML structure for a new configuration $configurationXml = $webService->get(['url' => $webServiceUrl . 'api/configurations?schema=blank']); } else { // Fetch the existing configuration to be updated $configurationXml = $webService->get([ 'resource' => 'configurations', 'id' => $configurationId, ]); } // Update values in the XML structure // Ensure the XML structure has a 'configuration' element to modify if ($configurationXml->configurations->configuration->count() > 0) { $configurationXml->configurations->configuration[0]->name = $configurationName; $configurationXml->configurations->configuration[0]->value = $configurationValue; } else { // If fetching a blank schema, we might need to create the structure manually // This part might need adjustment based on the exact 'blank' schema response $newConfiguration = $configurationXml->configurations->addChild('configuration'); $newConfiguration->addChild('name', $configurationName); $newConfiguration->addChild('value', $configurationValue); } } catch (PrestaShopWebserviceException $e) { // Handle exceptions, e.g., invalid URL, key, or network issues echo 'Error:' . $e->getMessage() . PHP_EOL; exit; } // Either create new configuration or update it if (null === $configurationId) { try { // Add the new configuration $webService->add([ 'resource' => 'configurations', 'postXml' => $configurationXml->asXML(), ]); echo 'Successfully created configuration ' . $configurationName . ' = ' . $configurationValue . PHP_EOL; } catch (PrestaShopWebserviceException $e) { echo 'Error while adding the configuration:' . $e->getMessage() . PHP_EOL; } } else { try { // Update the existing configuration $webService->edit([ 'resource' => 'configurations', 'id' => $configurationId, 'putXml' => $configurationXml->asXML(), ]); echo 'Successfully updated configuration ' . $configurationName . ' = ' . $configurationValue . PHP_EOL; } catch (PrestaShopWebserviceException $e) { echo 'Error while updating the configuration:' . $e->getMessage() . PHP_EOL; } } ?> ``` ``` -------------------------------- ### Implement PrestaShop Module Installer (PHP) Source: https://devdocs.prestashop-project.org/8/modules/sample-modules/extending-sf-form-with-upload-image-field Provides an Installer class for PrestaShop modules, handling database table creation/deletion and hook registration. It includes methods for installation, uninstallation, database schema management, and hook setup. This class is designed to be used by the main module class. ```php registerHooks($module)) { return false; } if (!$this->installDatabase()) { return false; } return true; } /** * Module's uninstallation entry point. * * @return bool */ public function uninstall(): bool { return $this->uninstallDatabase(); } /** * Install the database modifications required for this module. * * @return bool */ private function installDatabase(): bool { $queries = [ 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'supplier_extra_image` ( `id_extra_image` int(11) NOT NULL AUTO_INCREMENT, `id_supplier` int(11) NOT NULL, `image_name` varchar(64) NOT NULL, PRIMARY KEY (`id_extra_image`) ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8;`, ]; return $this->executeQueries($queries); } /** * Uninstall database modifications. * * @return bool */ private function uninstallDatabase(): bool { $queries = [ 'DROP TABLE IF EXISTS `'._DB_PREFIX_.'supplier_extra_image`', ]; return $this->executeQueries($queries); } /** * Register hooks for the module. * * @param Module $module * * @return bool */ private function registerHooks(Module $module): bool { $hooks = [ 'actionSupplierFormBuilderModifier', 'actionAfterCreateSupplierFormHandler', 'actionAfterUpdateSupplierFormHandler', ]; return (bool) $module->registerHook($hooks); } /** * A helper that executes multiple database queries. * * @param array $queries * * @return bool */ private function executeQueries(array $queries): bool { foreach ($queries as $query) { if (!Db::getInstance()->execute($query)) { return false; } } return true; } } ``` -------------------------------- ### Install MySQL Utilities Source: https://devdocs.prestashop-project.org/8/basics/keeping-up-to-date/migration Command to install the necessary package for database comparison utilities on Ubuntu systems. ```bash apt install mysql-utilities ``` -------------------------------- ### PHP Example: Using ShopConstraint Source: https://devdocs.prestashop-project.org/8/development/multistore/shops-configuration A practical PHP code example illustrating how to inject the legacy configuration adapter and use the ShopConstraint value object to retrieve a configuration value within a controller. ```APIDOC ## PHP Example: Fetching Configuration with ShopConstraint ### Description This code snippet shows how to obtain the `prestashop.adapter.legacy.configuration` service and instantiate a `ShopConstraint` value object to fetch a specific configuration value (`PS_ROUND_TYPE`) for a given shop and shop group. ### Method N/A (Illustrative PHP Code) ### Endpoint N/A (Illustrative PHP Code) ### Parameters - **$container**: Service container instance. - **$order->id_shop**: The ID of the shop. - **$order->id_shop_group**: The ID of the shop group. ### Request Example ```php get('prestashop.adapter.legacy.configuration'); // Instantiate a ShopConstraint value object $shopConstraint = new ShopConstraint( (int) $order->id_shop, (int) $order->id_shop_group ); // Get the needed configuration value, passing your ShopConstraint object as a third parameter $roundType = (int) $configuration->get('PS_ROUND_TYPE', null, $shopConstraint); // Use the fetched configuration value // ... } } ``` ### Response - **$roundType** (int) - The integer value of the 'PS_ROUND_TYPE' configuration setting for the specified shop context. ### Response Example ```php // If PS_ROUND_TYPE is set to 1 for the specified shop context $roundType = 1; ``` ``` -------------------------------- ### Install Module via CLI Source: https://devdocs.prestashop-project.org/8/modules/creation/adding-configuration-page-modern Commands to install and enable the module using the PrestaShop console. ```bash php bin/console prestashop:module install demosymfonyformsimple php bin/console prestashop:module enable demosymfonyformsimple ``` -------------------------------- ### Basic install() Method for PrestaShop Module Source: https://devdocs.prestashop-project.org/8/modules/creation/tutorial The most basic implementation of the install() method for a PrestaShop module. It simply calls the parent class's install() method and returns its result. This method is crucial for performing actions during module installation, such as creating database tables or setting up configuration variables. ```php public function install() { return parent::install(); } ``` -------------------------------- ### Integrate Installer with Main Module Class (PHP) Source: https://devdocs.prestashop-project.org/8/modules/sample-modules/extending-sf-form-with-upload-image-field Shows how to integrate the 'Installer' class within the main PrestaShop module class ('DemoExtendSymfonyForm2'). It overrides the 'install' and 'uninstall' methods to instantiate and call the respective methods of the 'Installer' class, ensuring proper setup and cleanup of module resources. ```php install($this); } /** * @return bool */ public function uninstall() { $installer = new Installer(); return $installer->uninstall() && parent::uninstall(); } ``` -------------------------------- ### Run PrestaShop CLI Installer Source: https://devdocs.prestashop-project.org/8/basics/installation/advanced/install-from-cli Executes the CLI installer script located in the install directory. This command displays available options when run without arguments. ```bash php index_cli.php ``` -------------------------------- ### Install Module Database and Fixtures in PHP Source: https://devdocs.prestashop-project.org/8/modules/sample-modules/order-pages-new-hooks/module-base This class is responsible for the module's installation process, including registering hooks, creating the database schema, and populating it with initial data using FixturesInstaller. It utilizes PrestaShop's DbCore for database operations. ```PHP * @copyright Since 2007 PrestaShop SA and Contributors * @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0 */ declare(strict_types=1); namespace PrestaShop\Module\DemoViewOrderHooks\Install; use Db; use Module; /** * Class responsible for modifications needed during installation/uninstallation of the module. */ class Installer { /** * @var FixturesInstaller */ private $fixturesInstaller; public function __construct(FixturesInstaller $fixturesInstaller) { $this->fixturesInstaller = $fixturesInstaller; } /** * Module's installation entry point. * * @param Module $module * * @return bool */ public function install(Module $module): bool { if (!$this->registerHooks($module)) { return false; } if (!$this->installDatabase()) { return false; } $this->fixturesInstaller->install(); return true; } /** * Module's uninstallation entry point. * * @return bool */ public function uninstall(): bool { return $this->uninstallDatabase(); } /** * Install the database modifications required for this module. * * @return bool */ private function installDatabase(): bool { $queries = [ 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'order_signature` ( `id_signature` int(11) NOT NULL AUTO_INCREMENT, `id_order` int(11) NOT NULL, `filename` varchar(64) NOT NULL, PRIMARY KEY (`id_signature`), UNIQUE KEY (`id_order`) ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8;`, ]; return $this->executeQueries($queries); } /** * Uninstall database modifications. * * @return bool */ private function uninstallDatabase(): bool { ``` -------------------------------- ### WsArticle Module - Main File Source: https://devdocs.prestashop-project.org/8/webservice/extend-webservice This snippet shows the main PHP file for the WsArticle module, including its constructor, installation logic, database installation method, and the hook for adding webservice resources. ```APIDOC ## WsArticle Module - Main File ### Description This file defines the main class for the WsArticle module. It handles module initialization, installation, database table creation, and registration of 'articles' as a webservice resource. ### Method ```php name = 'wsarticle'; $this->tab = 'front_office_features'; $this->version = '1.0.0'; $this->author = 'PrestaShop'; $this->need_instance = 0; $this->secure_key = Tools::encrypt($this->name); $this->bootstrap = true; parent::__construct(); $this->displayName = $this->getTranslator()->trans('Extend WS demo module', array(), 'Modules.Wsarticle.Admin'); } public function install() { return parent::install() && $this->installDB() && // Create tables in the DB $this->registerHook('addWebserviceResources'); // Register the module to the hook } public function installDB() { $sql = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.Article::$definition['table'].'` ( `id_article` int(10) unsigned NOT NULL AUTO_INCREMENT, `type` varchar(255), `date_add` datetime NOT NULL, `date_upd` datetime NOT NULL, PRIMARY KEY (`id_article`) ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci'; $sql_lang = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.Article::$definition['table'].'_lang` ( `id_article` int(10) unsigned NOT NULL, `id_lang` int(10) unsigned NOT NULL, `title` varchar(255), `content` text NOT NULL, `meta_title` varchar(255) NOT NULL, PRIMARY KEY (`id_article`, `id_lang`) ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci'; if (Db::getInstance()->execute($sql) && Db::getInstance()->execute($sql_lang)) { return true; } return false; } public function hookAddWebserviceResources($params) { return [ 'articles' => [ 'description' => 'Blog articles', // The description for those who access to this resource through WS 'class' => 'Article', // The classname of your Entity 'forbidden_method' => array('DELETE') // Optional, if you want to forbid some methods ] ]; } } ``` ``` -------------------------------- ### Install Git on Linux Source: https://devdocs.prestashop-project.org/8/themes/getting-started/tools-for-theme-designers Installs the Git version control system on Debian-based Linux distributions using the apt package manager. ```bash apt install git ``` -------------------------------- ### Install Shop Creator Dependencies Source: https://devdocs.prestashop-project.org/8/scale/benchmark/back-office Installs the necessary Composer dependencies for the PrestaShop Shop Creator. This command should be run from within the Shop Creator directory. ```bash composer install ``` -------------------------------- ### Automate PrestaShop Installation via Environment Variables Source: https://devdocs.prestashop-project.org/8/basics/installation/environments/docker Environment variables required to bypass the manual installation assistant and automatically populate the database with test data. ```yaml PS_INSTALL_AUTO: 1 PS_DOMAIN: localhost:8080 ``` -------------------------------- ### Database Schema Diff Examples Source: https://devdocs.prestashop-project.org/8/basics/keeping-up-to-date/migration Examples of schema differences encountered during migration, including adding columns, changing column sizes, and removing columns. ```sql -- New column example --- `prestashop16`.`ps_cart` +++ `prestashop`.`ps_cart` @@ -18,6 +18,7 @@ `allow_seperated_package` tinyint(1) unsigned NOT NULL DEFAULT '0', `date_add` datetime NOT NULL, `date_upd` datetime NOT NULL, + `checkout_session_data` mediumtext, [...] -- Column size change example - `lastname` varchar(32) NOT NULL, + `lastname` varchar(255) NOT NULL, -- Column removed example - `scenes` tinyint(1) NOT NULL DEFAULT '1', ``` -------------------------------- ### Clone and Install Prestashop Shop Creator Source: https://devdocs.prestashop-project.org/8/scale/benchmark This snippet shows how to clone the PrestaShop Shop Creator repository and install its dependencies using Composer. This tool helps in generating a dataset for benchmarking. ```bash git clone https://github.com/PrestaShop/prestashop-shop-creator cd prestashop-shop-creator composer install ``` -------------------------------- ### Use Grid Data Factory to Get Product Data Source: https://devdocs.prestashop-project.org/8/development/components/grid Utilize the configured Grid Data factory with search criteria to retrieve sorted, paginated, and filtered data for a grid. This example shows how to get records, total count, and the executed query. ```php $searchCriteria = ... /** PrestaShop\PrestaShop\Core\Grid\Data\Factory\GridDataFactoryInterface $productGridDataFactory */ $productGridDataFactory = $container->get('prestashop.core.grid.data.factory.product_data_factory'); $productGridData = $productDataFactory->getData($searchCriteria); $productGridData->getRecords(); // returns RecordCollection that contains products data $productGridData->getRecordsTotal(); // returns the total count of products $productGridData->getQuery(); // get the last executed query that was used to get RecordCollection ``` -------------------------------- ### Initialize PrestaShop Webservice Client Source: https://devdocs.prestashop-project.org/8/webservice/tutorials/prestashop-webservice-lib/setup-library Demonstrates how to instantiate the PrestaShopWebservice class using either Composer autoloading or manual file inclusion. ```php require_once('./vendor/autoload.php'); $webService = new PrestaShopWebservice('http://example.com/', 'ZR92FNY5UFRERNI3O9Z5QDHWKTP3YIIT', false); ``` ```php require_once('./PSWebServiceLibrary.php'); $webService = new PrestaShopWebservice('http://example.com/', 'ZR92FNY5UFRERNI3O9Z5QDHWKTP3YIIT', false); ``` -------------------------------- ### Define Behat Feature Scenario Source: https://devdocs.prestashop-project.org/8/testing/integration-tests/how-to-create-your-own-behat-tests An example of a Gherkin scenario for testing free shipping vouchers in a PrestaShop cart, demonstrating the use of existing context steps for setup and verification. ```gherkin Scenario: With free shipping voucher, there is no shipping fees Given I have an empty default cart And there is a product in the catalog named "product1" with a price of 50.0 and 1000 items in stock And there is a zone named "North America" And there is a country named "country1" and iso code "US" in zone "North America" And there is a state named "state1" with iso code "TEST-1" in country "country1" and zone "North America" And there is an address named "address1" with postcode "1" in state "state1" Given there is a carrier named "carrier1" And carrier "carrier1" applies shipping fees of 5.0 in zone "North America" for price between 0 and 150 Given there is a cart rule named "free4behat" that applies no discount with priority 4, quantity of 1000 and quantity per user 1000 And cart rule "free4behat" offers free shipping And cart rule "free4behat" has a discount code "free4behat" When I add 1 items of product "product1" in my cart Then my cart total should be 57.0 tax included When I use the discount "free4behat" Then my cart total should be 50.0 tax included ``` -------------------------------- ### Fetching Shop Configuration in Multistore Context Source: https://devdocs.prestashop-project.org/8/development/multistore/shops-configuration This example demonstrates how to fetch a configuration value in a multistore context using the legacy configuration adapter and the ShopConstraint value object. ```APIDOC ## POST /api/shops/configuration ### Description Fetches a configuration value from the PrestaShop 8 system, specifically designed to handle multistore contexts by allowing the specification of a target shop or shop group. ### Method GET ### Endpoint /api/shops/configuration ### Parameters #### Query Parameters - **key** (string) - Required - The configuration key to retrieve. - **shop_id** (int) - Optional - The ID of the specific shop to fetch the configuration for. If not provided, the current shop context is used. - **shop_group_id** (int) - Optional - The ID of the shop group to fetch the configuration for. If not provided, and shop_id is provided, the shop's group is inferred. #### Request Body This endpoint does not typically use a request body for GET requests. ### Request Example ```json { "key": "PS_ROUND_TYPE", "shop_id": 3, "shop_group_id": 2 } ``` ### Response #### Success Response (200) - **value** (string) - The configuration value for the specified context. #### Response Example ```json { "value": "1" } ``` ### Error Handling - **400 Bad Request**: If the required 'key' parameter is missing or invalid. - **404 Not Found**: If the configuration key does not exist for the specified context. ``` -------------------------------- ### TypeScript Loader Configuration (Webpack) Source: https://devdocs.prestashop-project.org/8/modules/concepts/templating/import-js Provides an example of a TypeScript loader configuration for Webpack, which is necessary when importing TypeScript files. This setup ensures that TypeScript files are correctly processed by the bundler. ```javascript { test: /\.ts?$/, use: 'ts-loader', exclude: /node_modules/, } ``` -------------------------------- ### Initialize Grid Component with Extensions Source: https://devdocs.prestashop-project.org/8/development/components/global-components Illustrates how to instantiate the Grid component and attach specific extensions like ColumnTogglingExtension to enhance functionality. ```javascript const grid = new window.prestashop.component.Grid(gridId); grid.addExtension(new window.prestashop.component.GridExtensions.ColumnTogglingExtension()); ``` -------------------------------- ### Clone PrestaShop Postman Examples Repository Source: https://devdocs.prestashop-project.org/8/webservice/tutorials/testing-webservice-postman This command clones the official PrestaShop repository containing Postman collections used for testing the Webservice API. It requires Git to be installed on your local machine. ```bash git clone git@github.com:PrestaShop/webservice-postman-examples.git ``` -------------------------------- ### Initialize Database Connection Source: https://devdocs.prestashop-project.org/8/development/components/database/db Demonstrates how to obtain a database connection instance. The first call initializes the link, which is then reused for subsequent operations. ```php /** @var \Db $db */ $db = \Db::getInstance(); ``` -------------------------------- ### Render Grid in Back Office Controller Source: https://devdocs.prestashop-project.org/8/development/components/grid Create and render a Grid within a Back Office controller using the configured Grid Factory. This example demonstrates fetching the factory, getting the grid, and passing it to the Twig template. ```php get('prestashop.core.grid.product_grid_factory'); $productGrid = $productGridFactory->getGrid($searchCriteria); return $this->render('@PrestaShop/Admin/Product/products.html.twig', [ // $this->presentGrid() is a helper method provided by FrameworkBundleAdminController 'productsGrid' => $this->presentGrid($productGrid), ]); } } ``` -------------------------------- ### Add Product Command Source: https://devdocs.prestashop-project.org/8/development/architecture/domain/references/product Creates a new product with basic information. ```APIDOC ## Add Product Command ### Description Creates a new product with basic information. ### Method POST ### Endpoint /api/products ### Parameters #### Request Body - **productType** (string) - Required - The type of product (e.g., 'standard', 'virtual'). - **shopId** (int) - Required - The ID of the shop where the product will be added. - **localizedNames** (object) - Required - An object containing product names localized by language code. - **langCode** (string) - Required - The language code (e.g., 'en', 'fr'). - **name** (string) - Required - The product name in the specified language. ### Request Example ```json { "productType": "standard", "shopId": 1, "localizedNames": { "en": {"name": "Example Product"}, "fr": {"name": "Produit Exemple"} } } ``` ### Response #### Success Response (200) - **productId** (int) - The ID of the newly created product. #### Response Example ```json { "productId": 123 } ``` ``` -------------------------------- ### Render PrestaShop Form in Twig Source: https://devdocs.prestashop-project.org/8/development/architecture/migration-guide/forms/settings-forms This Twig code snippet demonstrates how to render a form, including its start and end tags, form fields, and a submit button. It utilizes PrestaShop's custom form theme for rendering elements compatible with the PrestaShop UI Kit. The example shows how to render a 'Logs by email' form with a 'Minimum severity level' field. ```twig {{ form_start(logsByEmailForm) }}