Home
Prestashop - 1.4 Developer's Guide
Contents
1. accepted updateOrderStatus Class Called when an OrderHistory php order s status is changed right before it is actually changed postUpdateOrderStatus Class Called when an OrderHistory php order s status is changed right after it is actually changed cancelProduct AdminOrders php Called when an item is deleted from an order right after the deletion invoice AdminOrders php Called when the order s details are displayed above the Client Information block adminOrder AdminOrders php Called when the order s details are displayed below the Client Information block orderSlip AdminOrders php Called during the creation of a credit note right after it has been created Products Hook name File location Visible Description addproduct AdminProducts php No Called when a product is created or duplicated right creation duplication updateproduct AdminProducts php No Called when a product is update with a new picture right after said update deleteproduct Class Product php Called when a product is deleted right before said deletion updateQuantity Class Called during an the PaymentModule php validation of an order the status of which being something other than canceled or Payment error for each of the order s items updateProductAttribute Class Product php Called when a product declination is updated right after said update watermark AdminProducts php Called when an image
2. PHP Doc Element comment is required before the method declarations Return field value if possible both classical and multilingual fields FF F F HF Case 1 Return value if present in POST GET Case 2 Return object value param object Sobj Object param string key Field name param integer id lang Language id optional return string protected function getFieldValue obj key id lang NULL OF or more informations For more informations about the PHP Doc norm http manual phpdoc org HTMLSmartyConverter HandS phpDocumentor tutc Return values OM XAORWND O Return statement does not need brackets except when it deals with a composed expression retu retu retu retu reru rn result rn a b rn a b rn true Break a function rn Function call preceded by a is forbidden but beware with function method call with login password or path argmuments myfunction In the following exemple we put a for security reasons mysql connect Tags ODUN An empty line has to be left after the PHP opening tag lt php require once my file inc php The PHP ending tag is forbidden Indentation oO OMOAAID OB W The tabulation character t is the only indentation character allowed Each indentation level must be represented by a single tabulation character function foo Sa if
3. Sa null return false eee Array RwN Pe Ju 6 p 8 9 10 11 12 13 14 Bloc The array keyword must not be followed by a space array 17 23 42 The indentation when too much datas are inside an array has to follow the following Sa array 36 gt Sb Sc gt foo Sd gt array 17 23 42 Se gt array 0 gt zero 1 gt Sone 3 Brasses are prohibited when they define only one instruction or a statement combination if Sresult for Si 0 return false 7 Si lt 17 Sit if SmyArray i value Sresult SmyArray Si else Sfailed Security 1 2 3 4 5 6 All user datas datas entered by users have to be casted data Tools getValue name SmyObject gt street number int Tools getValue street_number All method function s parameters must be typed when Array or Object when received public myMethod Array S varl Svar2 Object S var3 For all other parameters they have to be casted each time they are use but not when sent to other methods functions protected myProtectedMethod Sid text Sprice Sthis gt id int id Sthis gt price float price Sthis gt callMethod S id Sprice Limitations 1 2 Source code lines are limited to 120 characters Functions and methods lines are limited to 80 with good justifications Other 1 2 3 It s forbidden to use
4. equivalents then displays the generated result Those dynamic elements are indicated with curly brackets The programmer may create new variables and use them in TPL files For instance in OUr mymodule page php we can create such a variable mymodule_page php lt php global S smarty include config config inc php include header php Smymodule new MyModule message Smymodule gt 1 Welcome to my shop Ssmarty gt assign messageSmarty message creation of our variable Ssmarty gt display dirname FILE mymodule page tpl include footer php gt From there on we can ask Smarty to display the content of this variable in our TPL file mymodule_page tpl SmessageSmarty PrestaShop includes a number of variables For instance HOOK_LEFT_COLUMN will be replaced with the content for the left column meaning the content from all the modules that have been attached to the left column s hook All Smarty variables are global You should therefore pay attention not to name your own variable with the name of an existing Smarty variable in order to avoid overwriting it It is good practice to avoid overly simple names such aS products and to prefix it with your module s name or even your own name such as mark_mymodule_product Here is a list of Smarty variables that are common to all pages File folder Description img_ship_dir URL for
5. a ternary into another ternary We recommend to use amp amp and into your conditions Please don t use reference parameters SQL Table names RwNn Pe Table names must begin with the PrestaShop DB_PREFIX prefix FROM DB PREFIX customer Table names must have the same name as the object they reflect e g ps_cart Table names have to stay singular e g ps_order 6 Language data have to be stored in a table named exactly like the object s one and with the suffix _lang e g ps_product_lang SQL query 1 Keywords must be written in uppercase SELECT firstname UIs Wh FROM DB PREFIX customer Back quotes must be used around field names and table names 6 7 SELECT Ppr foo y c bar 8 FROM _DB_PREFIX_ product p _DB_PREFIX customer c 9 Table aliases have to be make by taking the first letter of each word and must be lowercase 10 11 SELECT p id product pl name 12 FROM DB PREFIX product p 13 NATURAL JOIN DB PREFIX product lang pl 14 When conflicts between table aliases occur the second character has to be taken too Los 16 SELECT ca id product cu firstname 17 FROM DB PREFIX cart ca i DB PREFIX customer cu 18 Indentation has to be done for each clause 19 20 query SELECT pl name 21 FROM PS DB
6. file placed at the root of the module s folder TPL files can have just about any name It there s only one such file it is good practice to give it the same name as the folder and main file mymodule tpl The mymodule php file must start with the following test if defined PS VERSION exit This checks for the existence of a PHP constant and if it doesn t exist it quits The sole purpose of this is to prevent visitors to load this file directly The file must also contain the module s class PrestaShop uses Object Oriented programming and so do its modules That class must bear the same name as the module and its folder in CamelCase myModule Furthermore that class must extend the module class and thus inherits all methods and attributes It can just as well extend any class derived from Module PaymentModule ModuleGridEngine ModuleGraph mymodule php lt php if defined PS VERSION exit class MyModule extends Module public function _ construct Sthis gt name mymodule Sthis gt tab Test Sthis gt version 1 0 Sthis gt author Firstname Lastname Sthis gt need_ instance 0 parent construct Sthis gt displayName Sthis gt 1l1 My module Sthis gt description Sthis gt l Description of my module public function install if parent install false return false return true gt Let s examine each li
7. is added to an product right after said addition Statistics Hook name File location Visible Description GraphEngine Class Yes Called when a stats ModuleGraph php graph is displayed GridEngine Module Called when the GridEngine php grid of stats is displayed AdminStatsModules AdminStatsTab php Yes Called when the list of stats modules is displayed Clients Hook name File location Visible Description adminCustomers AdminCustomers php Yes Called when a client s details are displayed right after the list of the clients groups the current client belongs Carriers Hook name File location Visible Description updateCarrier AdminCarriers php No Called during a carrier s update right after said update Creating a PrestaShop module Modules operating principles Modules are the ideal way to let your talent and imagination as a developer express themselves as the creative possibilities are many They can display a variety of content blocks text etc perform many tasks batch update import export etc interface with other tools Modules can be made as configurable as necessary the more configurable it is the easier it will be to use and thus will be able to address the need of a wider range of users One of the main interest of a module is to add functionalities to PrestaShop without having to edit its core files this making it easier to perform an update without having the transpose all core chan
8. the carriers shipping images folder come_from URL for the visitor s origin shop_name Shop name cart_qties Number of products in the cart cart The cart currencies The various available currencies id_currency_cookie ID of the current currency currency Currency object currently used currency cookie User cookie languages The various available languages logged Indicates whether the visitor is logged to a customer account priceDisplay Price display method with or without taxes If you need to have all of the current page s Smarty variables displayed add the following function debug Comments are based on asterisk This string is commented out This string is too Unlike with HTML comments commented out Smarty code is not present in the final output file Module translation Our module s text strings are written in English but we might want French shop owners to use our module too We therefore have to translate those strings into French both front office and back offices ones This could be a tedious task but Smarty and PrestaShop s own translation make it far easier Strings in PHP files will need to be displayed through the method from the module php abstract class mymodule php partial Sthis gt 1 My module Sthis gt 1 Description of my module Sthis gt displayName Sthis gt description Strings in TPL files will need to be turned into dynami
9. true Recommendation We recommend one return per method function WO OnwAID 10 When a method function returns a boolean and the current method function return depends on it the if statement has to be avoided 11 12 public aFirstMethod T3 14 return this gt aSecondMethod 15 16 Tests must be grouped by entity ARTA 18 if price AND empty price 19 Deas 20 if Validate SmyObject OR myObject gt id NULL 2ks enc Visibility 1 The visibility must be defined everytime even when it is a public method 2 The order of the method properties should be visibility static function name 33 4 private static function foo Method Function names 1 Method and function name always begins with a lowercase character and each following words must begin with an uppercase character CamelCase public function myExempleMethodWithALotOfWordsInItsName Braces introducing method code have to be preceded by a carriage return Pon public function myMethod Sargl arg2 0 Method and function names must be explicit so such function names as b or ef are completly forbidden POONA WwW Exceptions The only exceptions are the translation function called I and debug functions p d Enumeration Commas have to be followed and only followed by a space protected function myProtectedMethod Sargl Sarg2 Sarg3 null Objects Classes
10. Object name must be singular Class Customer Class name must follow the CamelCase practice except that the first letter is uppercase RwWN Pe a Ul class MyBeautifulClass Defines 1 Define names must be written in uppercase 2 Define names have to be prefixed by PS_ inside the core and module 3 4 define PS DEBUG 1 5 define PS_MODULE NAME DEBUG 1 6 Define names does not allow none alphabetical characters Except m Keywords All keywords have to be lowercase e g as case if echo null Constants Constants must be uppercase except for true and false and null which must be lowercase e g ENT_NOQUOTE true Configuration variables Configuration variables follow same rules as defines Strings Strings have to be surrounded by simple quotes never double ones echo Debug SmyObj gt name Hello name Comments Inside functions and methods only the comment tag is allowed After the comment tag a space Comment is required My great comment The comment tag is tolerated at the end of a code line AN FwWNYH Ta a 17 23 A comment inside my exemple function 8 Outside funcions and methods only the and comment tags are allowed This method is required for compatibility issues public function foo ax 16 17 18 L9 Some code explanation right here
11. P product lang pl 22 WHERE pl id product 17 23 It s forbidden to make a join in WHERE clause
12. PrestaShop Developer Guide The technical documentation is currently being updated Some aspects of it might not yet be fully updated Do not hesitate to contact us if you have any issue with the documentation Fundamentals Concepts You should be familiar with PHP and Object Oriented Programming before attempting to write your own module PrestaShop was conceived so that third party modules could easily upon its foundations making it an extremely customizable e commerce software A module is an addition to PrestaShop that enables any developer to add the following e Provide additional functionality to PrestaShop e View additional items on the site product selection etc e Communicate with other e commerce players buying guides payment platforms logistics e etc The company behind PrestaShop provides more than 100 modules for free with the tool itself enabling you to launch your business quickly and for free More than 750 add ons are also available at the official add ons site These additional modules were built by the PrestaShop comapny or members of the PrestaShop community and are sold at affordable prices As a developer you can also share your modules on this site and receive 70 of the amounts associated with the sale of your creations Sign up now PrestaShop s technical architecture PrestaShop is based on a 3 tier architecture e Object data Database access is controlled through fil
13. a adi OATETIME popte TINYIT I 9 seare kay VARCHAR 32 nate TEXT 2 ctve TINYINT 1 Ss guest TINT 1 S deleted TINVINT 1 date_add DATETIME 9 date upd DATETIME or re Pa group INT 0 reduction DECMA 17 2 gt mm depay method TINN gt date _add DATETIME gt date_uod OATETIME Pid address INT 10 b d_country INT 10 _stte BVT 20 d_cmtoer er INT 10 _snarnsecturer INT 30 _guppher INT 10 Shas VARCHARL IZ company VARCHAR 32 strane ARCHAR 32 frstrame VARCHARL 32 sdcress VARCMAL 128 address VARCHAR 128 postcode VARCHAR 12 Oty VARCHAR 64 oiher TEXT phone VARCHAR 16 phone _mobie VARCHAR IS wat_mumber WRHROIJ da VROAR 16 date add DATETIME date upd DATETIME sctve TINYINT 1 deleted TINVINT 1 country INTL 20 fore VARCHAR 255 gt New Lover Fi Vid feferrar INT 10 name VARCHAR E4 pezswd ARCHAR 32 htip_refera regep VARCHAR 64 http refera Jke VARCHAR E4 equest un regep VARCHAR E4 request un Jke VAROIR GS http refera regep rol VAROR ES ht _pefere_jke CHAR request un regep_not Pequest_un_lke_not WROUR G4 bane _fe DEQMAL 5 2 percent ke DEGMA 5 2 dikk e DEGIMAL S 2 cache visitors INT 11 adw isis INTC cache pages INT 31 cache _regstratons INT 11 cache_orders IWT 11 cada ses DECIMAL 17 7 cache seg jate DECIMAL 5 4 cache_order rate DECIMAL 5 4 date_add DATETIME gt teeth Pid web bromsar INT 90 n
14. ame VARCHAR SA vid guest INT 10 id_aperating system INT 10 id_web_broweser INT 20 id ombone INT 20 Jmasoipt TINYINT 1 soreen_sesolution_x SMALLINT S svee_pecuton_y SMALLINT S sareen cokor TINYINT 3 an java TNYT 9 adobe fah TINANT I adobe_drector TIVINT 1 appie _quckine TINVINT 1 rea player TINCINT 1 windows meda TINYINT 1 accept_lenguage YVROURW tid ambona WT 10 id grop INT 20 gt ermee id _apa anng _systen INT 10 name V AROMA 64 gt product _guan ty INT 30 product_quensty_n_stock INT 20 prodat arity ended INT 10 product gan ty eten INTI 10 Droduct_quanaity_seinjected INT 10 gt product _price DECOM A 20 4 reduction percert DECIMAL 20 2 b reduction amount DECIA 20 6 p oup_reducton DECMAL 20 2 product_qaraty_dscourt DECIMAL 20 4 product product upc WARCHAR 12 ence VARCHAR 22 art 13 WARCHAR 3 product n product_supplier_reference YVARCHAR JZ p product _meight FLOAT b tax_name VARCHAR 16 gt tax_rote DECIMAL 10 3 gt ecotax DEI MAL 21 4 gt ecotax ee jate DECIMAL S 3 pdsmunt aunity appied TINYINT 1 download _hash VARCHAR 255 toertoad_rb INT 10 download _deadine DATETIME You can download the PrestaShop 1 4 SQL schema in PNG form 1 Mb or in the original MySQL Workbench file format you will need MySQL Workbench to view it What is a PrestaShop module PrestaShop s exten
15. by going to the Employee tab then its Tabs sub tab Click the Add new button and fill in the fields with the class name AdminTest Do not confuse class with modules Choose an icon like one from the FamFamFam pack choose where the tab should go and save You re set Now start customizing it to your needs Troubleshooting If your module does not work as expected here are a few ways to find help PrestaShop official forum Join our forum at http www prestashop com forums and search for an answer using the relevant keywords If your search needs refining use the advanced search form And if your search doesn t yield anything useful create a new thread where you can be as wordy as necessary when writing your question you will need to registered first Some forums keep certain threads pinned on top of all threads they contain some useful information so be sure to read them through Our bug tracker If it turns out your issue stems from a PrestaShop bug rather than your code please do submit the issue in the PrestaShop bug tracker http forge prestashop com you will need to register This enables you to discuss the issue directly with the PrestaShop developers Official PrestaShop websites Description http www prestashop com Official website for the PrestaShop tool its community and the company behind it http addons prestashop com Marketplace for themes and modules http www pr
16. c content which Smarty will replace by the translation for the chosen language In our sample module this file mymodule tpl partial lt li gt lt a href Sbase_ dir modules mymodule mymodule page php title Click this link gt Click me lt a gt lt li gt becomes mymodule tpl partial lt li gt lt a href Sbase dir modules mymodule mymodule page php title 1 s Click this link mod mymodule gt 1 s Click me mod mymodule lt a gt lt li gt and this one mymodule_page tpl lt h4 gt Welcome lt h4 gt Click me becomes mymodule tpl lt h4 gt l s Welcome mod mymodule lt h4 gt 1 s Click me mod mymodule The translation tool needs the moa parameter in order to match the string to translate with its translation Strings are delimited with single quotes If a string contains single quotes they should be escaped using a backslash This way strings can be directly translated inside PrestaShop go to the Tools tab its Translations sub tab and in the Modify translations drop down menu choose Module translations then click the French flag in order to translate modules into French The next page displays all the strings for all the currently installed modules Modules that have all their strings already translated have their fieldset closed whereas if at least one string is missing in a module s translation its fieldset is expanded In order to tra
17. cho lt form action ScurrentIndex amp submitAdd Sthis gt table l token Sthis gt token method post class width3 gt Sobj gt id lt input type hidden name id_ S this gt table value Sobj gt id gt lt fieldset gt lt legend gt lt img src img admin profiles png gt this gt 1 Profiles lt legend gt lt label gt Sthis gt 1 Name lt label gt lt div class margin form gt foreach Slanguages as Slanguage echo lt div id name_ Slanguage id_lang id lang my style display Slanguage id lang id lang defaultLanguage block none float left gt lt input size 33 type text name name _ Slanguage id lang id lang value htmlentities this gt getFieldValue obj name intval Slanguage id lang id lang ENT COMPAT UTF 8 gt lt sup gt lt sup gt lt div gt Sthis gt displayFlags Slanguages defaultLanguage name name echo lt div class clear gt lt div gt lt div gt lt div class margin form gt lt input type submit value Sthis gt l Save name sSubmitAdd S this gt table class button gt lt div gt lt div class small gt lt sup gt lt sup gt Sthis gt l Required field lt div gt lt fieldset gt lt form gt 2 gt Put the files online then create the tab
18. ck v1 2 7 aE ba Displays a block with links relative to user account rm W Tags block v1 0 7 ar aa Adds a block containing a tag cloud ca i x J Categories block v2 0 7 GE hd Adds a block featuring product categories 5 a Viewed products block v0 9 2 aF nl Adds a block displaying last viewed products 6 a Op Manufacturers block v1 0 7 aH h Displays a block of manufacturers brands CMS Block v1 1 7 w b Adds a block with several CMS links A an 2 i dil Block advertising v0 3 J aR Displaying content Now that we have access to the left column we should display something there As said earlier the content to be displayed in the theme should be stored in tp1 files We will create the mymodule tpi file which was passed as a parameter of the display method in our module s code So let s create the mymodule tpi file and add some lines of code to it mymodule tpl lt Block mymodule gt lt div id mymodule block left class block gt lt h4 gt Welcome lt h4 gt lt div class block_content gt lt ul gt lt li gt lt a href S base_ dir modules mymodule mymodule page php title Click this link gt Click me lt a gt lt li gt lt ul gt lt div gt lt div gt lt Block mymodule gt Save the file in the module s root folder reload your shop s homepage it should appear on top of the left column right below the shop s logo AG PRESTASHOP_ Click me MY ACCOUNT gt gt M
19. column home index php Yes Called at the center of the homepage Product sheet Hook name File Visible Description location extraLeft product php Yes Called right before the Print link under the picture extraRight product php Yes Called right after the block for the Add to Cart button productActions product php Yes Called inside the block for the Add to Cart button right after that button productOutOfStock product php Yes Called inside the block for the Add to Cart button right after the Availability information productTab product php Yes Called in tabs list such as More info Data sheet Accessories Ideal location for one more tab the content of which is handled by the productTabContent hook productTabContent product php Yes Called when a tab is clicked Ideal location for the content of a tab that has been defined using the Cart Hook name cart shoppingCart shoppingCartExtra createAccountTop File location Class Cart php order php order php authentication php createAccountForm authentication php createAccount customerAccount myAccountBlock authentication php my account php Module blockmyaccount php productTab hook Visible No Yes Yes Yes Yes No Yes Yes Description Called right after a cart creation or update Called right below the cart items table Called after the cart s table of items right above the na
20. ct these requirements e 16 16 image e named logo gif e placed on the module s main folder You can find an excellent set of free icons to pick from on the FamFamFam website Now that all basics are in place put the module s folder in the modules folder of your PrestaShop test install open PrestaShop and in the Modules tab under Other Modules you should find your module Install it in order to be able to manage it for the rest of this guide Market Place 1 module Other Modules 2 modules Info block v1 1 Adds a block with several information links x Install Delete My module v1 0 Description of my module A Module installed successfully v4 Uninstall Disable Reset Delete Migration Tools 2 modules PrestaShop automatically creates a small config xmi file in the module s folder which stores a few configuration information You should NEVER edit it by hand On installation PrestaShop also adds a line to the ps module SQL table B 514 statssearch 1 d ee 52 statscheckup 1 B e 53 mymodule 1 Hooking a module Displaying data starting a process at a specific time in order for a module to be attached to a location on the front office or the back office you need to give it access to one of the many PrestaShop hooks described earlier in this guide To that effect we are going to change your module s code and add these lines mymodule php partial public function instal
21. es in the classes folder e Data control User provided content is controlled by files in the root folder e Design All of the theme s files are in the themes folder PrestaShop s 3 tier architecture E JQ E Object data Database access is User provided content All of the theme s files controlled through files is controlled by files are in the themes in the classes folder in the root folder folder This is the same principle as the Model view controller MVC architecture only in a simpler and more accessible way Our developer team chose not to use a PHP framework such as Zend Framework Symfony or CakePHP so as to allow for better readability and thus faster editing This also makes for higher performances since the software is only made of the lines of code it requires and does not contain a bunch of supplemental generic libraries A 3 tier architecture has many advantages It s easier to read the software s code Developers can add and edit code faster Graphic designer and HTML integrators can work with the confines of the themes folder without having to understand or even read a single line of PHP code Developers can work on additional data and modules that the HTML integrators can make use of Database schema Customers and Stbostcs gt emai V ARCHAR 123 gt passwd VAROIAR I2Z gt imt _pasmd_gen TIMES TAVE birtnday DATE prendete TINYINT 1 preson rewseter VAROUR IS maitie di
22. estabox com Host your shop with us PrestaShop Development standard Summary PHP PHP SQL Variable names Strings Table names Assignments Comments SQL query Operators Return values Statements Call Visibility Tags Method Function names Indentation Enumeration Array Objects Classes Bloc Defines Security Keywords Limitations Constants Other Configuration variables PHP Variable names 1 Corresponding to data from databases my_var 2 Corresponding to algorithm my_var 3 The visibility of a member variable does not affect its name private my_var Assignments 1 There should be a space between variable and operators Zs 3 Smy var 17 4 Sa Sb Operators 1 4 en and any combination of them e g need a space between left and right members 2s 3 Sa 17 4 Sresult b 2 5 Si 34 6 don t have space between left and right members T 8 echo a b 9 c d this gt foo Recommendation For performance reasons please don t abusing of use of concatenation 10 need a space between left and right members se 12 Sa Debug Statements 1 if elseif while for presence of a space between the if keyword and the bracket if lt condition gt while lt condition gt When a combination of if and else are used and that they should both return a value the else has to be avoided U DUUN if lt condition gt return false return
23. ges That is way you should always strive to stay away from core files when building a module even though this can prove hard to do in some situations Module file tree O prestashop a O admin2 classes O config css E O docs O download H O img 4 O install old aO js E E mails ao O bankwire E O birthdaypresent 9 blockadvertising E 5 blockbestsellers blockcart O blockcategories All PrestaShop modules are found in the moduies folder which is at the root of the PrestaShop main folder This is true for both default modules provided with PrestaShop and 3rd party modules that are subsequently installed Each module has its own sub folder inside the modules folder bankwire birthdaypresent etc Basic structure of a module All modules use the same basic structure which makes it easier to learn by observing existing modules source code Let s create a simple first module this will enable us to better describe its structure We ll call it My module Let s first create the module folder It should have the same name as the module with no space only alphanumerical characters the hyphen and the underscore all in lowercase mymodule This folder must contain a PHP file of the same name which will handle most of the processing mymodule php That is enough for a very basic module but obviously more files and folders can complement it The front office part of the module is defined in a tpi
24. ic name for the module which will be displayed in the back office s modules list The 1 method is part of PrestaShop translation s tools and is explained further below Sthis gt description Sthis gt l Description of my module Assigning a public description for the module which will be displayed in the back office s modules list public function install return parent install In this first and extremely simplistic incarnation this method is useless since all it does is check the value returned by the Module class install method Moreover if we hadn t created that method the superclass method would have been called instead anyway making the end result identical Nevertheless we must mention this method because it will be very useful once we have to perform checks and actions during the module s installation process creating SQL tables copying files creation configuration variables etc Likewise the module should contain an uninstail method so as to have a custom uninstallation process This method could look as such public function uninstall if parent uninstall Db getInstance gt Execute DELETE FROM DB PREFIX mymodule parent uninstall To put the finishing touch to this basic module we can add an icon which will be displayed next to the module s name in the back office modules list The icon file must respe
25. ile In the middle of these we place your custom template file whose single action will be to display the Welcome to my shop line Save all files and reload your shop s homepage with just a few lines the end result is so much better with our Welcome line neatly placed between header footer and columns fl a a wr 2 Search Currency contact sitemap bookmark j PS prestasnor WELCOME Click me MY ACCOUNT gt gt My orders gt gt My credit slips gt gt My addresses gt gt My personal info NEW PRODUCTS gt gt My vouchers i Kej TAGS apple ipod iPod Nano If you make multiple changes and reloads to your homepage it may seem said changes do not apply This is because Smarty caches a compiled version of the homepage In order to force Smarty to recompile templates on every invocation you must go to Preferences tab its Performance sub tab and choose Yes for the Force recompile option Back Office gt Preferences gt Performance A Update successful A There is 1 warning Click here to see more Smarty Force compile V Yes X No Cache Y Yes X No Save Do not force recompilation on production sites as it severely slows everything down Using Smarty Smarty is a PHP template engine and is used by PrestaShop s theming system It parses TPL files looking for dynamic elements to replace by their data
26. l if parent install false OR S this gt registerHook leftColumn return false return true public function hookLeftColumn Sparams global Ssmarty return this gt display FILE mymodule tpl public function hookRightColumn Sparams return Sthis gt hookLeftColumn Sparams Let s explore these new or changed lines if parent install false OR S this gt registerHook leftColumn return false return true We changed the original line to add a second test This code checks e the boolean value returned by the module Class install method if true the module is installed and can be used e the boolean value returned by registerHook for the leftcolumn hook if true the module is indeed registered to the hook it needs and can be used If any of these two boolean values is false install returns false too and the module cannot be installed Both values have to be true for the module to be considered installed Therefore this line now reads this way if installation or hooking fail we inform PrestaShop public function hookLeftColumn Sparams global Ssmarty return this gt display _ FILE mymodule tpl The hookLeftColumn method makes it possible for the module to hook into the theme s left column Ssmarty is the global variable for the Smarty template system which PrestaShop uses and which we need to access The display me
27. module prestashop gt mymodule page cOd7 cffa0105851272f83d5clfe63 Bienvenue dans ma boutique This file must not be edited manually It can only be edited through the PrestaShop translation tool zZ O O M O D O C O Cc wy il wm i wm il wm IVA z w e Q Now that we have a translation we can click on the French flag in the front office provided the language has indeed been installed and get the expected result the module s strings are now in French cE L Devises a PRESTASHOP WELCOME Bienvenue dans ma boutique Cliquez moi They are also translated in French when the back office is in French Supprimer F IA Mon module v1 0 A Description de mon module Desactiver R initialiser Supprimer Outils de Migration The translated strings can only be taken into account by the PrestaShop tool the PHP and TPL files have to be located at the root of the module s folder Creating the module s back office tab and its class In this section you will learn how to give your module its own tab or sub tab in a matter of minutes Follow these steps 1 Add a new table to your PrestaShop database named ps test Give it two fields O id test INT 11 o test VARCHAR 32 2 Create a blank file named test php in PrestaShop s classes folder 3 Add the following lines to that file Test php lt php class Test extend
28. n the 3rd party website Ideal location to display a confirmation message or to give some details on the payment orderConfirmation order Yes A duplicate of confirmation php paymentReturn backBeforePayment order php Called when displaying the list of available payment solutions Ideal location to redirect the user instead of displaying said list i e 1 click PayPal checkout Merchandise Returns Hook name File Visible Description location orderReturn order No Called when the customer request to follow php send his merchandise back to the store and if now error occurs PDFInvoice Class Called when displaying the invoice in PDF php PDF format Ideal location to display dynamic or static content within the invoice Back office General Hook name File location Visible Description backOfficeTop header inc php Yes Called within the header above the tabs backOfficeHeader header inc php No Called between the HEAD tags Ideal location for adding JavaScript and CSS files backOfficeFooter footer inc php Yes Called within the page footer above the Power By PrestaShop line backOfficeHome index php Yes Called at the center of the homepage Orders and order details Hook name File location Visible Description newOrder Class No Called during PaymentModule php the new order creation process right after it has been created paymentConfirm Class Hook php No Called when an order s status becomes
29. ne from our myModule object public function _ construct Defines the class constructor Sthis gt name mymodule Sthis gt tab Test Sthis gt version 1 0 Sthis gt author PrestaShop This section assigns a handful of attributes to the class instance this A name attribute This is an internal identifier so make it unique without special characters or spaces and keep it lower case e A tab attribute This is the title for the table that shall contain this module in PrestaShop s back office modules list You may use an existing name such aS Products Blocks OF Stats Or a custom as we did here In this last case a new table will be created with your title e Version number for the module displayed in the modules list e An author attribute This is displayed in the PrestaShop modules list Sthis gt need_ instance 0 The need _ instance flag indicates whether to load the module s class when displaying the Modules page in the back office If set at 0 the module will not be loaded and therefore will spend less resources to generate the page module If your module needs to display a warning message in the Modules page then you must set this attribute to 1 parent construct Calling the parent s constructor This must be done before any use of the Sthis gt 1 method and after the creation of sthis gt name Sthis gt displayName Sthis gt 1l My module Assigning a publ
30. nslate your module s strings the ones that were marked using the 1 method simply find your module in the list use the browser s in page search and fill the empty fields Module mymodule default mymodule 4 expressions 4 My module Description of my module Click this link Click me default mymodule_page 1 expressions 1 Welcome to my shop a Once all strings for your module are correctly translated click on the Update translation button either at the top or the bottom of the page Each field has an icon on its right This enables you to get an suggestion from Google Translate You can hover the mouse over it to see the translation and click it to fill the field with the translation Automatic translation are not always accurate use with caution The translations are saved in a new file fr php OF languageCode php which is generated by PrestaShop and looks like this mymodule tpl lt php lobal MODULE M a DULE array DULE lt mymodule prestashop gt mymodule 2ddddc2a736e4128celcdfd22b04le7 on module DULE lt mymodule prestashop gt mymodule d6968577f 69f08c93c209bd8b6b3d4d5 J escription de mon module D 1 D 1 D zZ z ULE lt mymodule prestashop gt mymodule c 6bl0fbf9cbe526d0f7d7a602a09b75 iquez sur ce lien ULE lt mymodule prestashop gt mymodule f42c5e67 c97b2167e7eoble0028ec d iquez moi MODULE lt my
31. r php di cheque i it php db criteo a 53 logo gif ab crossselling Any PrestaShop module once installed on an online shop can interact with one or more hooks Hooks enable you to hook your code to the current View at the time of the code parsing i e when displaying the cart or the product sheet when displaying the current stock Specifically a hook is a shortcut to the various methods available from the Module object as assigned to that hook A list of PrestaShop hooks Here s a recap of PrestaShop s module architecture PrestaShop s modular architecture Example with 3 modules and 2 hooks MyPrestaShop com Lists categories from the products catalog Module 1 Hook Displays the latest product hookLeftColumn that the visitor viewed lt Module 2 Module 3 Suggests links to informative pages y Hook hookFooter When one of the site s pages is loaded the PrestaShop engine check which are the modules to call for each of the hooks that make up the page Here is a list of 53 hooks available in PrestaShop Front office Homepage and general website items Hook name File Visible Description location header header php No Called between the HEAD tags Ideal location for adding JavaScript and CSS files top header php Yes Called in the page s header leftColumn header php Yes Called when loading the left column rightColumn footer php Yes Called when loading the right
32. s ObjectModel var string Name public test protected SfieldsRequired array test protected fieldsSize array test gt 64 protected S fieldsValidate array test gt isGenericName protected Stable test protected Sidentifier id test public function getFields parent validateFields Sfields test pSQL Sthis gt test return Sfields gt 1 Create a blank file named AdminTest php in PrestaShop s admin tabs 2 Add the following lines to that file AdminTest php lt php include _once PS ADMIN DIR classes AdminTab php class AdminTest extends AdminTab public function _ construct this gt table test Sthis gt className Test Sthis gt lang false Sthis gt edit true Sthis gt delete true Sthis gt fieldsDisplay array id _ test gt array title gt S this gt 1l ID align gt center width gt 25 test gt array title gt Sthis gt 1l Name width gt 200 3 Sthis gt identifier id test parent construct public function displayForm global ScurrentIndex S defaultLanguage intval Configuration get PS LANG DEFAULT Slanguages Language getLanguages Sobj S this gt loadObject true echo lt script type text javascript gt id language Number defaultLanguage lt script gt e
33. sibility revolves around modules which are small programs that make use of PrestaShop s functionality and changes them or add to them in order to make PrestaShop easier to use or more customized Technical principles behind a module A PrestaShop module consists of e A root folder named after the module which will hold all of the module s files and will reside in PrestaShop s modules folder e A main PHP file named after the module located in that root folder This PHP file should have the same name as its root folder e An icon file named iogo gif representing this module e Optional some tp1 files containing the module s theme e Optional language files if the module or its theme have text to display and therefore that should be translatable e Optional in a themes modules folder a folder with the same name as the module containing tpi and language files if necessary This last folder is essential during modifications of existing module so that you can adapt it without having to touch its original files Notably it enables you to handle the module s display in various ways according to the current theme Let s see an example with PrestaShop s blockuserinfo module a blocktags _ blockuserinfo php d blockuserinfo _ blockuserinfo tpl db blockviewed E ae config xml ab blockwishlist R _ de php ad carriercompare _ en php d cashondelivery i es php d cashticket f
34. thod returns the content of the mymodule tp1 template file if it exists public function hookRightColumn Sparams return Sthis gt hookLeftColumn Sparams Likewise hookRightColumn gives access to the theme s right column In this example we simply call the nookLeftcolumn method in order to have the very same display whatever the column Save your file and already you can hook it into the theme move it around and transplant it go to the Positions sub tab for the Modules tab in the back office then click on the Transplant a module link In the transplantation form find My module in the modules drop down menu then choose Left column blocks in the Hook into drop down menu Transplant a module Module My module z Hook into Left column blocks z Exceptions wot want the module to be displaye e g identity php Please type each filename separated by a comma Save It is useless to try to attach a module to a hook for which it has no implemented method Save The Positions page should reload with the following message Module transplanted successfully to hook Congratulations Scroll down and you should indeed see your module among the other modules from the Left column blocks list Move it to the top of the list Left column blocks 9 modules Technical name leColumn P if My module v1 0 ZARA a Description of my module T 5 ra amp My Account blo
35. vigation buttons Called within the client account creation form right above the the Your personal information block Called within the client account creation form right before the Register button Called right after the client account creation Called on the client account homepage after the list of available links Ideal location to add a link to this list Called within the My account block in the left column below the list of available links Ideal location to add a link to this list authentication authentication php No Called right after the client identification only if the authentication is valid e mail address and password are both OK Search Hook File Visible Description name location search Class No Called after a search is performed Search php Ideal location to parse and or handle the search query and results Carrier choice Hook name File Visible Description location extraCarrier order php Yes Called after the list of available carriers during the order process Ideal location to add a carrier as added by a module Hook name File location Visible Description payment order php Called when needing to build a list of the available payment solutions during the order process Ideal location to enable the choice of a payment module that you have developed paymentReturn order Yes Called when the user confirmation php is sent back to the store after having paid o
36. y orders gt gt My credit slips gt gt My addresses gt gt My personal info gt gt My vouchers The displayed link doesn t lead anywhere for now If you need to test it add the needed mymodule page php file in the module s folder with a minimal content such as Welcome to my shop The resulting page will be very raw so let s see if we can use the theme s style instead As you would expect we have to create a TPL file in order to use the theme s style Let s create the mymodule page tpi file which will contain the basic line and call that file from mymodule page php which will add the theme s header footer etc You should strive to use explicit and recognizable names for your TPL files so that you can find them quickly in the back office which is a must when using the translation tool mymodule_page tpl Welcome to my shop mymodule_page php lt php global Ssmarty include config config inc php include header php Ssmarty gt display dirname FILE mymodule page tpl include footer php gt We first load the current Smarty instance This must be done before any call to the display 0o method The various include calls in the file enable us to load e The current PrestaShop configuration e The theme s header file through header php which acts as a load file e the theme s footer file through footer php which acts as a load f
Download Pdf Manuals
Related Search
Related Contents
Philips Citrus press HR2744/80 Manual del Usuario para Nokia 2710 SM SERIES - supersonic 1747-UM076C-EN-E SLC 500 EtherNet/IP Adapter User Manual MANUEL D`INSTRUCTIONS - TA Triumph Peronäus-Schiene langsohlig - Sanitätshaus Burbach + Goetz la guía del usuario - ImagesAttainment.com Tensiomètre au poignet à gonflage automatique Télécharger Copyright © All rights reserved.
Failed to retrieve file