Your Mother has asked for the wisdom of the Perl Monks concerning the following question:
I'm working on an idea for a personal module to simplify automatic and appropriate generation of html form fields from DBI or from a db handle. I'd like to know:
Oh, and the CGI::MxScreen family is something I came across while digging that looks pretty interesting but doesn't do what I'm after. Anyone have any feedback on it?
Any related general feedback, experience, code snippets is, of course, welcome. Code bits and expanded query follow.
Given a hypothetical module SQL::DBIforms. It should take a DBI handle and return sensible form fields by querying the table for column info. A VARCHAR(10) would become a text input limited to 10 chars. An ENUM field would become a dropdown. A SET would become a scrolling menu allowing multiple selections and so on.
Then with the supposed module, SQL::DBIforms, something along these lines (loose code, no error checking):# Given a test table along the lines of use test; CREATE TABLE userish ( id INT(6) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, user VARCHAR(16) UNIQUE NOT NULL, updated DATE NOT NULL, type ENUM('admin','user','root','bot') NOT NULL DEFAULT 'user' ) TYPE = InnoDB;
Which would result in something like:use DBI; use SQL::DBIforms; my $connect_file = '/etc/www/.mysql.www'; my $dbh = DBI->connect( "DBI:mysql:database=userish;host=localhost;" . "mysql_read_default_file=$connect_file;" ); my $db_fields = SQL::DBIforms::make_form_fields($dbh, 'userish'); for my $field ( @{db_fields} ) { next if $field->type eq 'DATE'; # want to stamp in background print $field . ": \n", ucfirst $field->form_field, $field->is_required ? ' (required)' : '', # for NOT NULL "\n<p>\n"; }
The code in the SQL::DBIforms to get info out of the db handle would look something like:Id: <input type="text" name="userish.id" size=6 maxlength=6> (required) <p> User: <input type="text" name="userish.user size=16 maxlength=16> (required +) <p> Type: <select name="userish.type"> <option value="admin">admin <option selected value="user">user <option value="root">root <option value="bot">bot </select> (required)
Thank you for looking!use Data::Dumper; sub make_form_fields { my ( $dbh, $table ) = @_; my $sth = $dbh->prepare (qq{ DESCRIBE ?; }); my $table_info = $dbh->selectall_arrayref($sth, $ATTR, $table); # then parse that structure to get info and turn it into an array of f +ield objects # NOT NULL would set a required flag # DEFAULT value would drop into same for field and so on # I haven't written the parsing, just playing still so a cop out... return = "<PRE>", Dumper($table), "</PRE>\n"; }
|
|---|