
CGI::Widget::DBI::Search - Database search widget

use CGI;
use CGI::Widget::DBI::Search;
my $q = CGI->new;
my $ws = CGI::Widget::DBI::Search->new(q => $q);
# database connection info
$ws->{-dbi_connect_dsn} = 'DBI:Pg:dbname=my_pg_database;host=localhost';
$ws->{-dbi_user} = 'pguser';
$ws->{-dbi_pass} = 'pgpass';
# what table to use in the SQL query FROM clause
$ws->{-sql_table} = 'table1 t1 inner join table2 t2 using (key_col)';
# optional WHERE clause
$ws->{-where_clause} = 'WHERE t1.filter = ? OR t2.filter != ?';
# bind params needed for WHERE clause
$ws->{-bind_params} = [ $filter, $inverse_filter ];
# what columns to retrieve from query
$ws->{-sql_retrieve_columns} =
[ qw/t1.id t1.name t2.long_description/, '(t1.price + t2.price) AS total_price'];
# what columns to display in search results (with header name)
$ws->{-display_columns} =
{ id => "ID", name => "Name", long_description => "Description", total_price => "Price" };
$ws->{-numeric_columns} = { id => 1 };
$ws->{-currency_columns} = { total_price => 1 };
$ws->{-show_total_numresults} = 1;
# execute database search
$ws->search();
# output search results to browser
print $q->header;
print $q->start_html;
# show search results as HTML
print $ws->display_results();
print $q->end_html;

Encapsulates a DBI search in a Perl class, including all SQL statements required for performing the search, query results, HTML display methods, and multi-column, sortable result set displayed page-by-page (using HTML navigation links).

Creates and initializes a new CGI::Widget::DBI::Search object. Possible configuration options:
-dbi_connect_dsn => DBI data source name (full connection string) -dbi_user => database username -dbi_pass => database password -dbi_host => host to connect to database (overridden by -dbi_connect_dsn) -sql_database => database to connect to (overridden by -dbi_connect_dsn)
-sql_table => Database table(s) to query,
-sql_table_columns => [ARRAY] List of all columns in sql_table,
-sql_retrieve_columns => [ARRAY] List of columns for retrieval,
-opt_precols_sql => Optional SQL code to insert between 'SELECT' and
columns to retrieve (-sql_retrieve_columns).
This is commonly something like 'DISTINCT',
-where_clause => Literal SQL WHERE clause to use in SELECT state-
ment sent to database (may contain placeholders),
-default_orderby_columns => [ARRAY] Default list of columns to use in ORDER BY
clause. If 'sortby' cgi param is passed (e.g. from
user clicking a column sort link), it will always be
the first column in the ORDER BY clause, with these
coming after it.
-bind_params => [ARRAY] If -where_clause used placeholders ("?"),
this must be the ordered values to use for them,
-fetchrow_closure => (CODE) A code ref to execute upon retrieving a
single row of data from database. First arg to
closure will be calling object; subsequent args
will be the values of the retrieved row of data.
The closure's return value will be push()d onto the
object's results array, which is unique to a search.
It should be a hash reference with a key for each
column returned in the search, and values with the
search field values.
The following settings affect display of search results, but also affect the search logic (SQL query executed).
-max_results_per_page => Maximum number of database records to display on a
single page of search result display table
(default: 20)
-show_total_numresults => Show total number of records found by most recent
search, with First/Last page navigation links
(default: true)
The following settings only affect display of search results, not the search logic.
-display_table_padding => Size of HTML display table cellpadding attribute,
-display_columns => {HASH} Associative array holding column names as
keys, and labels for display table as values,
-numeric_columns => {HASH} Columns of numeric type should have a
true value in this hash,
-currency_columns => {HASH} Columns of monetary value should have a
true value in this hash,
-unsortable_columns => {HASH} Columns which the user should not be able
to sort should have a true value in this hash,
-pre_nondb_columns => [ARRAY] Columns to show left of database columns
in display table,
-post_nondb_columns => [ARRAY] Columns to show right of database columns
in display table,
(Note: Since no data from the database will be present for
-{pre,post}_nondb_columns columns, you should define
-columndata_closures for each column you list)
-optional_header => Optional HTML header to display just above search
result display table,
-optional_footer => Optional HTML footer to display just below search
result display table,
-href_extra_vars => Extra CGI params to append to column sorting and
navigation links in search result display table.
May be either a HASHREF or a literal string
containing key/values to append. If a key in the
HASHREF has an undef value, will take the value
from an existing CGI param on request named the
same as key.
-action_uri => HTTP URI of script this is running under
(default: SCRIPT_NAME environment variable),
-page_range_nav_limit => Maximum number of pages to allow user to navigate to
before and after the current page in the result set
(default: 10)
-columndata_closures => {HASH} of (CODE): Reference to a hash containing a
code reference for each column which should be
passed through before displaying in result table.
Each closure will be passed 3 arguments:
$searchobj (this CGI::Widget::DBI::Search object),
$row (the current row from the result set)
$color (the current background color of this row)
and is (currently) expected to return an HTML table
cell (e.g. "<td>blah</td>")
-display_mode => ('table'|'grid') Which of the default display modes
to use, table or grid.
(default: table)
-display_class => Actual class to use to display search results.
(default: CGI::Widget::DBI::Search::Display::Table)
-grid_columns => Maximum number of columns to render, if displaying
as grid
-no_persistent_object => Inform object that we are not running under a
persistent object framework (eg. Apache::Session):
disable all features which enhance performance
under a persistence framework, and enable features
necessary for smooth operation without persistence
(default: true)

Sets necessary object variables from defaults in package constants, if not already set. Called from search() method.

This is the default -fetchrow_closure that will be called for each row returned by a search. It can be called by an overridden -fetchrow_closure to selectively modify desired fields.
Perform the search: runs the database query, and stores the matched results in an object variable: 'results'.
Optional parameters $where_clause and $bind_params will override object variables -where_clause and -bind_params. If $clobber is true, search results from a previous execution will be deleted before running new search.
Executes a SELECT COUNT() query with the current search parameters and stores result in object variable: 'numresults'. Has no effect unless -show_total_numresults object variable is true. As a side-effect, this method also sets the 'lastpage' object variable which, no surprise, is the page number denoting the last page in the search result set.
This is used for displaying total number of results found, and is necessary to provide a last-page link to skip to the end of the search results.
Sorts a single page of results by column $col. Reorders object variable 'results' based on sort column $col and boolean $reverse parameters.
(note: method currently unused)
Displays an HTML table of data values stored in object variable 'results' (retrieved from the most recent call to search() method). Optional variable $disp_cols overrides object variable -display_columns.
Transfers all display-specific settings from search widget object to the search display widget object.

Adi Fairbank <adi@adiraj.org>

Copyright (C) 2004-2008 Adi Fairbank

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.

Apr 18, 2008