QuickForm and Smarty, is there a better way to use them?
| From: | karl at posmaster dot com dot au | Date: | Mon, 06 Jun 2005 02:13:56 +0000 |
| Subject: | QuickForm and Smarty, is there a better way to use them? | ||
| Groups: | php.pear.general | ||
| Request: | Send a blank email to pear-general+get-19476@lists.php.net to get a copy of this message | ||
This is a stripped down version of how I currently get dynamically
produced QuickForm elements to work in a Smarty template. The ugly
part is that the form ends up with an array of element->toHtml()
elements that the template displays and the rendered QuickForm
itself.
The reason I use the toHtml() elements is because I cannot find a way
to structure a single HTML_QuickForm or HTML_QuickForm_group such
that I can access it from within a Smarty {section} tag.
My question is: Is there a better way to use Smarty to render this
variable number of rows (and therefore QuickForm elements) into a
page?
demo.php
---
<?php
require_once 'HTML/QuickForm.php';
require_once 'HTML/QuickForm/Renderer/ArraySmarty.php';
require_once 'Smarty.class.php';
// This would usually be a result-set from the DB
$data = array(
array('StockID'=>0, 'Description'=>'Product 1',
'RetailPrice'=>'1.0'),
array('StockID'=>1, 'Description'=>'Product 2',
'RetailPrice'=>'2.0'),
array('StockID'=>2, 'Description'=>'Product 3',
'RetailPrice'=>'5.0'));
// Make objects
$form = new HTML_QuickForm('the_form', 'POST');
$tpl =& new Smarty;
$renderer =& new HTML_QuickForm_Renderer_ArraySmarty($tpl, true);
$tpl->template_dir = '.';
$tpl->compile_dir = '.';
// Fills the form with some defaults values
$defaultValues['NewProduct'] = 'Scan a new product';
$form->setDefaults($defaultValues);
$form->addElement('text', 'NewProduct', null, 'size=25
onfocus="this.select(); changeMe(\'InvoiceItemsItems\',this.id);"');
$items = array();
foreach ($data as $ind => &$Product) {
$sid = $Product['StockID'];
$Description = $form->createElement('static',
'Description_'.$sid, null, $Product['Description']);
$RetailPrice = $form->createElement('text', 'RetailPrice_' .
$sid, null, 'id="RetailPrice_'.$sid.'" ');
$RetailPrice->setValue($Product['RetailPrice']);
$form->addGroup(array($Description, $RetailPrice), $sid);
$items[] = array('Description'=>$Description->toHtml(),
'RetailPrice'=>$RetailPrice->toHtml());
}
$tpl->assign('items', $items);
$form->accept($renderer);
$tpl->assign('the_form', $renderer->toArray());
$tpl->display('demo.tpl');
?>
demo.tpl
---
{debug}<html>
<head>
</head>
<body>
<form {$the_form.attributes}>
<table width="300" border="1" cellpadding="0"
cellspacing="0">
<tr>
<td width="70">Description</td>
<td width="70">Price</td>
</tr>
<tr>
<td width="188" align="left" colspan="2">
{$the_form.NewProduct.html}
</td>
</tr>
{section name=product loop=$items}
<tr>
<td>
{$items[product].Description}
</td>
<td>
{$items[product].RetailPrice}
</td>
</tr>
{/section}
</table>
</form>
</body>
</html>