Speaking in terms of MVC your $fields array is a "model" of a form. It is 
indeed a model that relatively closely describes, what you want to output in 
html, but nevertheless it is a model.

So what you want to do is to iterate over this model and render it:

        <div tal:repeat="field fields">
                <tal:block tal:define="name repeat/field/key" 
metal:use-macro="${field/type}" />

<tal:block metal:define-macro="text">
        <label>${field/label}</label><input name="${name}" type="text" 
value="${field/value}" />

<tal:block metal:define-macro="selet">
        <label>${field/label}</label><select name="${name}">
                <tal:block tal:repeat="value field/valuelist">
                        <option tal:condition="php:field.value != value" 
                        <option tal:condition="php:field.value == 
value"value="${value}" selected="selected">${value}</option>

And so on... What you can see is, that the template get's more ugly the more 
the model is insufficient. For example defing the the name as 
"repeat/field/key" wouldn't be necessary, if the name of the field would also 
be an index in the field's array.

What we did is to implement a very rich model of a representation of a form 
that really describes "what" the form is, not, how it looks like. Our fields 
can be nested having methods like "getSubQuestions" and also have methods like 
"isChecked" to simplify the templates.
We even try to avoid saying that the type of a field is "select" and prefer to 
call it a SingleChoiceQuestion. That enables you to not only render a form in 
html but also into other presentation formats like a question within a cli 

So keep improving your model! By the way: You should always prefer strong 
classes and objects instead nested array definitions ;)

Kind regards,

-----Ursprüngliche Nachricht-----
Von: phptal-boun...@lists.motion-twin.com 
[mailto:phptal-boun...@lists.motion-twin.com] Im Auftrag von Richard Dyce
Gesendet: Montag, 2. August 2010 20:27
An: Template Attribute Language for PHP
Betreff: [PHPTAL] PHPTAL and form macros


Just a pre-re-invent-the-wheel inquiry... Does anyone have an example of macros 
for formatting form fields in phptal?

I have an older framework which create field objects based on the data and 
type, and populates them from a simple array:



  $fields = array(
    'id'        => array('label'=>'',      'type'=>'hidden', 'value'=>2),
    'name' => array('label'=>'Name',  'type'=>'text',   'value'=>'John Smith'),
    'user'    => array('label'=>'Owner', 'type'=>'select', 
'valuelist'=>array(1,2,3), 'value'=>2)

It seems daft me to duplicate the logic twice over, and it appears that phptal 
might be able to handle it with some repeats and templating. But before I tie 
myself in knots over this, has anyone already done it, or tried it and found 
the gotcha ;-)


PHPTAL mailing list

PHPTAL mailing list

Reply via email to