File Coverage

blib/lib/HTML/FormHandler/Model/CDBI.pm
Criterion Covered Total %
statement 12 141 8.5
branch 0 88 0.0
condition 0 54 0.0
subroutine 4 14 28.5
pod 9 10 90.0
total 25 307 8.1


line stmt bran cond sub pod time code
1             package # hide from Pause
2             HTML::FormHandler::Model::CDBI;
3             # ABSTRACT: Class::DBI model class (non-functioning)
4              
5 1     1   1529 use Moose;
  1         2  
  1         8  
6 1     1   4634 use Carp;
  1         2  
  1         61  
7 1     1   679 use Data::Dumper;
  1         4637  
  1         1297  
8             extends 'HTML::FormHandler';
9              
10              
11             HTML::FormHandler::Model::CDBI->meta->make_immutable;
12              
13              
14             sub init_item {
15 0     0 1   my $self = shift;
16              
17 0 0         my $item_id = $self->item_id or return;
18 0           return $self->item_class->retrieve($item_id);
19             }
20              
21             sub BUILDARGS {
22 0     0 1   my ( $self, @args ) = @_;
23 0           return {@args};
24             }
25              
26              
27             sub guess_field_type {
28 0     0 1   my ( $self, $column, $class ) = @_;
29              
30 0   0       $class ||= $self->item_class;
31              
32 0 0 0       return unless $class && $class->isa('Class::DBI');
33              
34 0           my @return;
35              
36             # Is it a direct has_a relationship?
37 0 0         if ( my $meta = $class->meta_info('has_a')->{$column} ) {
    0          
    0          
38 0           my $f_class = $meta->foreign_class;
39              
40 0 0         @return =
41             $f_class->isa('DateTime') ? ('DateTime') :
42             ( 'Select', $f_class );
43              
44             # Otherwise, check for has_many
45             }
46             elsif ( $meta = $class->meta_info('has_many')->{$column} ) {
47              
48 0           my $f_class = $meta->foreign_class;
49             # Is there a mapping table in between? If so need to find the
50             # actual class for lookups -- call recursively
51 0 0         if ( @{ $meta->args->{mapping} } ) {
  0            
52 0           my $t;
53 0           ( $t, $f_class ) = $self->guess_field_type( $meta->args->{mapping}[0], $f_class );
54             }
55 0           @return = ( 'Multiple', $f_class );
56             }
57             elsif ( $column =~ /_time$/ ) {
58 0           @return = ('DateTime');
59             }
60             else {
61 0           @return = ('Text');
62             }
63              
64 0 0         return wantarray ? @return : $return[0];
65             }
66              
67              
68             sub lookup_options {
69 0     0 1   my ( $self, $field ) = @_;
70              
71 0 0         my $class = $self->item_class or return;
72 0 0         return unless $class->isa('Class::DBI');
73 0           my $field_name = $field->name;
74 0           my ( $type, $f_class ) = $self->guess_field_type( $field_name, $class );
75 0 0         return unless $f_class;
76              
77             # label column
78 0           my $label_column = $field->label_column;
79 0 0         return unless $f_class->find_column($label_column);
80             # active column
81 0 0         my $active_col =
82             $self->can('active_column') ? $self->active_column :
83             $field->active_column;
84 0 0         $active_col = '' unless $f_class->find_column($active_col);
85             # sort column
86 0           my $sort_col = $field->sort_column;
87 0 0 0       $sort_col =
88             defined $sort_col && $f_class->find_column($sort_col) ? $sort_col :
89             $label_column;
90              
91 0           my $criteria = {};
92 0           my $primary_key = $f_class->primary_column;
93             # In cases where the f_class is the same as the item's class don't
94             # include item in the option list -- don't want to be able to have item point to itself
95             # Obviously, this doesn't prevent circular references.
96 0 0         $criteria->{"$primary_key"} = { '!=', $self->item->id }
97             if $f_class eq ref $self->item;
98              
99             # If there's an active column, only select active OR items already selected
100 0 0         if ($active_col) {
101 0           my @or = ( $active_col => 1 );
102             # But also include any existing non-active
103 0 0 0       push @or, ( "$primary_key" => $field->init_value ) # init_value is scalar or array ref
104             if $self->item && defined $field->init_value;
105 0           $criteria->{'-or'} = \@or;
106             }
107              
108 0           my @rows = $f_class->search( $criteria, { order_by => $sort_col } );
109              
110             return [
111             map {
112 0           my $label = $_->$label_column;
  0            
113 0 0 0       $_->id, $active_col && !$_->$active_col ? "[ $label ]" : "$label"
114             } @rows
115             ];
116              
117             }
118              
119              
120             sub init_value {
121 0     0 1   my ( $self, $field, $item ) = @_;
122              
123 0           my $column = $field->name;
124              
125 0   0       $item ||= $self->item;
126 0 0         return if $field->writeonly;
127             return
128             unless $item &&
129             ( $item->can($column) ||
130 0 0 0       ( ref $item eq 'HASH' && exists $item->{$column} ) );
      0        
131 0           my @values;
132 0 0         if ( ref $item eq 'HASH' ) {
    0          
133 0 0         @values = $item->{$column} if ref($item) eq 'HASH';
134             }
135             elsif ( !$item->isa('Class::DBI') ) {
136 0           @values = $item->$column;
137             }
138             else {
139             @values =
140 0 0 0       map { ref $_ && $_->isa('Class::DBI') ? $_->id : $_ } $item->$column;
  0            
141             }
142              
143 0 0         my $value = @values > 1 ? \@values : shift @values;
144 0           $field->init_value($value);
145 0           $field->value($value);
146             }
147              
148              
149             sub validate_model {
150 0     0 1   my ($self) = @_;
151              
152 0 0         return unless $self->validate_unique;
153 0           return 1;
154             }
155              
156              
157             sub validate_unique {
158 0     0 1   my ($self) = @_;
159              
160 0           my @unique = map { $_->name } grep { $_->unique } $self->fields;
  0            
  0            
161 0 0         return 1 unless @unique;
162              
163 0           my $item = $self->item;
164              
165 0   0       my $class = ref($item) || $self->item_class;
166 0           my $found_error = 0;
167 0           for my $field ( map { $self->field($_) } @unique ) {
  0            
168 0 0         next if $field->errors;
169 0           my $value = $field->value;
170 0 0         next unless defined $value;
171 0           my $name = $field->name;
172             # unique means there can only be on in the database like it.
173 0   0       my $match = $class->search( { $name => $value } )->first || next;
174 0 0         next if $self->items_same( $item, $match );
175 0   0       my $field_error = $field->unique_message ||
176             'Value must be unique in the database';
177 0           $field->add_error($field_error);
178 0           $found_error++;
179             }
180 0           return $found_error;
181             }
182              
183             sub update_model {
184 0     0 0   my ($self) = @_;
185              
186             # Grab either the item or the object class.
187 0           my $item = $self->item;
188 0   0       my $class = ref($item) || $self->item_class;
189 0           my $updated_or_created;
190              
191             # get a hash of all fields
192 0           my %fields = map { $_->name, $_ } grep { !$_->noupdate } $self->fields;
  0            
  0            
193             # First process the normal and has_a columns
194             # as that data is directly stored in the object
195 0           my %data;
196             # Loads columns (including has_a)
197 0           foreach my $col ( $class->columns('All') ) {
198 0 0         next unless exists $fields{$col};
199 0           my $field = delete $fields{$col};
200             # If the field is flagged "clear" then set to NULL.
201 0           my $value = $field->value;
202 0 0         if ($item) {
203 0           my $cur = $item->$col;
204 0 0 0       next unless $value || $cur;
205 0 0 0       next if $value && $cur && $value eq $cur;
      0        
206 0           $item->$col($value);
207             }
208             else {
209 0           $data{$col} = $value;
210             }
211             }
212              
213 0 0         if ($item) {
214 0           $item->update;
215 0           $updated_or_created = 'updated';
216             }
217             else {
218 0           $item = $class->create( \%data );
219 0           $self->item($item);
220 0           $updated_or_created = 'created';
221             }
222              
223             # Now check for mapping/has_many in any left over fields
224              
225 0           for my $field_name ( keys %fields ) {
226 0 0         next unless $class->meta_info('has_many');
227 0 0         next unless my $meta = $class->meta_info('has_many')->{$field_name};
228              
229 0           my $field = delete $fields{$field_name};
230 0           my $value = $field->value;
231              
232             # Figure out which values to keep and which to add
233 0           my %keep;
234 0 0         %keep = map { $_ => 1 } ref $value ? @$value : ($value)
  0 0          
235             if defined $value;
236              
237             # Get foreign class and its key that points to $class
238 0           my $foreign_class = $meta->foreign_class;
239 0           my $foreign_key = $meta->args->{foreign_key};
240 0           my $related_key = $meta->args->{mapping}->[0];
241 0 0         die "Failed to find related_key for field [$field] in class [$class]"
242             unless $related_key;
243              
244             # Delete any items that are not to be kept
245 0           for ( $foreign_class->search( { $foreign_key => $item } ) ) {
246 0 0         $_->delete unless delete $keep{ $_->$related_key };
247             }
248              
249             # Add in new ones
250             $foreign_class->create(
251             {
252             $foreign_key => $item,
253             $related_key => $_,
254             }
255 0           ) for keys %keep;
256             }
257              
258             # Save item in form object
259 0           $self->item($item);
260 0           return $item;
261             }
262              
263              
264             sub items_same {
265 0     0 1   my ( $self, $item1, $item2 ) = @_;
266              
267             # returns true if both are undefined
268 0 0 0       return 1 if not defined $item1 and not defined $item2;
269             # return false if either undefined
270 0 0 0       return unless defined $item1 and defined $item2;
271 0           return $self->obj_key($item1) eq $self->obj_key($item2);
272             }
273              
274              
275             sub obj_key {
276 0     0 1   my ( $self, $item ) = @_;
277             return join '|', $item->table,
278 0   0       map { $_ . '=' . ( $item->$_ || '.' ) } $item->primary_columns;
  0            
279             }
280              
281             __PACKAGE__->meta->make_immutable;
282 1     1   11 no Moose;
  1         1  
  1         62  
