Using SMARTY Templates with PEAR HTML_QuickForm
- Transfer
1. Introduction.
What is this article about?
This article is a simple introduction to using Smarty templates with the PEAR HTML_QuickForm classes. This article is not an exhaustive guide, and in fact represents only a small part of the functionality of Smarty templates. However, for a beginner in using Smarty templates, this article will be a useful base.
Translator's note: Since Habr parses HTML, in some places the code is presented in the form of screenshots.
Prerequisites.
It is understood that you have already installed PHP and PEAR and that you are familiar with PHP and HTML. You should also be familiar with using the PEAR HTML_QuickForm classes. You can get help with PEAR on the PEAR website , help with PHP you can get on the PHP website and you can find an introduction to using HTML_QuickForm in another article of mine .
This article is written from a practical point of view. If you want to get the most out of it, you will need to copy the example code from here and run it yourself. Among other things, templates are used to represent information and examples of data output are not presented in this article. If you want to see patterns in action, you will have to run the code yourself. And finally, the code examples presented in this article are intended to represent the use of only Smarty templates. In other words, functions such as data validation have been omitted to more clearly represent the template function.
2. The main forms.
Short review.
Let's start with a simple form that does not use templates. Later we will change it so that it uses patterns.
Create the following file and place it in the folder to which your web server has access and display the file in the browser:

you should see the form, enter the information and send the data. After that, the page will reload with information in a static form. If this does not work or you do not understand why it works, then please see the following article .
Notice the following about the code above:
- It contains PHP / PEAR code, as well as HTML,
- There is no clear way to influence the formatting of the displayed HTML.
3. A bit of theory.
What are templates used for?
As we saw in the example above, by default, templates created by the PEAR HTML_QuickForm classes are displayed in an extremely simple way - a shortcut with a subsequent form and with elements displayed under each other.
Being workable, these forms lack some touches for a professional application.
One of the problems with generating programmable HTML is the separation of the displayed elements from the program code, and this is what the PEAR classes do very successfully.
Templates enable the designer to create much more attractive and complex pages and precisely determine the display locations of form elements. The designer works with HTML files, the programmer works with PHP code and PEAR classes, and changing one of them does not require changing the second.
How do smarty templates work with HTML_QuickForm?
From the example above, the line $ form → display (); calls the standard HTML_QuickForms visualizer. By replacing this line, you can achieve more control over the displayed HTML. It will also give us the opportunity to split the code in 2 parts: the PHP / PEAR code and the template file itself.
The template file contains HTML code and some additional tags. At this simple level, these tags are places to display information. The role of the visualizer is to take form data and transfer it to a format that can be used by the template object. The role of the template object is to parse the template file and replace additional tags with data from the form.
Creating and visualizing a form using a template is a multi-step process.
- A form is created using the PEAR classes in the same way as before,
- A template object is created,
- A visualization object is created,
- The visualizer generates HTML fragments for each form element and these fragments, together with the rest of the information about the forms, are collected in one large array.
- An array of form data is passed to the template object,
- Next, the template object parses the template file, replaces the tags with data from the array, and displays the HTML.
4. A simple form template.
Simple example
Now we will change the example above to use the template. We will need a couple of require_once lines at the beginning of the file, we will also replace the line $ form → display (); pattern code. We can also remove all HTML code. The result is shown below:
- require_once "HTML/QuickForm.php";
- require_once 'HTML/QuickForm/Renderer/ArraySmarty.php';
- require_once 'Smarty.class.php';
- $form = new HTML_QuickForm('frmTest', 'get');
- $form->addElement('header', 'hdrTesting', 'Тестируем Smarty');
- $form->addElement('text', 'txtFirstName', 'Имя?');
- $form->addElement('text', 'txtLastName', 'Фамилия?');
- $form->addElement('text', 'txtAge', 'Возраст?');
- $form->addElement('text', 'txtTelephone', 'Номер телефона?');
- $form->addElement('reset', 'btnClear', 'Очистить');
- $form->addElement('submit', 'btnSubmit', 'Отправить');
- if ($form->validate()) {
- # Если форма проверена, заморозить данные
- $form->freeze();
- }
- // Создание объекта шаблона
- $tpl =& new Smarty;
- $tpl->template_dir = '.';
- $tpl->compile_dir = '/tmp';
- // Создание объекта визуализатора
- $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($tpl);
- // создание HTML для формы
- $form->accept($renderer);
- // присвоить массиву данные формы
- $tpl->assign('form_data', $renderer->toArray());
- // парсировать и отобразить шаблон
- $tpl->display('smarty1.tpl');
- ?>
We will also need a template file, which is shown below. The file should be placed in the same folder as the PHP file above.

