Support boolean fields alias checkboxes
[misc/kostenrechnung] / ajax / ajax.php
index 2256e9d..a709a03 100644 (file)
@@ -1,16 +1,49 @@
 <?php
 
-require_once('../config.php');
-require_once('../lib/general.php');
-
+require_once('../init.php');
 
 function fetch($mask)
 {
   $sql = sprintf('SELECT id,%s FROM %s WHERE id = %d',
                 implode(',', array_keys($mask['edit'])),
                 $mask['table'], $_POST['id']);
-  error_log($sql);
+
   $sth = pg_query($sql);
+  if ($sth === false) return false;
+
+  $row = pg_fetch_assoc($sth);
+
+  foreach ($mask['edit'] as $field => $info)
+    if ($info['type'] == 'boolean')
+      $row[$field] = $row[$field]?true:false;
+    elseif (array_key_exists('format', $info))
+      $row[$field] = sprintf($info['format'], $row[$field]);
+
+  return $row;
+}
+
+function details($mask)
+{
+  if (empty($_POST['id']))
+    return array('error' => 'Missing ID');
+
+  $sql = sprintf('SELECT id,%s FROM %s WHERE id = %d',
+                implode(',', array_keys($mask['details']['list'])),
+                $mask['table'], $_POST['id']);
+
+  $sth = pg_query($sql);
+
+  if (!$sth)
+    return array('error' => pg_last_error(),
+                'sql' => $sql);
+
+  $row = pg_fetch_assoc($sth);
+
+  foreach ($mask['details']['list'] as $field => $info)
+    if (array_key_exists('format', $info))
+      $row[$field] = sprintf($info['format'], $row[$field]);
+
+  return $row;
 }
 
 function format_ajax($data)
@@ -23,16 +56,22 @@ function format_ajax($data)
 if (empty($_POST['func']))
   exit;
 
-if (empty($_POST['mask']))
+if (empty($_POST['source']))
   exit;
 
 connect_db();
-if (load_mask($_POST['mask'], '../') === false) exit;
+if (load_mask($_POST['source'], '../') === false) exit;
+
+$data = array('error' => 'Unknown function');
 
 if ($_POST['func'] == 'fetch') {
-  format_ajax(fetch($mask));
+  $data = fetch($mask);
+} elseif ($_POST['func'] == 'details') {
+  $data = details($mask);
 } elseif ($_POST['func'] == 'save') {
   error_log('save');
 }
 
-?>
\ No newline at end of file
+format_ajax($data);
+
+?>