Debian Codegraph @

lib/HTML/FormHandler/Field/Select.pm

raw
1 package HTML::FormHandler::Field::Select;
2 # ABSTRACT: select fields
3 $HTML::FormHandler::Field::Select::VERSION = '0.410002';
4 use Moose;
5 extends 'HTML::FormHandler::Field';
6 use Carp;
7
8
9 has 'options' => (
10 isa => 'HFH::SelectOptions',
11 is => 'rw',
12 coerce => 1,
13 traits => ['Array'],
14 auto_deref => 1,
15 handles => {
16 all_options => 'elements',
17 reset_options => 'clear',
18 clear_options => 'clear',
19 has_options => 'count',
20 num_options => 'count',
21 },
22 lazy => 1,
23 builder => 'build_options'
24 );
25 sub options_ref { [shift->options] }
26 # this is used for rendering
27 has 'options_index' => ( traits => ['Counter'], isa => 'Num',
28 is => 'rw', default => 0,
29 handles => { inc_options_index => 'inc', dec_options_index => 'dec',
30 reset_options_index => 'reset' },
31 );
32 sub clear_data {
33 my $self = shift;
34 $self->next::method();
35 $self->reset_options_index;
36 }
37
38 sub build_options { [] }
39 has 'options_from' => ( isa => 'Str', is => 'rw', default => 'none' );
40 has 'do_not_reload' => ( isa => 'Bool', is => 'ro' );
41 has 'no_option_validation' => ( isa => 'Bool', is => 'rw' );
42 has 'option_wrapper' => ( is => 'rw' );
43
44 sub BUILD {
45 my $self = shift;
46
47 $self->build_options_method;
48 if( $self->options && $self->has_options ) {
49 $self->options_from('build');
50 $self->default_from_options([$self->options]);
51 }
52 $self->input_without_param; # vivify
53 }
54
55 has 'options_method' => (
56 traits => ['Code'],
57 is => 'ro',
58 isa => 'CodeRef',
59 writer => '_set_options_method',
60 predicate => 'has_options_method',
61 handles => { 'get_options' => 'execute_method' },
62 );
63
64 sub build_options_method {
65 my $self = shift;
66
67 my $set_options = $self->set_options;
68 $set_options ||= "options_" . HTML::FormHandler::Field::convert_full_name($self->full_name);
69 if ( $self->form && $self->form->can($set_options) ) {
70 my $attr = $self->form->meta->find_method_by_name( $set_options );
71 if ( $attr and $attr->isa('Moose::Meta::Method::Accessor') ) {
72 $self->_set_options_method( sub { my $self = shift; $self->form->$set_options; } );
73 }
74 else {
75 $self->_set_options_method( sub { my $self = shift; $self->form->$set_options($self); } );
76 }
77 }
78 }
79
80 has 'sort_options_method' => (
81 traits => ['Code'],
82 is => 'rw',
83 isa => 'CodeRef',
84 predicate => 'has_sort_options_method',
85 handles => {
86 sort_options => 'execute_method',
87 },
88 );
89
90 has 'set_options' => ( isa => 'Str', is => 'ro');
91
92 has 'multiple' => ( isa => 'Bool', is => 'rw', default => '0' );
93 # following is for unusual case where a multiple select is a has_many type relation
94 has 'has_many' => ( isa => 'Str', is => 'rw' );
95 has 'size' => ( isa => 'Int|Undef', is => 'rw' );
96 has 'label_column' => ( isa => 'Str', is => 'rw', default => 'name' );
97 has 'localize_labels' => ( isa => 'Bool', is => 'rw' );
98 has 'active_column' => ( isa => 'Str', is => 'rw', default => 'active' );
99 has 'auto_widget_size' => ( isa => 'Int', is => 'rw', default => '0' );
100 has 'sort_column' => ( isa => 'Str|ArrayRef[Str]', is => 'rw' );
101 has '+widget' => ( default => 'Select' );
102 sub html_element { 'select' }
103 has '+type_attr' => ( default => 'select' );
104 has 'empty_select' => ( isa => 'Str', is => 'rw' );
105 has '+deflate_method' => ( default => sub { \&select_deflate } );
106 has '+input_without_param' => ( lazy => 1, builder => 'build_input_without_param' );
107 sub build_input_without_param {
108 my $self = shift;
109 if( $self->multiple ) {
110 $self->not_nullable(1);
111 return [];
112 }
113 else {
114 return '';
115 }
116 }
117 has 'value_when_empty' => ( is => 'ro', lazy => 1, builder => 'build_value_when_empty' );
118 sub build_value_when_empty {
119 my $self = shift;
120 return [] if $self->multiple;
121 return undef;
122 }
123
124 our $class_messages = {
125 'select_not_multiple' => 'This field does not take multiple values',
126 'select_invalid_value' => '\'[_1]\' is not a valid value',
127 };
128
129 sub get_class_messages {
130 my $self = shift;
131 return {
132 %{ $self->next::method },
133 %$class_messages,
134 }
135 }
136
137 sub select_widget {
138 my $field = shift;
139
140 my $size = $field->auto_widget_size;
141 return $field->widget unless $field->widget eq 'Select' && $size;
142 my $options = $field->options || [];
143 return 'Select' if @$options > $size;
144 return $field->multiple ? 'checkbox_group' : 'radio_group';
145 }
146
147 sub as_label {
148 my ( $self, $value ) = @_;
149
150 $value = $self->value unless defined $value;
151 return unless defined $value;
152 if ( $self->multiple ) {
153 unless ( ref($value) eq 'ARRAY' ) {
154 if( $self->has_inflate_default_method ) {
155 my @values = $self->inflate_default($value);
156 $value = \@values;
157 }
158 else {
159 # not sure under what circumstances this would happen, but
160 # just in case
161 return $value;
162 }
163 }
164 my @labels;
165 my %value_hash;
166 @value_hash{@$value} = ();
167 for ( $self->options ) {
168 if ( exists $value_hash{$_->{value}} ) {
169 push @labels, $_->{label};
170 delete $value_hash{$_->{value}};
171 last unless keys %value_hash;
172 }
173 }
174 my $str = join(', ', @labels);
175 return $str;
176 }
177 else {
178 for ( $self->options ) {
179 return $_->{label} if $_->{value} eq $value;
180 }
181 }
182 return;
183 }
184
185 sub _inner_validate_field {
186 my ($self) = @_;
187
188 my $value = $self->value;
189 return unless defined $value; # nothing to check
190
191 if ( ref $value eq 'ARRAY' &&
192 !( $self->can('multiple') && $self->multiple ) )
193 {
194 $self->add_error( $self->get_message('select_not_multiple') );
195 return;
196 }
197 elsif ( ref $value ne 'ARRAY' && $self->multiple ) {
198 $value = [$value];
199 $self->_set_value($value);
200 }
201
202 return if $self->no_option_validation;
203
204 # create a lookup hash
205 my %options;
206 foreach my $opt ( @{ $self->options } ) {
207 if ( exists $opt->{group} ) {
208 foreach my $group_opt ( @{ $opt->{options} } ) {
209 $options{$group_opt->{value}} = 1;
210 }
211 }
212 else {
213 $options{$opt->{value}} = 1;
214 }
215 }
216 if( $self->has_many ) {
217 $value = [map { $_->{$self->has_many} } @$value];
218 }
219 for my $value ( ref $value eq 'ARRAY' ? @$value : ($value) ) {
220 unless ( $options{$value} ) {
221 $self->add_error($self->get_message('select_invalid_value'), $value);
222 return;
223 }
224 }
225 return 1;
226 }
227
228 sub _result_from_object {
229 my ( $self, $result, $item ) = @_;
230
231 $result = $self->next::method( $result, $item );
232 $self->_load_options;
233 $result->_set_value($self->default)
234 if( defined $self->default && not $result->has_value );
235 return $result;
236 }
237
238 sub _result_from_fields {
239 my ( $self, $result ) = @_;
240
241 $result = $self->next::method($result);
242 $self->_load_options;
243 $result->_set_value($self->default)
244 if( defined $self->default && not $result->has_value );
245 return $result;
246 }
247
248 sub _result_from_input {
249 my ( $self, $result, $input, $exists ) = @_;
250
251 $input = ref $input eq 'ARRAY' ? $input : [$input]
252 if $self->multiple;
253 $result = $self->next::method( $result, $input, $exists );
254 $self->_load_options;
255 $result->_set_value($self->default)
256 if( defined $self->default && not $result->has_value );
257 return $result;
258 }
259
260 sub _load_options {
261 my $self = shift;
262
263 return
264 if ( $self->options_from eq 'build' ||
265 ( $self->has_options && $self->do_not_reload ) );
266 my @options;
267 if( $self->has_options_method ) {
268 @options = $self->get_options;
269 $self->options_from('method');
270 }
271 elsif ( $self->form ) {
272 my $full_accessor;
273 $full_accessor = $self->parent->full_accessor if $self->parent;
274 @options = $self->form->lookup_options( $self, $full_accessor );
275 $self->options_from('model') if scalar @options;
276 }
277 return unless @options; # so if there isn't an options method and no options
278 # from a table, already set options attributes stays put
279
280 # possibilities:
281 # @options = ( 1 => 'one', 2 => 'two' );
282 # @options = ([ 1 => 'one', 2 => 'tw' ]);
283 # @options = ([ { value => 1, label => 'one'}, { value => 2, label => 'two'}]);
284 # @options = ([[ 'one', 'two' ]]);
285 my $opts = ref $options[0] eq 'ARRAY' ? $options[0] : \@options;
286 if ( ref $opts->[0] eq 'HASH' ) {
287 # do the array of hashrefs separately so we can get the defaults
288 $self->default_from_options($opts);
289 }
290 $opts = $self->options($opts); # coerce will reformat
291 if ($opts) {
292 # sort options if sort method exists
293 $opts = $self->sort_options($opts) if $self->has_sort_options_method;
294 $self->options($opts);
295 }
296 }
297
298 # This is because setting 'checked => 1' or 'selected => 1' in an options
299 # hashref is the equivalent of setting a default on the field. Originally
300 # that was handled only in rendering, but it moved knowledge about where
301 # the 'fif' value came from into the renderer, which was bad. So instead
302 # we're setting the defaults from the options.
303 # It's probably better to use 'defaults' to start with, but since there are
304 # people using this method, this at least normalizes it.
305 sub default_from_options {
306 my ( $self, $options ) = @_;
307
308 my @defaults = map { $_->{value} } grep { $_->{checked} || $_->{selected} } @$options;
309 if( scalar @defaults ) {
310 if( $self->multiple ) {
311 $self->default(\@defaults);
312 }
313 else {
314 $self->default($defaults[0]);
315 }
316 }
317 }
318
319 before 'value' => sub {
320 my $self = shift;
321
322 return undef unless $self->has_result;
323 my $value = $self->result->value;
324 if( $self->multiple ) {
325 if ( !defined $value || $value eq '' || ( ref $value eq 'ARRAY' && scalar @$value == 0 ) ) {
326 $self->_set_value( $self->value_when_empty );
327 }
328 elsif ( $self->has_many && scalar @$value && ref($value->[0]) ne 'HASH' ) {
329 my @new_values;
330 foreach my $ele (@$value) {
331 push @new_values, { $self->has_many => $ele };
332 }
333 $self->_set_value( \@new_values );
334 }
335 }
336 };
337
338 sub select_deflate {
339 my ( $self, $value ) = @_;
340
341 return $value unless ( $self->has_many && $self->multiple );
342
343 # the following is for the edge case of a has_many select
344 return $value unless ref($value) eq 'ARRAY' && scalar @$value && ref($value->[0]) eq 'HASH';
345 return [map { $_->{$self->has_many} } @$value];
346 }
347
348 __PACKAGE__->meta->make_immutable;
349 use namespace::autoclean;
350 1;
351
352 __END__
353
354 =pod
355
356 =encoding UTF-8
357
358 =head1 NAME
359
360 HTML::FormHandler::Field::Select - select fields
361
362 =head1 VERSION
363
364 version 0.410002
365
366 =head1 DESCRIPTION
367
368 This is a field that includes a list of possible valid options.
369 This can be used for select and multiple-select fields.
370 Widget type is 'select'.
371
372 Because select lists and checkbox_groups do not return an HTTP
373 parameter when the entire list is unselected, the Select field
374 must assume that the lack of a param means unselection. So to
375 avoid setting a Select field, it must be set to inactive, not
376 merely not included in the HTML for a form.
377
378 This field type can also be used for fields that use the
379 'radio_group' widget, and the 'checkbox_group' widget (for
380 selects with multiple flag turned on, or that use the Multiple
381 field).
382
383 =head2 options
384
385 The 'options' array can come from a number of different places:
386
387 =over 4
388
389 =item From a field declaration
390
391 In a field declaration:
392
393 has_field 'opt_in' => ( type => 'Select', widget => 'RadioGroup',
394 options => [{ value => 0, label => 'No'}, { value => 1, label => 'Yes'} ] );
395
396 =item From a field class 'build_options' method
397
398 In a custom field class:
399
400 package MyApp::Field::WeekDay;
401 use Moose;
402 extends 'HTML::FormHandler::Field::Select';
403 ....
404 sub build_options {
405 my $i = 0;
406 my @days = ('Sunday', 'Monday', 'Tuesday', 'Wednesday',
407 'Thursday', 'Friday', 'Saturday' );
408 return [
409 map {
410 { value => $i++, label => $_ }
411 } @days
412 ];
413 }
414
415 =item From a coderef supplied to the field definition
416
417 has_field 'flim' => ( type => 'Select', options_method => \&flim_options );
418 sub flim_options { <return options array> }
419
420 =item From a form 'options_<field_name>' method or attribute
421
422 has_field 'fruit' => ( type => 'Select' );
423 sub options_fruit {
424 return (
425 1 => 'apples',
426 2 => 'oranges',
427 3 => 'kiwi',
428 );
429 }
430 -- or --
431 has 'options_fruit' => ( is => 'rw', traits => ['Array'],
432 default => sub { [1 => 'apples', 2 => 'oranges',
433 3 => 'kiwi'] } );
434
435 Notice that, as a convenience, you can return a simple array (or arrayref)
436 for the options array in the 'options_field_name' method. The hashrefs with
437 'value' and 'label' keys will be constructed for you by FormHandler.
438
439 =item From the database
440
441 The final source of the options array is a database when the name of the
442 accessor is a relation to the table holding the information used to construct
443 the select list. The primary key is used as the value. The other columns used are:
444
445 label_column -- Used for the labels in the options (default 'name')
446 active_column -- The name of the column to be used in the query (default 'active')
447 that allows the rows retrieved to be restricted
448 sort_column -- The name or arrayref of names of the column(s) used to sort the options
449
450 See also L<HTML::FormHandler::Model::DBIC>, the 'lookup_options' method.
451
452 =back
453
454 The options field should contain one of the following data structures:
455
456 =over
457
458 =item ArrayRef of HashRefs
459
460 Each hash reference defines an option, with the label and value
461 attributes corresponding to those of the HTML field.
462
463 =item ArrayRef
464
465 A list of key/value pairs corresponding to HTML field values and labels.
466
467 =item ArrayRef containing one ArrayRef
468
469 Each item inside the inner ArrayRef defines both the label and value of
470 an option.
471
472 =back
473
474 =head2 Customizing options
475
476 Additional attributes can be added in the options array hashref, by using
477 the 'attributes' key. If you have custom rendering code, you can add any
478 additional key that you want, of course.
479
480 Note that you should *not* set 'checked' or 'selected' attributes in options.
481 That is handled by setting a field default.
482
483 An options array with an extra 'note' key:
484
485 sub options_license
486 {
487 my $self = shift;
488 return unless $self->schema;
489 my $licenses = $self->schema->resultset('License')->search({active => 1},
490 {order_by => 'sequence'});
491 my @selections;
492 while ( my $license = $licenses->next ) {
493 push @selections, { value => $license->id, label => $license->label,
494 note => $license->note };
495 }
496 return @selections;
497 }
498
499 Setting the select element to disabled:
500
501 sub options_license
502 {
503 my $self = shift;
504 return unless $self->schema;
505 my $licenses = $self->schema->resultset('License')->search(undef,
506 {order_by => 'sequence'});
507 my @selections;
508 while ( my $license = $licenses->next ) {
509 push @selections, { value => $license->id, label => $license->label,
510 attributes => { disabled => ($license->active == 0) ? 1 : 0 } };
511 }
512 return @selections;
513 }
514
515 You can also divide the options up into option groups. See the section on
516 rendering.
517
518 =head2 Reloading options
519
520 If the options come from the options_<fieldname> method or the database, they
521 will be reloaded every time the form is reloaded because the available options
522 may have changed. To prevent this from happening when the available options are
523 known to be static, set the 'do_not_reload' flag, and the options will not be
524 reloaded after the first time
525
526 =head2 Sorting options
527
528 The sorting of the options may be changed using a 'sort_options' method in a
529 custom field class. The 'Multiple' field uses this method to put the already
530 selected options at the top of the list. Note that this won't work with
531 option groups.
532
533 =head1 Attributes and Methods
534
535 =head2 options
536
537 The options available for this field as defined in the L<< /DESCRIPTION
538 >> above.
539
540 =head2 options_method
541
542 Coderef of method to return options
543
544 =head2 multiple
545
546 If true allows multiple input values
547
548 =head2 size
549
550 This can be used to store how many items should be offered in the UI
551 at a given time. Defaults to 0.
552
553 =head2 empty_select
554
555 Set to the string value of the select label if you want the renderer
556 to create an empty select value. This only affects rendering - it does
557 not add an entry to the list of options.
558
559 has_field 'fruit' => ( type => 'Select',
560 empty_select => '---Choose a Fruit---' );
561
562 =head2 value_when_empty
563
564 Usually the empty value is an empty arrayref. This attribute allows
565 changing that. Used by SelectCSV field.
566
567 =head2 label_column
568
569 Sets or returns the name of the method to call on the foreign class
570 to fetch the text to use for the select list.
571
572 Refers to the method (or column) name to use in a related
573 object class for the label for select lists.
574
575 Defaults to "name".
576
577 =head2 localize_labels
578
579 For the renderers: whether or not to call the localize method on the select
580 labels. Default is off.
581
582 =head2 active_column
583
584 Sets or returns the name of a boolean column that is used as a flag to indicate that
585 a row is active or not. Rows that are not active are ignored.
586
587 The default is "active".
588
589 If this column exists on the class then the list of options will included only
590 rows that are marked "active".
591
592 The exception is any columns that are marked inactive, but are also part of the
593 input data will be included with brackets around the label. This allows
594 updating records that might have data that is now considered inactive.
595
596 =head2 auto_widget_size
597
598 This is a way to provide a hint as to when to automatically
599 select the widget to display for fields with a small number of options.
600 For example, this can be used to decided to display a radio select for
601 select lists smaller than the size specified.
602
603 See L<select_widget> below.
604
605 =head2 sort_column
606
607 Sets or returns the column or arrayref of columns used in the foreign class
608 for sorting the options labels. Default is undefined.
609
610 If not defined the label_column is used as the sort condition.
611
612 =head2 select_widget
613
614 If the widget is 'select' for the field then will look if the field
615 also has a L<auto_widget_size>. If the options list is less than or equal
616 to the L<auto_widget_size> then will return C<radio_group> if L<multiple> is false,
617 otherwise will return C<checkbox_group>.
618
619 =head2 as_label
620
621 Returns the option label for the option value that matches the field's current value.
622 Can be helpful for displaying information about the field in a more friendly format.
623
624 =head2 no_option_validation
625
626 Set this flag to true if you don't want to validate the options that are submitted.
627 This would generally only happen if the options are generated via javascript.
628
629 =head2 error messages
630
631 Customize 'select_invalid_value' and 'select_not_multiple'. Though neither of these
632 messages should really be seen by users in a properly constructed select.
633
634 =head1 Rendering
635
636 The 'select' field can be rendered by the 'Select', 'RadioGroup', and 'CheckboxGroup'
637 widgets. 'RadioGroup' is for a single select, and 'CheckboxGroup' is for a multiple
638 select.
639
640 Option groups can be rendered by providing an options arrays with 'group' elements
641 containing options:
642
643 sub options_testop { (
644 {
645 group => 'First Group',
646 options => [
647 { value => 1, label => 'One' },
648 { value => 2, label => 'Two' },
649 { value => 3, label => 'Three' },
650 ],
651 },
652 {
653 group => 'Second Group',
654 options => [
655 { value => 4, label => 'Four' },
656 { value => 5, label => 'Five' },
657 { value => 6, label => 'Six' },
658 ],
659 },
660 ) }
661
662 The select rendering widgets all have a 'render_option' method, which may be useful
663 for situations when you want to split up the rendering of a radio group or checkbox group.
664
665 =head2 Rendering with Template Toolkit
666
667 Calling 'options' from Template Toolkit can causes issues with wantarray when there
668 is only a single option. As a solution you should use 'options_ref'.
669
670 =head1 Database relations
671
672 Also see L<HTML::FormHandler::TraitFor::Model::DBIC>.
673
674 The single select is for a DBIC 'belongs_to' relation. The multiple select is for
675 a 'many_to_many' relation.
676
677 There is very limited ability to do multiple select with 'has_many' relations.
678 It will only work in very specific circumstances, and requires setting
679 the 'has_many' attribute to the name of the primary key of the related table.
680 This is a somewhat peculiar data structure for a relational database, and may
681 not be what you really want. A 'has_many' is usually represented with a Repeatable
682 field, and may require custom code if the form structure doesn't match the database
683 structure. See L<HTML::FormHandler::Manual::Cookbook>.
684
685 =head1 AUTHOR
686
687 FormHandler Contributors - see HTML::FormHandler
688
689 =head1 COPYRIGHT AND LICENSE
690
691 This software is copyright (c) 2017 by Gerda Shank.
692
693 This is free software; you can redistribute it and/or modify it under
694 the same terms as the Perl 5 programming language system itself.
695
696 =cut