283             1;
284              
285             __END__
286              
287             =pod
288              
289             =encoding UTF-8
290              
291             =head1 NAME
292              
293             HTML::FormHandler::Model::CDBI - Class::DBI model class (non-functioning)
294              
295             =head1 VERSION
296              
297             version 0.40067
298              
299             =head1 SYNOPSIS
300              
301             package MyApplication::Form::User;
302             use strict;
303             use base 'HTML::FormHandler::Model::CDBI';
304              
305              
306             # Associate this form with a CDBI class
307             has '+item_class' => ( default => 'MyDB::User' );
308              
309             # Define the fields that this form will operate on
310             sub field_list {
311             return {
312             [
313             name => 'Text',
314             age => 'PosInteger',
315             sex => 'Select',
316             birthdate => 'DateTimeDMYHM',
317             ]
318             };
319             }
320              
321             =head1 DESCRIPTION
322              
323             A Class::DBI database model for HTML::FormHandler
324              
325             I don't use CDBI, so this module almost certainly doesn't work.
326             It is only being left here as a starting point in case somebody is
327             interested in getting it to work.
328              
329             Patches and tests gratefully accepted.
330              
331             =head1 METHODS
332              
333             =head2 item_class
334              
335             The name of your database class.
336              
337             =head2 init_item
338              
339             This is called first time $form->item is called.
340             It does the equivalent of:
341              
342             return $self->item_class->retrieve( $self->item_id );
343              
344             =head2 guess_field_type
345              
346             Pass in a column and assigns field types.
347             Must set $self->item_class to return the related item class.
348             Returns the type in scalar context, returns the type and maybe the related table
349             in list context.
350              
351             Currently returns:
352              
353             DateTime - for a has_a relationship that isa DateTime
354             Select - for a has_a relationship
355             Multiple - for a has_many
356             DateTime - if the field ends in _time
357             Text - otherwise
358              
359             =head2 lookup_options
360              
361             Returns a array reference of key/value pairs for the column passed in.
362             Calls $field->label_column to get the column name to use as the label.
363             The default is "name". The labels are sorted by Perl's cmp sort.
364              
365             If there is an "active" column then only active are included, with the exception
366             being if the form (item) has currently selected the inactive item. This allows
367             existing records that reference inactive items to still have those as valid select
368             options. The inactive labels are formatted with brackets to indicate in the select
369             list that they are inactive.
370              
371             The active column name is determined by calling:
372              
373             $active_col = $form->can( 'active_column' )
374             ? $form->active_column
375             : $field->active_column;
376              
377             Which allows setting the name of the active column globally if
378             your tables are consistently named (all lookup tables have the same
379             column name to indicate they are active), or on a per-field basis.
380              
381             In addition, if the foreign class is the same as the item's class (or the class returned
382             by item_class) then options pointing to item are excluded. The reason for this is
383             for a table column that points to the same table (self referenced), such as a "parent"
384             column. The assumption is that a record cannot be its own parent.
385              
386             =head2 init_value
387              
388             Populate $field->value with object ids from the CDBI object. If the column
389             expands to more than one object then an array ref is set.
390              
391             =head2 validate_model
392              
393             Validates fields that are dependent on the model.
394             Currently, "unique" fields are checked to make sure they are unique.
395              
396             This validation happens after other form validation. The form already has any
397             field values entered in $field->value at this point.
398              
399             =head2 validate_unique
400              
401             Checks that the value for the field is not currently in the database.
402              
403             =head2 items_same
404              
405             Returns true if the two passed in cdbi objects are the same object.
406             If both are undefined returns true.
407              
408             =head2 obj_key
409              
410             returns a key for a given object, or undef if the object is undefined.
411              
412             =head1 AUTHOR
413              
414             FormHandler Contributors - see HTML::FormHandler
415              
416             =head1 COPYRIGHT AND LICENSE
417              
418             This software is copyright (c) 2016 by Gerda Shank.
419              
420             This is free software; you can redistribute it and/or modify it under
421             the same terms as the Perl 5 programming language system itself.
422              
423             =cut