The form shown by the code above will certainly not receive a premium for the best design, but it looks much better than in the previous example.
If you experience any problems, check the following:
- Do the file names match what is written in this article?
- Are both files in the same folder?
- Does your web server process have read permissions?
- Does the web server process have write permissions to the / tmp folder?
Step by step: PHP source code
Notice the following differences compared to the first version:
- The form is represented by two columns, unlike the first version,
- At the bottom of the page is static copyright information,
- The PHP file contains only PHP code.
Let's analyze the files starting with the PHP code. In addition to the additional require_once lines , the first change was made when we introduced the Smarty template object:
- // Создание объекта шаблона
- $tpl =& new Smarty;
- $tpl->template_dir = '.';
- $tpl->compile_dir = '/tmp';
After initialization, we prompt the template object where it can find the template file (in the specific case, this is the same folder) and in which folder to load the compiled version (in the specific case, this is the / tmp folder). You can use any folders if the web server process has read permissions to the template folder and write permissions to the folder for the compiled version.
Next, we initialize the visualizer by passing the template object as a parameter:
- // Создание объекта визуализации
- $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($tpl);
The next step is to create an array containing form information and HTML fragments for each element. This is done with the following line:
- // Создание HTML для формы
- $form->accept($renderer);
The next step is passing the data array to the template:
- // присвоить массиву данные формы
- $tpl->assign('form_data', $renderer->toArray());
The assign statement creates the form_data variable in the template and populates it with data from a previously defined array.
Finally, we call the display method of the template object, which parses the template file and replaces the data display locations with the immediate data for these locations taken from the array. The following HTML is displayed:
- // визуализировать и отобразить шаблон
- $tpl->display('smarty1.tpl');
Data array
Before we familiarize ourselves with the template file, let's take a closer look at the data array created by the visualizer. It consists of a number of elements, some of which are also arrays. The code further shows the structure of the array:

If we want to examine this array, being filled with data, we can add an additional line to the PHP file, as shown below:

Now that we are familiar with the format of the data array, we can examine the template file in detail.
Step by step: template file
The template file consists mainly of plain HTML and does not contain interesting things for this article. However, various tags and commands for Smarty are shown in brackets. Let's study them.
The first {literal} command appears at the beginning of the file:

The {literal} tag closed by the {/ literal} tag simply means that the text that is between these two tags should be taken in the same form, should not be interpreted by the Smarty template. This is necessary in this case, since the text is a definition of style, which in itself should use brackets. Without the {literal} tag, Smarty would interpret the line text-align: right; like a smarty tag.
Next command {$ form_data.header.hdrTesting} generates the text of the second level header. By calling it earlier, we passed the form data array to the template and then saved it to the form_data variable with the following line:
- $tpl->assign('form_data', $renderer->toArray());
This array has an element named header , which is also an array whose keys are the names of the header elements and data components that compare the header text. It follows that the line {$ form_data.header.hdrTesting} represents the header text called hdrTesting , which was passed to the template in the form_data array .
The remaining tags in the template file simply take different elements of the form_data array . Each form element other than the headers has its own array in the form_data array , which implies that, for example, the txtFirstName element can be represented in the form_data array in the following way:
- ["txtFirstName"]=>
- array(8) {
- ["name"]=>
- string(12) "txtFirstName"
- ["value"]=>
- string(5) "Keith"
- ["type"]=>
- string(4) "text"
- ["frozen"]=>
- bool(true)
- ["label"]=>
- string(11) "First name?"
- ["required"]=>
- bool(false)
- ["error"]=>
- NULL
- ["html"]=>
- string(62) "Keith"
- }
In this example, form_data.txtFirstName.label will be “First name?” And form_data.txtFirstName.html will be “Keith”.
Finally, the template may contain static information. In the example above, copyright information will always be displayed verbatim, as it is embedded in the template file in the form of static HTML.
5. Intelligent template processing.
Introduction
Without trying to write an exhaustive guide to using Smarty templates (which has been very successfully done on the Smarty website ), in this part we will learn a few simple functions of Smarty templates that will make the templates much more powerful.
Processing type "if-then-else".
Smarty templates support if-then-else processing. We can modify the original template file as follows:

