[Html-widget] FormFu - validation module to check (unique)
constraints of dbix-class models in catalyst
Mario Minati
mario.minati at googlemail.com
Mon Mar 19 18:42:02 GMT 2007
For those how are interested how to create a validation modul in connection
with catalyst I post a modul which can validate a form against data in a
DBIx::Class model.
I define the validator in yaml like this:
validator:
- type: +glue::HTML::FormFu::Validator::DBIxClassModel
name: name
model: 'glueDB::Contact::Company'
match_params: [ name ]
negative_match_params: [ id ]
load_params_from_request: [ id ]
max_found: 0
The class looks like this:
-----------------------------------------------------------------------------
package glue::HTML::FormFu::Validator::DBIxClassModel;
use strict;
use warnings;
use base 'HTML::FormFu::Validator';
#use Data::Dumper;
__PACKAGE__->mk_accessors( qw/
load_params_from_request
model
match_params
max_found
negative_match_params
/ );
sub new {
my $self = shift->SUPER::new(@_);
#
$self->form->add_localize_object( 'glue::HTML::FormFu::Validator::DBIxClassModel::I18N' );
# default error name:
# form_glue_html_formfu_validator_dbixclassmodel_error
return $self;
}
sub validate_value {
my ( $self, $value, $params ) = @_;
my $model;
my $i = 0;
my $argument_params = {};
my $resultset;
my $match = {};
my $max = $self->max_found || 0;
my $ok;
return 1 if !defined $value || $value eq '';
# check model name
$self->model
or die "Model not named - Need model name for DB check.";
# check Catalyst context
$self->form->{stash}->{context}
or die "Catalyst context not available.";
# check for valid model
$model = $self->form->{stash}->{context}->model( $self->model )
or die "Model not defined - DB check failed for model '".
$self->model. "'.";
# get parameters from request
foreach my $param (@{$self->load_params_from_request || []}) {
$argument_params->{$param} =
$self->form->{stash}->{context}->request->arguments->[$i];
$i++;
}
# prepare hash for search operation in model
foreach my $param (@{$self->match_params || []}) {
$match->{$param} = $params->{$param}
if exists $params->{$param};
$match->{$param} = $argument_params->{$param}
if exists $argument_params->{$param};
}
foreach my $param (@{$self->negative_match_params || []}) {
$match->{$param} = { '!=', $params->{$param} }
if exists $params->{$param};
$match->{$param} = { '!=', $argument_params->{$param} }
if exists $argument_params->{$param};
}
#warn Dumper ($match);
# create resultset
$resultset = $model->search( $match )
or die "No resultset defined - DB check failed for model '".
$self->model. "'.";
#warn "cnt: ". $resultset->count." max:". $max;
# validate
$ok = $resultset->count <= $max;
return $ok;
}
1;
-----------------------------------------------------------------------------
Have fun,
Mario
More information about the Html-widget
mailing list