Please note: This is an unpublished site and we are making changes - glitches still!!!

 The News Edit Module

This module is the longest so far but very straightforward and probably pretty easy to understand.
news_edit_module.php
<?php
require_once "UpdateFormObj.class.php";
class news_edit_module extends CmsModule {
    function init(){
        $this->initDB();
    }
 
    function fetch(){
        // save the referer for use in the DBUpdate redirect 
        $_SESSION['_ref'] = $_SERVER['HTTP_REFERER'];
        $form = new UpdateForm();
        setlocale(LC_ALL,$GLOBALS['cms_config']['locale']);
        // get stuff needed from $_GET
        $editact = $this->GET['editact'];
        $id      = $this->GET['id'];
        // Initialize title,button and form actions
        switch($editact){
            case "edit"     : 
                $form->setTitle("Edit this article");      
                $form->setAction("?act=save_news&saveact=update");
                $form->setSubmitText("Save article");            
                break;
            case "delete": 
                $form->setTitle("Remove this article");    
                $form->setAction("./index.php?act=save_news&saveact=delete");
                $form->setSubmitText("Delete article");
                // do not allow for editing if we are deleting
                $form->setReadOnly(true);
                break;
            case "insert": 
                $form->setTitle("Add new article");        
                $form->setAction("./index.php?act=save_news&saveact=insert");
                $ucf->setSubmitText("Save new article");
                break;
            default: $form->setTitle("Unknown editact: $editact"); 
        }
        // if edit/delete show the form with data
        if (($editact=="edit") || ($editact=="delete")) {
            $query = "select id," .
                     "DATE_FORMAT(newsdate,'%Y-%m-%d')AS newsdate,".
                     "title, ingress, article " .
                     "FROM site_news where id=$id";
            $result = mysql_query($query) or 
                      die ("[".$query."], ".mysql_error());
            if (mysql_num_rows($result)==0) {
                return "<h1>Alert: No data found at record: $id";
            }                
            $row = mysql_fetch_object($result);
            //foreach ($row as $key=>$value) $GLOBALS[$key]=$value
            $id = $row->id;
            $newsdate = $row->newsdate;
            $title    = $row->title;
            $ingress= $row->ingress;
            $article= $row->article;
        // create an empty form to insert data
        } else if ($editact=='insert'){
            // default to today's date
            $newsdate = date_format("%Y-%m-%d");
            $title = "";
            $ingress = "";
            $article = "";
        }
        // Add the fields and possible subtitles
        $form->addSubTitle("Set the news date");        
        $form->addField("newsdate",$newsdate,"Date","DATE");
        $form->addField("title",$title,"Title","TEXT");
 
        $form->addSubTitle("Write the news in less than 255 characters");
        $form->addField("ingress",$ingress,"Ingress","TEXTAREA");
        $form->limitInputLength(-1,250);
 
        $form->addSubTitle("Write the full story here");
        $form->addField("article",$article,"Article","TEXTAREA",80,10);
        $form->addHiddenField("id",$id);
        $form->addHiddenField("_ref",$_SERVER['HTTP_REFERER']);
 
        $form->setSmarty(new Smarty());
        $form->assignSmarty();
        $output = $form->fetchTemplate("UpdateFormObj.tpl");        
        return $output;        
    }
}
?>
Save this as admin/modules/news/news_edit_module.php.  Like before, we will have a closer look at what goes on here.
 
After creating the form we inspect the "editact" to know what to do. If we will either edit or delete the record we must show it to the user and fetch data from the database. If we insert we will use default values.
 
After that we add subtitles (self-explanatory) and fields. The syntax for addField is:
 
addField(<field name>, <inital value>,<field label>,<field type>,<extra parms>);
field name
This is the html form field name that is passed to the DBUpdate process
inital value
Either from the database or set by other means (see the default date set to "today")
field label
The label next to the field
field type
one of "date", "time", "text", "checkbox", "select", "file", "password", "radiogroup", "textarea", "plaintext" or "function"
 
A textarea has two extra parameters "cols" and "rows".
 
We can (and sometimes must) add some extra stuff to make the form work the way we intend it to do. A select dropdown, for instance, needs data to be fed into it. It can be done in a multitude of ways like with a comma-delimited value string and an output string:
 
$form->addField("position",$position,"Position","select");
$form->addOptions(-1,"1,2,3,4","Worker,Manager,Director,President");
 
The parameter "-1" tells the class to add these options to the last field added. This produces a nice select box with the 1,2,3,4 as the values and the texts shown to the user. Another very handy way of addint options is to use SQL:
 
$form->addField("group",$group,"Product group","select");
$form->addOptionsSQL(-1,"SELECT id,name FROM product_groups");
 
You can also instruct the form to have an empty option "please select":
 
$form->addField("group",$group,"Product group","select");
$form->addOptionsSQL(-1,"SELECT id,name FROM types",true,"select one",-9);
 
The "true" above results in having an "empty" option "select one" on top with value "-9".
That's about all we need to know so far. The code above should produce a valid basic HTML form. Now it is time to have a look at the database update process. 
 
Here is an example of what the editing form looks like:
As you can see the form is a no-frills basic form that does its job in daily use.
 
The full UpdateForm documentation will be available at a later date.

The DBUpdate Process

This is the shortest of the "holy trinity". The code looks like this:
 
news_save_article_module.php
<?php
include "DBUpdate.class.php";
class news_save_article_module extends CmsModule {
 
    function init(){
        $this->initDB();
    }
    function fetch() {
    	// get $_POST variables
        $id       = mysql_real_escape_string( $_POST['id'] );
        $title    = mysql_real_escape_string( $_POST['title'] );
        $newsdate = $_POST['newsdate'];
        $ingress  = mysql_real_escape_string( $_POST['ingress'] );
        $article  = mysql_real_escape_string( $_POST['article'] );
        $saveact  = $_POST['saveact'];
	// Create object (so stands for SaveObject)
        $so = new DBUpdate();
        // add fields to the object
        $so->addField('title',$title,'text');
        $so->addField('newsdate',$newsdate,'date');
        $so->addField('ingress',$ingress,'text');
        $so->addField('article',$article,'text');
        // set table name, action and condition
        $so->setTableName('site_news');
        $so->setSaveAct($saveact);
        $so->setCondition("id = '$id'");
        // create query
        $so->createQuery();
        $result = $so->commitQuery();
        // did we have success?
        if (!$result){ 
            $_alert =  $so->msg_error;
        } else {
            // we might need the insert id for post-insert
            // activity, this is not needed here, though 
            $lastID = $so->getInsertID();
        }
        // retrieve and unset the saved referer value
        $url = $_POST['_ref'];
        if ($_alert != "")
            $url .= "&_alert=Error saving item ($alert)";
        header("location: $url");
        exit;
    }
}
?>

This is fairly simple. You get the values from the POST data, create an object, add the fields and the data to the object, tell which table to update, set the desired action (insert, delete or update), set the condition, create and commit the query. Actually the commitQuery checks whether the SQL has been generated and if not it will call the createQuery() automatically.

If needed we can also retrieve the insert id after a successful insert (here just as an example). In the form phase we saved the referrer URL to a hidden variable.
 
And after that we simply go back to the URL where we pressed the editing button. This is where you can add information or an alert to the URL if you wish
 
The next task we have is the What-You-See-Is-What-You-Get editor. Worried? You have a good reason to be!