<?php
/* project: Advanced form, file: advform.php */
/**
* This file implements following actions:
* - list: show persons datagrid
* - add: show form for adding new person
* - edit: show edit form
* - insert: insert person into database
* - update: update item in database
* - delete: delete from database
*/
/* We want remember template parameters across pages */
session_start();
//Include pclib framework
require 'pclib/pclib.php';
//Create pclib application
$app = new PCApp('demo');
$datasource = 'pdo_mysql://user:password@localhost/test';
$db = new PCDb($datasource);
$app->db = $db;
//Get control variables
//action is invoked by pressing button/clicking on datagrid
//id contains ID of person to be shown or modified
$id = $_GET['id'] ?? 0;
//Initialize form template
$pform = new PCForm('tpl/examples/personform.tpl', 'personform');
$action = $pform->submitted ?? $_GET['action'] ?? '';
switch($action) {
case 'add':
//show 'insert' button only
$pform->enable('insert');
print $pform;
break;
case 'edit':
//on edit show buttons 'update' and 'delete'
$pform->enable('update','delete');
if (!$pform->values)
$pform->values = $db->select('PERSONS', ['ID' => $id]);
print $pform;
break;
//user click on 'insert' button
case 'insert':
if (!$pform->validate()) $app->redirect("examples/advform/action:add");
$pform->values['CREATED_AT'] = date("Y-m-d H:i:s");
$id = $pform->insert('PERSONS');
$app->redirect("examples/advform");
break;
//user click on 'update' button
case 'update':
if (!$id) die('Object not found.');
if (!$pform->validate()) $app->redirect("examples/advform/action:edit/id:$id");
$pform->update('PERSONS', ['ID' => $id]);
$app->redirect("examples/advform");
break;
//user click on 'delete' button
case 'delete':
if (!$id) die('Object not found.');
$pform->delete('PERSONS', ['ID' => $id]);
$app->redirect('examples/advform');
break;
//default action - show datagrid
case 'list':
default:
$pform->deleteSession();
$plist = new PCGrid("tpl/examples/personlist.tpl");
$plist->setQuery("select * from PERSONS order by CREATED_AT desc");
print $plist;
break;
}
?>