Debian Codegraph @

lib/HTML/FormHandler/Model/CDBI.pm

raw
1 package # hide from Pause
2 HTML::FormHandler::Model::CDBI;
3 # ABSTRACT: Class::DBI model class (non-functioning)
4
5 use Moose;
6 use Carp;
7 use Data::Dumper;
8 extends 'HTML::FormHandler';
9
10
11 HTML::FormHandler::Model::CDBI->meta->make_immutable;
12
13
14 sub init_item {
15 my $self = shift;
16
17 my $item_id = $self->item_id or return;
18 return $self->item_class->retrieve($item_id);
19 }
20
21 sub BUILDARGS {
22 my ( $self, @args ) = @_;
23 return {@args};
24 }
25
26
27 sub guess_field_type {
28 my ( $self, $column, $class ) = @_;
29
30 $class ||= $self->item_class;
31
32 return unless $class && $class->isa('Class::DBI');
33
34 my @return;
35
36 # Is it a direct has_a relationship?
37 if ( my $meta = $class->meta_info('has_a')->{$column} ) {
38 my $f_class = $meta->foreign_class;
39
40 @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 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 if ( @{ $meta->args->{mapping} } ) {
52 my $t;
53 ( $t, $f_class ) = $self->guess_field_type( $meta->args->{mapping}[0], $f_class );
54 }
55 @return = ( 'Multiple', $f_class );
56 }
57 elsif ( $column =~ /_time$/ ) {
58 @return = ('DateTime');
59 }
60 else {
61 @return = ('Text');
62 }
63
64 return wantarray ? @return : $return[0];
65 }
66
67
68 sub lookup_options {
69 my ( $self, $field ) = @_;
70
71 my $class = $self->item_class or return;
72 return unless $class->isa('Class::DBI');
73 my $field_name = $field->name;
74 my ( $type, $f_class ) = $self->guess_field_type( $field_name, $class );
75 return unless $f_class;
76
77 # label column
78 my $label_column = $field->label_column;
79 return unless $f_class->find_column($label_column);
80 # active column
81 my $active_col =
82 $self->can('active_column') ? $self->active_column :
83 $field->active_column;
84 $active_col = '' unless $f_class->find_column($active_col);
85 # sort column
86 my $sort_col = $field->sort_column;
87 $sort_col =
88 defined $sort_col && $f_class->find_column($sort_col) ? $sort_col :
89 $label_column;
90
91 my $criteria = {};
92 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 $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 if ($active_col) {
101 my @or = ( $active_col => 1 );
102 # But also include any existing non-active
103 push @or, ( "$primary_key" => $field->init_value ) # init_value is scalar or array ref
104 if $self->item && defined $field->init_value;
105 $criteria->{'-or'} = \@or;
106 }
107
108 my @rows = $f_class->search( $criteria, { order_by => $sort_col } );
109
110 return [
111 map {
112 my $label = $_->$label_column;
113 $_->id, $active_col && !$_->$active_col ? "[ $label ]" : "$label"
114 } @rows
115 ];
116
117 }
118
119
120 sub init_value {
121 my ( $self, $field, $item ) = @_;
122
123 my $column = $field->name;
124
125 $item ||= $self->item;
126 return if $field->writeonly;
127 return
128 unless $item &&
129 ( $item->can($column) ||
130 ( ref $item eq 'HASH' && exists $item->{$column} ) );
131 my @values;
132 if ( ref $item eq 'HASH' ) {
133 @values = $item->{$column} if ref($item) eq 'HASH';
134 }
135 elsif ( !$item->isa('Class::DBI') ) {
136 @values = $item->$column;
137 }
138 else {
139 @values =
140 map { ref $_ && $_->isa('Class::DBI') ? $_->id : $_ } $item->$column;
141 }
142
143 my $value = @values > 1 ? \@values : shift @values;
144 $field->init_value($value);
145 $field->value($value);
146 }
147
148
149 sub validate_model {
150 my ($self) = @_;
151
152 return unless $self->validate_unique;
153 return 1;
154 }
155
156
157 sub validate_unique {
158 my ($self) = @_;
159
160 my @unique = map { $_->name } grep { $_->unique } $self->fields;
161 return 1 unless @unique;
162
163 my $item = $self->item;
164
165 my $class = ref($item) || $self->item_class;
166 my $found_error = 0;
167 for my $field ( map { $self->field($_) } @unique ) {
168 next if $field->errors;
169 my $value = $field->value;
170 next unless defined $value;
171 my $name = $field->name;
172 # unique means there can only be on in the database like it.
173 my $match = $class->search( { $name => $value } )->first || next;
174 next if $self->items_same( $item, $match );
175 my $field_error = $field->unique_message ||
176 'Value must be unique in the database';
177 $field->add_error($field_error);
178 $found_error++;
179 }
180 return $found_error;
181 }
182
183 sub update_model {
184 my ($self) = @_;
185
186 # Grab either the item or the object class.
187 my $item = $self->item;
188 my $class = ref($item) || $self->item_class;
189 my $updated_or_created;
190
191 # get a hash of all fields
192 my %fields = map { $_->name, $_ } grep { !$_->noupdate } $self->fields;
193 # First process the normal and has_a columns
194 # as that data is directly stored in the object
195 my %data;
196 # Loads columns (including has_a)
197 foreach my $col ( $class->columns('All') ) {
198 next unless exists $fields{$col};
199 my $field = delete $fields{$col};
200 # If the field is flagged "clear" then set to NULL.
201 my $value = $field->value;
202 if ($item) {
203 my $cur = $item->$col;
204 next unless $value || $cur;
205 next if $value && $cur && $value eq $cur;
206 $item->$col($value);
207 }
208 else {
209 $data{$col} = $value;
210 }
211 }
212
213 if ($item) {
214 $item->update;
215 $updated_or_created = 'updated';
216 }
217 else {
218 $item = $class->create( \%data );
219 $self->item($item);
220 $updated_or_created = 'created';
221 }
222
223 # Now check for mapping/has_many in any left over fields
224
225 for my $field_name ( keys %fields ) {
226 next unless $class->meta_info('has_many');
227 next unless my $meta = $class->meta_info('has_many')->{$field_name};
228
229 my $field = delete $fields{$field_name};
230 my $value = $field->value;
231
232 # Figure out which values to keep and which to add
233 my %keep;
234 %keep = map { $_ => 1 } ref $value ? @$value : ($value)
235 if defined $value;
236
237 # Get foreign class and its key that points to $class
238 my $foreign_class = $meta->foreign_class;
239 my $foreign_key = $meta->args->{foreign_key};
240 my $related_key = $meta->args->{mapping}->[0];
241 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 for ( $foreign_class->search( { $foreign_key => $item } ) ) {
246 $_->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 ) for keys %keep;
256 }
257
258 # Save item in form object
259 $self->item($item);
260 return $item;
261 }
262
263
264 sub items_same {
265 my ( $self, $item1, $item2 ) = @_;
266
267 # returns true if both are undefined
268 return 1 if not defined $item1 and not defined $item2;
269 # return false if either undefined
270 return unless defined $item1 and defined $item2;
271 return $self->obj_key($item1) eq $self->obj_key($item2);
272 }
273
274
275 sub obj_key {
276 my ( $self, $item ) = @_;
277 return join '|', $item->table,
278 map { $_ . '=' . ( $item->$_ || '.' ) } $item->primary_columns;
279 }
280
281 __PACKAGE__->meta->make_immutable;
282 no Moose;
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.410002
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) 2017 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