|
Posted by Peter Salzman on 10/01/70 11:19
Hi all,
Newish PHP programmer here. I wrote a form select class to help reduce code
clutter, but I don't think the effort was worth it. I was hoping to post my
attempt and get some ideas from more advanced users on how to implement a
select form using less lines of code.
First the select form class which implements a select widget. I'll post only
the relevent parts:
class frmSelectClass
{
// Attributes
var $name = '';
var $size = '';
var $multiple = '';
var $id = '';
var $class = '';
var $style = '';
// Options
var $options = array();
function frmSelectClass($arg = '')
{
if ( gettype($arg) == 'array' )
{
foreach ( array_keys($arg) as $key )
{
if ( $key == 'name' )
$this->name = 'name="' . $arg['name'] . '" ';
elseif ( $key == 'size' )
$this->size = 'size="' . $arg['size'] . '" ';
elseif ( $key == 'multiple' )
$this->multiple = 'multiple="' . $arg['multiple'] . '" ';
elseif ( $key == 'id' )
$this->id = 'id="' . $arg['id'] . '" ';
elseif ( $key == 'class' )
$this->class = 'class="' . $arg['class'] . '" ';
elseif ( $key == 'style' )
$this->style = 'style="' . $arg['style'] . '" ';
}
}
}
function addOption($arg = '')
{
$value = '';
$label = '';
$selec = '';
if ( gettype($arg) == 'array' )
{
foreach ( array_keys($arg) as $key )
{
if ( $key == 'value' )
$value = 'value="' . $arg['value'] . '"';
elseif ( $key == 'label' )
$label = $arg['label'];
elseif ( $key == 'selec' && $arg['selec'] == $arg['value'] )
$selec = 'selected ';
}
}
$this->options[] = "<option $value $selec>$label</option>\n";
}
function output()
{
$attributes = $this->name . $this->size . $this->multiple .
$this->id . $this->class . $this->style;
$retval = "<select $attributes>";
foreach ( $this->options as $opt )
$retval .= $opt;
echo $retval . '</select>';
}
}
A tad more complicated than what I was hoping for. Now I'll demonstrate how to
use the class to create a select form on a webpage.
$frm = new frmSelectClass( array('id'=>'weekday', 'name'=>'frmDow') );
$dow = array( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' );
for ( $i = 0; $i <= 6; $i++ )
$frm->addOption(
array( 'value'=>$dow[$i], 'label'=>$dow[$i], 'selec'=>date('D') )
);
$frm->output();
That's about it. I thought I was being really sneaky by passing in arrays
that hold attributes, so this:
$frm = new frmSelectClass( array('id'=>'weekday', 'name'=>'frmDow') );
would yield this:
<select id="weekday" name="frmDow" >
It works, but I think it would've taken less lines of code to just use the
straight forward non-OOP method:
$id = 'weekday';
$name = 'frmDow';
echo "<select id=\"$id\" name=\"frmDow\">
I'm sure lots of people have tried to abstract HTML forms using PHP classes.
It seems like a natural thing to do.
Any ideas on how to make the code more compact?
Thanks for reading down this far. ;-)
Pete
Navigation:
[Reply to this message]
|