Source code in Qf2Smarty.php

To see how this is used return to this tutorial index.

<?php
    // Integration of QuickForm2 with Smarty.

    // This provides the 'logic', the html template is in QfSmarty.tpl
    // Most of this is the same as in the previous examples, the differences are at the end.

    // Copyright (c) 2009, 2011, Parliament Hill Computers (www.phcomp.co.uk). Author: Alain D D Williams (addw@phcomp.co.uk).
    // You may used this file as the basis your own (or organisation's/company's) project (under whatever
    // licence that you see fit), but may not claim ownership or copyright of the substantially unmodified file.
    // This file is made available in the hope that it is useful, there is no warranty at all, use at your own risk.
    // SCCS: %W% %G% %U%

    // Check that the title is valid.
    // Don't want 0 since that is the one that asks for the title to be selected
    function CheckTitle($t)
    {
        global $Titles;
        return $t > 0 && isset($Titles[$t]);
    }

    // Check that the first name is one of an approved list, callback function:
    function checkFNfunc($name)
    {
        $OKlist = array('John', 'Bill');
        return strcmp(array_search($name, $OKlist), '');
    }

    require_once "HTML/QuickForm2.php";

    // You may need to add the 4th argument 'false' otherwise QF2 will look for a hidden
    // input field _qf__$id ($id is 'QfDemo' here) to check if the form has
    // been submitted. The existing Smarty templates may not push out these hidden fields.
    // $form = new HTML_QuickForm2('QfDemo', 'get', null, false);
    // This was an expectation that 'hidden' was a string, rather than QF2's array - the Smarty
    // renderer fixes that.
//    $form = new HTML_QuickForm2('QfDemo', 'get');
$form = new HTML_QuickForm2('QfDemo', 'post', NULL, '_self', NULL, TRUE);

    // This is where converting the header to a hidden field is used to create a form
    // element with the name of the header.
    // QF2 doesn't use headers, but we can put in the header at the render stage - see below
    // near $FormData.
    // $form->addElement('header', 'DemoHeader', 'Quickform Demo');

    // When the form has been filled in, trim spaces from all fields:
    $form->addRecursiveFilter('trim');

    $Titles = array('Please select', 'Mr', 'Mrs', 'Miss', 'Dr');
    $title = $form->addElement('select', 'Title', null, ['label' => 'Title', 'options' => $Titles]);
    $title->addRule('required', 'A title must be set', NULL, HTML_QuickForm2_Rule::SERVER | HTML_QuickForm2_Rule::CLIENT);
    $title->addRule('regex', 'A title must be from the list', '/^\d+$/');    // numeric
    $title->addRule('callback', 'A title must be from the list', 'CheckTitle');

    $first = $form->addElement('text', 'FirstName', null, ['label' => 'First name']);
    $first->addRule('required', 'First name is required', NULL, HTML_QuickForm2_Rule::SERVER | HTML_QuickForm2_Rule::CLIENT);
    $first->addRule('callback', 'First name is not in approved list', 'checkFNfunc');

    $last = $form->addElement('text', 'LastName', null, ['label' => 'Last name']);
    $last->addRule('required', 'Last name is required');

    $age = $form->addElement('text', 'Age', ['maxlength' => 3, 'size' => 3], ['label' => 'Age']);
    $age->addRule('required', 'Age is required');
    $age->addRule('regex', 'Age must be numeric', '/^\d+$/');

    $phone = $form->addElement('text', 'Telephone', null, ['label' => 'Telephone number']);
    $phone->addRule('regex', 'The phone number must start with 0, or international ones with +',
        '/^[0+]/');

    $form->addElement('reset', 'Clear');
    $form->addElement('submit', 'Submit', ['value' => 'Press to Submit']);

    if($form->validate()) {
        # Get here when the form has been filled in and validation checks passed
        // $form->freeze(); // If we want the form redisplayed in the way that the user entered it
        // but you need to do another display()
        $res = $form->getValue();
        echo "Title = " . htmlspecialchars($res['Title']) . " = '" . $Titles[$res['Title']] . "'<br>\n";
        echo "FirstName = " . htmlspecialchars($res['FirstName']) . "<br>\n";
        echo "LastName = " . htmlspecialchars($res['LastName']) . "<br>\n";
        echo "Age = " . htmlspecialchars($res['Age']) . "<br>\n";
        echo "Telephone = " . htmlspecialchars($res['Telephone']) . "<br>\n";
        exit;
    } else {
        // only does something with empty form
        $form->addDataSource(new HTML_QuickForm2_DataSource_Array(
            ['FirstName' => 'John', 'LastName' => 'Smith', 'Age' => 42]
            ));
    }

    // **** Differences from previous examples start here: ****

    // require_once 'HTML/QuickForm/Renderer/ArraySmarty.php';
    require_once 'HTML/QuickForm2/Renderer.php';
    require_once 'Smarty.class.php';

    // Create the template object
    $tpl = new Smarty;
    $tpl->template_dir = '.';       // Where the template files live
    // Smarty 'compiles' the .tpl and creates a .php script to generate the html
    // Next time smarty will use the .php without recompilation if the .tpl has not changed
    // This will live in the templates_c directory.
    // This templates_c/XXXXX.php is run to produce html
    // We could cache this html but that would mean that we would not see error messages or other things
    // that are dynamically genereated. Do not switch on caching.

    // Create the renderer object
    // $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl);
    HTML_QuickForm2_Renderer::register('smarty', 'HTML_QuickForm2_Renderer_Smarty');
    $renderer = HTML_QuickForm2_Renderer::factory('smarty');

    $requiredMarker = "<span class=required>*</span>";
    // Generate styles/output compatible with the old renderer (for old templates):
//    $renderer->setOption('old_compat', true);
    $renderer->setOption([
        'group_errors'  => true,
        'group_hiddens' => true,
        'required_note' => '<strong>Note:</strong> Required fields are marked with an asterisk (' . $requiredMarker . ').',
    ]);

    // Errors in an array 'errors' in the form array keyed by the form name.
    // If false error are in the form field's array keyed 'error'.
//    $renderer->setOption('group_errors', true);

    // The old Smarty renderer produced a string 'requirednote' that could be produced.
    // This is called 'required_note' in QF2. You may set the string as below - which is default.
    // It will be edited to be in a 'div class="reqnote"'. Old smarty it has the * styled red.
    // $renderer->setOption('required_note', '<em>*</em> denotes required fields.');

    // build the HTML for the form
    // $form->accept($renderer);

    // assign array with form data
    // $tpl->assign('FormData', $renderer->toArray());
    $FormData = $form->render($renderer)->toArray();

    // This is where the header is inserted directly into the array for smarty:
    if( !isset($FormData['header']))
        $FormData['header'] = [];
    $FormData['header']['DemoHeader'] = 'Quickform Demo';
    $tpl->assign('FormData', $FormData);
    $tpl->assign('QuickForm2', 1);    // Tell the template that this is QF2

    require_once 'HTML/QuickForm2/JavascriptBuilder.php';

    // parse and display the template
    $tpl->display('QfSmarty.tpl');

    // echo "<b>toArray()</b><pre>";var_dump($renderer->toArray());echo "</pre>";
    // echo "<b>form</b><pre>";var_dump($form);echo "</pre>";

Return to this tutorial index.