Friday, November 7, 2008

Using Xataface to create forms

You can leverage off the power of Xataface to create forms allowing users to submit data to your tables. Here is some code to allow you do that, I'll go into more explanation after:


$app =& Dataface_Application::getInstance();
$record =& $app->getRecord();
$form =& df_create_edit_record_form($record, array('FirstName','LastName'));

$form->addElement('hidden','-action','myaction');
if ($form->validate() ){
$res = $form->process(array(&$form, 'save'), true);
// could return false or PEAR_Error to indicate error.
header('Location: '.DATAFACE_SITE_HREF.'?-action=foo&--msg=Success');
exit;
}
$form->display();


The first two lines are basically grabbing a reference to the xataface application and the current record loaded.

$form =& df_create_edit_record_form($record, array('FirstName','LastName'));


This line will create a xataface form object which represents the same table that this record is taken from. It will only display the FirstName and LastName fields though since the second parameter allows you to select which fields to display. Because it is a edit record form, it will fill in the values of the form with the values from the record that was sent in through the parameter. You can alternatively use the df_create_new_record_form() to create a new form entirely.

$form->addElement('hidden','-action','myaction&#


This line adds a hidden element to the form and then sets the name of the hidden element to be -action. It is basically used to allow the form to figure out what action to take after it has been submitted. Generally, we set the action to be the same action as the current page and then allow the form to be validate (explained below)

if ($form->validate() ){
$res = $form->process(array(&$form, 'save'), true);
// could return false or PEAR_Error to indicate error.
header('Location: '.DATAFACE_SITE_HREF.'?-action=foo&--msg=Success');
exit;
}


The form first gets validated for valid values. And then if it returns true, it will then process the form and basically save the data to the database. From there, we need to redirect the user to the next location. We always put an exit statement after the header() to make sure the code stops after the redirect. Because should the redirect for some reason fail, we don't want the user to be see the form again.

$form->display();


Finally, if the form was not validated (ie. not submitted before, or values wrong) we need to display form which is what this line does.

And there you go! That's how you can use Xataface to help you create forms!

No comments: