Instant Forms from Tables with Solar

By | April 14, 2006

I was talking with Matthew this morning, and he asked if I was setting up a methodology to create forms using table definitions. My answer was “yes!”.

Here’s an example: 2 lines to start Solar, 2 lines to connect to an existing Solar_Sql_Table, 2 lines to create a Solar_Form using the table columns, and 2 lines to display it with Solar_View using the associated form helper. (The “Solar_Model_Nodes” table is part of the existing Solar_Content domain model.)

<?php
// prelims
require 'Solar.php';
Solar::start();

// sql and table connection
Solar::register('sql', 'Solar_Sql');
$table = Solar::factory('Solar_Model_Nodes');

// get a form and load elements from the table
$form = Solar::factory('Solar_Form');
$form->load('Solar_Form_Load_Table', $table);

// display the form
$view = Solar::factory('Solar_View');
echo $view->form($form);

// done!
Solar::stop();
?>

This creates an element for each column and a form-level validation based on the column datatype. Number and string columns get a properly-sized “text” element, CLOBs get a “textarea”, and booleans get a checkbox. If the column has its own validation of “inList” or “inKeys”, it gets a “select” element of the allowed values. Soon, when I add Ajax-y widgets, date/time/timestamp columns will get date-picker elements.

The $form->load() call can use ‘Solar_Form_Load_Xml’ too, if you want to define forms using XML. (I don’t, but Matthew liked the idea and contributed the code.)

If you only want certain columns, you can pass a list of them as the third param to $form->load():

$cols = array('email', 'subj', 'body');
$form->load('Solar_Form_Load_Table', $table, $cols);

Now, this is not all sweetness and light; the magic requires that you do the work of definining your columns in the Solar_Sql_Table class. Lucky for us, that’s pretty easy. More on that in another post.

2 thoughts on “Instant Forms from Tables with Solar

  1. Tomek

    In my very own framework I’m using MDB2’s Reverse module to dynamically get table definition directly from RDBMS – would be cool to have something like that in Solar too.
    What is also worth considering is a second parameter for $view->form() that would tell $view where to look for form’s templates. This way designers can use many different looking forms in one page.

    Reply
  2. pmjones Post author

    Hi Tomek — Solar_View_Helper_Form uses CSS for layout, so you can design a different-looking form by setting the form ID to a related CSS identifier. E.g., $form->attrib[‘class’] = ‘formClassId'; echo $view->form($form).

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *