TUTORIAL: "Form" Class #5: Quick & Dirty Forms - mudmin/UserSpice5-Dev GitHub Wiki

Although 25 lines is not unbearable (without the UserSpice classes it would probably take 4-10 times as many lines to get the same functionality) the Forms class can do even better. Here are several options you can set to tell the Forms class to make some assumptions and do some of the work automatically (most of these require that 'table' is also set in the options):

  • 'AutoLoad'=>true - load the data from the database according to 'table' and 'tableId' settings (no more need to query the database and set 'data'=>$fooData or use $myData->setFieldValues($fooData)). If no 'tableId' has been set then Form will check $_GET['id']; if it still doesn't find it then it assumes it is inserting a new record.
  • 'AutoLoadPosted'=>true - load the data from $_POST which was posted from the form (no more need to call $myData->setNewValues($_POST) explicitly)
  • 'AutoSave'=>true - save the data automatically (no more need to call $myData->updateIfValid() or $myData->insertIfValid() explicitly)
  • 'AutoShow'=>true - automatically display the form after the Form object is constructed (no more need to `echo $myForm->getHTML() explicitly)
  • 'default=>'all'- this turns on all of the AutoX settings above and also calculates a rough approximation of the form fields you wish to use (based on the columns in the database for the specified'table'`) so you don't have to specify them at all
  • since usually people don't want to see the ID, this field is automatically excluded in the output of the form.
  • 'ExcludeFields'=>['id'] - fields specified in the array (['id'] is the default) will be excluded from the form entirely

This means that these few lines of code are a fully functional database form, missing only the pretty formatting and the validation that could have been defined. But it makes for a great way of scaffolding your tables while you are in the process of developing.

<?php
$myForm = new Form([], [
    'dbtable' => 'foo',
    'default' => 'all',
]);

See how this works at tutorial/form5a.php?id=1. Try setting various values of ?id=n and leaving it out entirely.