[html-formfu] HTML::FormFu::Element::DBIC::Select for review

Mario Minati mario.minati at googlemail.com
Fri Sep 7 23:16:26 GMT 2007


Hello @all,

I would like to share my HTML::FormFu::Element::DBIC::Select class, as the 
community around FormFu is growing now, someone else might need it or use it 
for inspiration.

It has no documentation and test, it's just working(tm).

I use it to create select boxes which gets it's data from the table, where 
also the models have relations. 

It takes as parameters:
model - the dbic model name
search - the search function to use (search by default)
name_field - the fieldname containing the displayed name (the name field of 
the element by default)
value_field - the fieldname containing the value ('id' by default)

Greets,
Mario

PS:
Maybe someone else can think about the shortcut I build in for performance 
reasons. Do I might ran in a DB issue?

==============================

package HTML::FormFu::Element::DBIC::Select;

use strict;
use warnings;

use base 'HTML::FormFu::Element::Select';

use Carp;


__PACKAGE__->mk_accessors( qw/
    model
    search
    name_field
    value_field
/ );


sub process {
    my $self = shift;

    $self->_add_options;

    my $process = $self->next::method( { @_ ? %{ $_[0] } : () } );

    return $process;
}


sub render {
    my $self = shift;

    $self->_add_options;

    my $render = $self->next::method( { @_ ? %{ $_[0] } : () } );

    return $render;
}


sub _add_options {
    my $self = shift;

    # shortcut
    if (defined $self->{__data}) {
        $self->options( $self->{__data} );
        return;
    }

    my $stash = $self->form->{stash};

    # check model name
    $self->model
        or die "Model not named - Need model name for DB check.";

    # check Catalyst context
    $stash->{context}
        or die "Catalyst context not available.";

    # check for valid model
    my $model = $stash->{context}->model( $self->model )
        or die "Model not defined - DB check failed for model '". 
$self->model. "'.";

    # search function
    my $search = $self->search() || 'search';

    # get data
    my @data = $model->$search()->all();

    # get name and value fields
    my $name_field = $self->name_field  || $self->name;
    my $value_field = $self->value_field || 'id';

    # create array of options
    my @options = map { [ $_->$value_field, $_->$name_field ] } @data;

    # safe for shortcut
    $self->{__data} = \@options;

    # set array of options
    $self->options( \@options );

    return;
}


1;

__END__



More information about the HTML-FormFu mailing list