:::

3. 動態產生表單元件

<?php
//定義一個抽象的 FormElement  類別,其中 output方法負責輸出動態元件
abstract class FormElement
{
  protected $_name = null;
  protected $_value = null;
  public function __construct($name, $value)
  {
    $this->_name = $name;
    $this->_value = $value;
  }
  public function getName()
  {
    return $this->_name;
  }
  abstract public function output();

}

//處理文字輸入欄位的類別,繼承FormElement,並覆寫 output方法,輸出input標籤動態元件
class FormElement_input extends FormElement
{
  private $_type;
  public function set_type($type){
    $this->_type=$type;
  }
  public function output()
  {
    return '<input type="'.$this->_type.'" name="'. $this->_name .'" value="' .htmlspecialchars($this->_value) . '" />';
  }
}
//圖片類別也是繼承FormElement類別,並覆寫output方法,輸出img標籤動態元件
class FormElement_Image extends FormElement
{
  public function output()
  {
    return '<img src="'. $this->_value .'" alt="" />';
  }
}
//送出按鈕類別也是繼承FormElement類別,並覆寫output方法,輸出button標籤動態元件
class FormElement_Submit extends FormElement
{
  public function output()
  {
    return '<button type="submit">' . htmlspecialchars($this->_value) .'</button>';
  }
}
//大量文字框也是繼承FormElement類別,並覆寫output方法,輸出textarea標籤動態元件
class FormElement_textarea extends FormElement
{
  private $_rows;
  public function set_rows($rows){
    $this->_rows=$rows;
  }
  public function output()
  {
    return '<textarea type="textarea" rows="'.$this->_rows.'"  name="'. $this->_name .'">'.htmlspecialchars($this->_value) .' </textarea>';
  }
}
//下拉式選單也是繼承FormElement類別,並覆寫output方法,輸出select標籤動態表單
class FormElement_select extends FormElement
{
  private $_itemarr= array();
  public function set_itemgroup(Array $itemarr){
    $this->_itemarr=$itemarr;
  }
  public function output()
  {
    $html='<select name="'. $this->_name .'" >';
    foreach($this->_itemarr as $key => $arr){
      $select=($this->_value==$key)?'selected':'';
      $html.='<option value="'.$key.'" '.$select.' >'.$arr.'</option>';
    }
    $html.='</select>';
    return $html;
  }
}
//單選框也是繼承FormElement類別,並覆寫output方法,輸出radio標籤動態表單
class FormElement_radio extends FormElement
{
  private $_itemarr= array();
  public function set_itemgroup(Array $itemarr){
    $this->_itemarr=$itemarr;
  }
  public function output()
  {
    $html="";
    foreach($this->_itemarr as $key => $arr){
      $checked=($this->_value==$key)?'checked':'';
      $html.='<label class="radio"><input type="radio" name="'. $this->_name .'" id="'. $this->_name .'" value="'. $key .'" '.$checked.'>'.$arr.'</label>';
    }
    return $html;
  }
}

?>