00001 <? 00002 require_once("form.inc.php"); 00003 00004 class FormSync extends Form 00005 { 00006 private $table; 00007 private $id; 00008 private $dbConn; 00009 00010 public function __construct($layout = null) 00011 { 00012 parent::__construct($layout); 00013 00014 if(isset($GLOBALS['dbconn'])) 00015 { 00016 self::assertIsDbObject($GLOBALS['dbconn']); 00017 $this->dbConn = &$GLOBALS['dbconn']; 00018 } 00019 00020 $this->id = 0; 00021 } 00022 00028 public function __set($name, $value) 00029 { 00030 switch($name) 00031 { 00032 case 'table': 00033 case 'id': 00034 $this->$name = $value; 00035 return true; 00036 break; 00037 00038 case 'dbConn': 00039 self::assertIsDbObject($value); 00040 $this->dbConn = $value; 00041 break; 00042 00043 default: 00044 return parent::__set($name, $value); 00045 } 00046 } 00047 00052 public function handleSubmit($redir = null) 00053 { 00054 if($this->isSubmitted()) 00055 { 00056 $this->validate(); 00057 if(!$this->hasError()) 00058 { 00059 $this->sync(); 00060 00061 if($redir) 00062 header("Location: $redir"); 00063 } 00064 } 00065 } 00066 00067 00073 public function handleSubmitWithCallback($callback, $redir = null) 00074 { 00075 if($this->isSubmitted()) 00076 { 00077 $this->validate(); 00078 00079 if(!$this->hasError()) 00080 { 00081 if(!is_callable($callback)) 00082 throw new InvalidCallbackException(); 00083 00084 $ret = call_user_func($callback, $this->getData(), &$this); 00085 00086 if($ret && $redir) 00087 header("Location: $redir"); 00088 00089 return $ret; 00090 } 00091 } 00092 00093 return false; 00094 } 00095 00100 public static function assertIsDbObject(&$obj) 00101 { 00102 $type = get_class($obj); 00103 if(!preg_match('/^DB_.+$/', $type)) 00104 throw new InvalidValueException(); 00105 00106 return true; 00107 } 00108 00113 public function sync(&$dbConn = null) 00114 { 00115 # Table name is required, otherwise generated SQL is invalid. 00116 if(!$this->table) 00117 throw new TableNotSetException(); 00118 00119 if($dbConn === null) 00120 $dbConn = $this->dbConn; 00121 00122 self::assertIsDbObject($dbConn); 00123 $this->id = (int)$_REQUEST['id']; 00124 00125 $fieldSql = array(); 00126 foreach($this->fields as $field) 00127 { 00128 $fieldSql[] = $field->getSqlImpl(); 00129 } 00130 00131 # Implode the array, using array_diff against a null array to remove all empty elements 00132 $fieldSql = implode(',', array_diff($fieldSql, array(''))); 00133 $sql = <<<EOSQL 00134 INSERT INTO $this->table 00135 SET 00136 id = $this->id, 00137 $fieldSql 00138 ON DUPLICATE KEY UPDATE 00139 $fieldSql 00140 EOSQL; 00141 00142 $res =& $dbConn->query($sql); 00143 00144 if(PEAR::isError($res)) 00145 throw new Exception($res->getMessage()); 00146 } 00147 00148 00149 protected function drawHiddenFields() 00150 { 00151 parent::drawHiddenFields(); 00152 00153 echo "<input type=\"hidden\" name=\"id\" value=\"$this->id\"/>"; 00154 } 00155 } 00156 ?>