Building queries with db_form

db_form has also the ability to help with simple query creation. In order to do so, it must know the structure of a table that is stored inside tabledesc Obliquid table. Before switching to Metabase db_form class was fairly complex, in order to handle many db datatypes, and when a datatype not used before was found it stopped to work. Now these problems are solved because Metabase has just a few simple datatypes.

Further in order to support the creation of the next value a sequence must exist on the table. A sequence is a small table, added to Metabase XML table definition file. For example:

    <sequence>
        <name>{{$tprefix}}module</name>
        <start>1</start>
        <on> <table>{{$tprefix}}module</table>
             <field>id_module</field>
        </on>
    </sequence>
  
  

To build an insert query you need to create a new Id and call executeSqlInsert method.

  $dbf =& new db_form();
  if ($_POST["action"]=="add_record") {
      //the form was posted for insert
      $dbf->setDbConnection($_obweb->mb);
      $dbf->setTable("module", $_obweb->tprefix); //setTable clears form values!
      $dbf->parseForm(); //parse the form and reassign it back to controls
      $dbf->newId();     //creates a new id
      $dbf->executeSqlInsert(); //executes an insert query
  }
  //here the form will be built as explained in the previous sections
  

To build an update query you need to fetch the existing record from database with fetch method, and then call executeSqlUpdate method.

  $dbf =& new db_form();
  $dbf->setDbConnection($_obweb->mb);
  $dbf->setTable("module", $_obweb->tprefix); //setTable clears form values!
  //fetches the current record for the update or the form below
  $dbf->fetch($_GET["id"]);
  if ($_POST["action"]=="mod_record") {
      //the form was posted for update
      $dbf->parseForm(); //parse the form and reassign it back to controls
      $dbf->executeSqlUpdate(); //executes an insert query
  }
  //here the form will be built as explained in the previous sections
  

This part needs some more explanations: the fetch method stores the record in internal private variables. Just after a fetch, I can get the value for author with $dbf->getValue("author"), but after a parseForm, the same instruction will return the value coming from the form. The reason for this apparently strange behaviour is that form values have higher priority, and this is a design feature of db_form. In this way if any of the column existing in the table is not added in the form it will be preserved, because when a form value is not found, the db value will be returned instead.

In some cases you need to explicitly refer to form values or db_values, this is possible with the methods getFormValue (or using PHP $_POST array) and with getDbValue.