[PHPTAL] PHPTAL & Form processor ???

Laurent Bedubourg lbedubourg at motion-twin.com
Tue Sep 26 10:33:39 CEST 2006


Lukas wrote:
> Hi, i'm new at this mailing list and i've big question.
> I used Pagetemplates earlier in ZOPE.
> 
> Now i'm using PHPTAL and it's a great thing!!!
> 
> Is it possible to use a form processor with PHPTAL like this one (http://simon.incutio.com/archive/2003/06/17/theHolyGrail)???
> 
> I'm searching for an easy way to create and validate forms...
> 
> I'm ready for input... ;-)
> 

Hi Lukas,

The easiest way to integrate such a class would be to compute the form 
outside PHPTAL using the author's FormProcessor class and then put the 
result into the PHPTAL templates using some :

<span tal:replace="structure formHtml"/>



Another solution would be to create a FormValidator class and use 
booleans to indicate if an error occured or not :

myform.html (phptal template) :

...
<form method="post" action="/user/create">
   <div>
     <label>Name:
     <input type="text" name="name" value=""
       tal:attributes="value request/name | default"
     />
     </label>
   </div>
   <div class="error" tal:condition="errorMissingName">You did not enter 
your name</div>
   <div class="error" tal:condition="errorMalformedName">Your name must 
consists only of letters</div>
    ...
   <div><input type="submit" name="submit" value="Create"/>
</form>
...

And in PHP :

// please note that the logic is described in PHP and not inside
// the form XHTML if the template is modified by error PHP will just
// refuse to validate checks.

$form = new FormValidator();
// first argument = variable name
// second argument = error name
$form->checkCompulsory('name', 'errorMissingName');
$form->checkAlpha('name', 'errorMalformedName');
...

// $_REQUEST['submit'] must exists and all checks must succeed.
// If submit is not present, the FormValidator assumes that it
// cannot validate checks, they won't fail and errors won't be shown,
// but validates() will fail.

if ($form->validates()){
   // ... do submit ...
   // ... and redirect to result page ...
}
else {
   // checks failed, the form must be shown (for the first time or
   // to display input errors).

   $tpl = new PHPTAL('myform.html');

   // we pass the $_REQUEST hash to PHPTAL context for input values
   // (tal:attributes="value request/name | default")
   $tpl->request = $_REQUEST;

   // set errorMissingName and cie to true or false depending on checks
   // results
   foreach ($form->getChecks() as $checkName => $checkFailed)
     $tpl->$checkName = $checkFailed;

   echo $tpl->execute();
}

Well, you get the idea, and writing the FormValidator class shouldn't be 
complex...

Best regards
Laurent
-- 
Laurent Bedubourg
lbedubourg at motion-twin.com
http://www.motion-twin.com



More information about the PHPTAL mailing list