The $ form_data.frozen variable is a boolean that is one if the form is frozen. When the form is displayed for the first time, the title will be the value of the hdrTesting variable , as provided by the code from the PHP file. After the data has been submitted, the form will be “frozen” and displayed in red.
A more practical example would be displaying the buttons of a form if it is not frozen. We can do this as follows:

Note that {if} closes {/ if} . Smarty templates also support {else} and {elseif} that work as expected.
Local variables
It is possible to embed local variables in a template. The following example sets the label style based on whether the form is frozen or not. Although not a useful feature, it demonstrates the use of local variables well. The template file is the same as before, with some changes:

Comments in the template.
Comments can be included in the template by placing them between {* and *} . Example:
- {* Это комментарий *}
5. Practical considerations.
Introduction
The example above was compiled in a simple way to clearly show the things done. However, in real life, there are some additional things that need to be added there. For example, in the example above there was no mark for users which fields are required. There are also other items that we will need to take care of.
Hidden Fields and JavaScript
Hidden fields are used in forms to store contextual information. Many forms use JavaScript to perform various functions. As you know, neither hidden fields nor JavaScript code will be displayed on the page, however this information is in the array that is passed to the template object. We will need to make the following changes in order to use this data:

Required fields
In the visualizer, by default, required fields are marked with a red asterisk and a note is placed at the bottom of the form stating that these fields are required.
When creating our own templates, we must include code for marking the fields mandatory (if we need such functionality). Let's make our Age field mandatory by making the following changes to our PHP file.
- $form->addElement('submit', 'btnSubmit', 'Отправить');
- $form->addRule('txtAge', 'Поле возраст обязателен', 'required');
- if ($form->validate()) {
- # Если форма проверена, заморозить данные
- $form->freeze();
- }
After displaying this form, we will see that there is no mark on the form that the Age field is required. And if we leave the Age field empty, the form will not send data, but will not tell us why. To prevent these problems, we will need to make some changes to the visualizer using the setRequiredTemplate method . It takes the template as an argument to the text line, although of course we can read the external template file using the PHP function file_get_contents () . For simplicity, we will directly indicate the template.
The Smarty template recognizes 3 variables:
- {$ label} - the label of the item in the question,
- {$ html} - HTML code of the element,
- {$ required} - the value will be “True” if this element is required
It will be clearer after reading the following example. Change the PHP code as shown below:

From the code above it is seen that when an error occurs, the item's label should be shown in red. If there is no error, display the shortcut as usual. And if this is a required field, put a small red star in it.
If we now display the form, we will see that the Age field has a small red asterisk. And if we send the data, leaving the Age field blank, the form will appear with a red label for the Age field . However, the form does not tell us what the red asterisk means and why data is not sent when the Age field is empty .
Error messages.
Like the setRequiredTemplate method , the renderer also has the setErrorTemplate method . In addition to the three Smarty variables for setRequiredTemplate , the setErrorTemplate method also supports variables. It contains the error text that is associated with the element that is defined in the second argument to the addRule method .
Next, we modify the PHP code as follows:

The code says that if an error occurs, the error message should be shown in small orange font. The item itself is always displayed. The whole effect is that all form elements will have orange error messages above them.
Finally, we must explain to the user what exactly the red star means. We do this by adding the requirednote field to the template. Modify the template file as follows:

This will display the standard text “requirednote”, but we can change it in the PHP file itself.

6. Conclusions.
This guide only superficially presented what Smarty can do. However, most often the most difficult part is the beginning, and I hope that this guide has helped you take this first step. The second useful step for you is to read the Smarty documentation in order to understand what else Smarty can do.