File: Group.pm

package info (click to toggle)
libhtml-formfu-perl 0.09007-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 4,184 kB
  • sloc: perl: 13,186; makefile: 9; sql: 5
file content (579 lines) | stat: -rw-r--r-- 14,789 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
package HTML::FormFu::Role::Element::Group;
use Moose::Role;

with 'HTML::FormFu::Role::Element::Field',
     'HTML::FormFu::Role::Element::SingleValueField' => { -excludes => 'nested_name' },
     'HTML::FormFu::Role::Element::ProcessOptionsFromModel',
     'HTML::FormFu::Role::Element::SingleValueField',
     'HTML::FormFu::Role::Element::Coercible';

use HTML::FormFu::Attribute qw( mk_output_accessors );
use HTML::FormFu::Util qw( append_xml_attribute literal xml_escape );
use Clone ();
use List::MoreUtils qw( none );
use Scalar::Util qw( reftype );
use Carp qw( croak );

has empty_first => ( is => 'rw', traits => ['Chained'] );

__PACKAGE__->mk_output_accessors(qw( empty_first_label ));

has _options => (
    is      => 'rw',
    default => sub { [] },
    lazy    => 1,
    isa     => 'ArrayRef',
);

my @ALLOWED_OPTION_KEYS = qw(
    group
    value
    value_xml
    value_loc
    label
    label_xml
    label_loc
    attributes
    attrs
    attributes_xml
    attrs_xml
    container_attributes
    container_attrs
    container_attributes_xml
    container_attrs_xml
    label_attributes
    label_attrs
    label_attributes_xml
    label_attrs_xml
    placeholder
    placeholder_xml
    placeholder_loc
);

after BUILD => sub {
    my $self = shift;

    $self->container_attributes( {} );

    return;
};

after process => sub {
    my $self = shift;

    $self->_process_options_from_model;

    return;
};

sub options {
    my ( $self, $arg ) = @_;
    my ( @options, @new );

    return $self->_options if @_ == 1;

    croak "options argument must be a single array-ref" if @_ > 2;

    if ( defined $arg ) {
        croak "options argument must be an array-ref"
            if reftype($arg) ne 'ARRAY';
        
        @options = @$arg;

        if ( $self->empty_first ) {
            push @new, $self->_get_empty_first_option;
        }

        for my $item (@options) {
            push @new, $self->_parse_option($item);
        }
    }

    $self->_options( \@new );

    return $self;
}

sub _get_empty_first_option {
    my ($self) = @_;

    my $label = $self->empty_first_label || '';

    return {
        value                => '',
        label                => $label,
        attributes           => {},
        container_attributes => {},
        label_attributes     => {},
    };
}

sub _parse_option {
    my ( $self, $item ) = @_;

    if ( reftype($item) eq 'HASH' ) {
        return $self->_parse_option_hashref($item);
    }
    elsif ( reftype($item) eq 'ARRAY' ) {
        return {
            value                => $item->[0],
            label                => $item->[1],
            attributes           => {},
            container_attributes => {},
            label_attributes     => {},
        };
    }
    else {
        croak "each options argument must be a hash-ref or array-ref";
    }
}

sub _parse_option_hashref {
    my ( $self, $item ) = @_;

    # sanity check options
    my @keys = keys %$item;

    for my $key (@keys) {
        croak "unknown option argument: '$key'"
            if none { $key eq $_ } @ALLOWED_OPTION_KEYS;

        my $short = $key;

        if ( $short =~ s/attributes/attrs/ ) {
            for my $cmp (@keys) {
                next if $cmp eq $key;

                croak "cannot use both '$key' and '$short' arguments"
                    if $cmp eq $short;
            }
        }
    }

    if ( exists $item->{group} ) {
        my @group = @{ $item->{group} };
        my @new;
        for my $groupitem (@group) {
            push @new, $self->_parse_option($groupitem);
        }
        $item->{group} = \@new;
    }

    if ( !exists $item->{attributes} ) {
        $item->{attributes}
            = exists $item->{attrs}
            ? $item->{attrs}
            : {};
    }

    if ( exists $item->{attributes_xml} ) {
        for my $key ( keys %{ $item->{attributes_xml} } ) {
            $item->{attributes}{$key}
                = literal( $item->{attributes_xml}{$key} );
        }
    }
    elsif ( exists $item->{attrs_xml} ) {
        for my $key ( keys %{ $item->{attrs_xml} } ) {
            $item->{attributes}{$key} = literal( $item->{attrs_xml}{$key} );
        }
    }

    if ( !exists $item->{container_attributes} ) {
        $item->{container_attributes}
            = exists $item->{container_attrs}
            ? $item->{container_attrs}
            : {};
    }

    if ( exists $item->{container_attributes_xml} ) {
        for my $key ( keys %{ $item->{container_attributes_xml} } ) {
            $item->{container_attributes}{$key}
                = literal( $item->{container_attributes_xml}{$key} );
        }
    }
    elsif ( exists $item->{container_attrs_xml} ) {
        for my $key ( keys %{ $item->{container_attrs_xml} } ) {
            $item->{container_attributes}{$key}
                = literal( $item->{container_attrs_xml}{$key} );
        }
    }

    if ( !exists $item->{label_attributes} ) {
        $item->{label_attributes}
            = exists $item->{label_attrs}
            ? $item->{label_attrs}
            : {};
    }

    if ( exists $item->{label_attributes_xml} ) {
        for my $key ( keys %{ $item->{label_attributes_xml} } ) {
            $item->{label_attributes}{$key}
                = literal( $item->{label_attributes_xml}{$key} );
        }
    }
    elsif ( exists $item->{label_attrs_xml} ) {
        for my $key ( keys %{ $item->{label_attrs_xml} } ) {
            $item->{label_attributes}{$key}
                = literal( $item->{label_attrs_xml}{$key} );
        }
    }

    if ( defined $item->{label_xml} ) {
        $item->{label} = literal( $item->{label_xml} );
    }
    elsif ( defined $item->{label_loc} ) {
        $item->{label} = $self->form->localize( $item->{label_loc} );
    }

    if ( defined $item->{placeholder_xml} ) {
        $item->{placeholder} = literal( $item->{placeholder_xml} );
    }
    elsif ( defined $item->{placeholder_loc} ) {
        $item->{placeholder} = $self->form->localize( $item->{placeholder_loc} );
    }

    if ( defined $item->{value_xml} ) {
        $item->{value} = literal( $item->{value_xml} );
    }
    elsif ( defined $item->{value_loc} ) {
        $item->{value} = $self->form->localize( $item->{value_loc} );
    }

    if ( !defined $item->{value} ) {
        $item->{value} = '';
    }

    return $item;
}

sub values {
    my ( $self, $arg ) = @_;

    croak "values argument must be a single array-ref of values" if @_ > 2;

    my @values;

    if ( defined $arg ) {
        croak "values argument must be an array-ref"
            if reftype($arg) ne 'ARRAY';
        
        @values = @$arg;
    }

    my @new = map { {
            value                => $_,
            label                => ucfirst $_,
            attributes           => {},
            container_attributes => {},
            label_attributes     => {},
        }
    } @values;

    if ( $self->empty_first ) {
        unshift @new, $self->_get_empty_first_option;
    }

    $self->_options( \@new );

    return $self;
}

sub value_range {
    my ( $self, $arg ) = @_;
    my (@values);

    croak "value_range argument must be a single array-ref of values"
        if @_ > 2;

    if ( defined $arg ) {
        croak "value_range argument must be an array-ref"
            if reftype($arg) ne 'ARRAY';
        
        @values = @$arg;
    }

    croak "range must contain at least 2 values" if @values < 2;

    my $end   = pop @values;
    my $start = pop @values;

    return $self->values( [ @values, $start .. $end ] );
}

before prepare_attrs => sub {
    my ( $self, $render ) = @_;

    my $submitted = $self->form->submitted;
    my $default   = $self->default;

    my $value
        = defined $self->name
        ? $self->get_nested_hash_value( $self->form->input, $self->nested_name )
        : undef;

    if ( ( reftype($value) || '' ) eq 'ARRAY' ) {
        my $elems = $self->form->get_fields({ nested_name => $self->nested_name });
        if ( $#$elems ) {
            # There are multiple fields with the same name; assume
            # none are multi-value fields, i.e. only one selected
            # option per field.  (Otherwise it might be ambiguous
            # which option came from which field.)
            for ( 0 .. @$elems - 1 ) {
                if ( $self == $elems->[$_] ) {
                    # Use the value of the option actually selected in
                    # this group.
                    $value = $value->[$_];
                }
            }
        }
    }

    if ( !$submitted && defined $default ) {
        for my $deflator ( @{ $self->_deflators } ) {
            $default = $deflator->process($default);
        }
    }

    for my $option ( @{ $render->{options} } ) {
        if ( exists $option->{group} ) {
            for my $item ( @{ $option->{group} } ) {
                $self->_prepare_attrs( $submitted, $value, $default, $item );
            }
        }
        else {
            $self->_prepare_attrs( $submitted, $value, $default, $option );
        }
    }

    return;
};

around render_data_non_recursive => sub {
    my ( $orig, $self, $args ) = @_;

    my $render = $self->$orig( {
            options => Clone::clone( $self->_options ),
            $args ? %$args : (),
        } );

    $self->_quote_options( $render->{options} );

    return $render;
};

sub _quote_options {
    my ( $self, $options ) = @_;

    foreach my $opt (@$options) {
        $opt->{label} = xml_escape( $opt->{label} );
        $opt->{placeholder} = xml_escape( $opt->{placeholder} );
        $opt->{value} = xml_escape( $opt->{value} );
        $opt->{attributes}           = xml_escape( $opt->{attributes} );
        $opt->{label_attributes}     = xml_escape( $opt->{label_attributes} );
        $opt->{container_attributes} = xml_escape( $opt->{container_attributes} );

        if ( exists $opt->{group} ) {
            $self->_quote_options( $opt->{group} );
        }
    }
}

sub string {
    my ( $self, $args ) = @_;

    $args ||= {};

    my $render
        = exists $args->{render_data}
        ? $args->{render_data}
        : $self->render_data;

    # field wrapper template - start

    my $html = $self->_string_field_start($render);

    # input_tag template

    $html .= $self->_string_field($render);

    # field wrapper template - end

    $html .= $self->_string_field_end($render);

    return $html;
}

sub as {
    my ( $self, $type, %attrs ) = @_;

    return $self->_coerce(
        type       => $type,
        attributes => \%attrs,
        errors     => $self->_errors,
        package    => __PACKAGE__,
    );
}

around clone => sub {
    my ( $orig, $self ) = @_;

    my $clone = $self->$orig(@_);

    $clone->_options( Clone::clone( $self->_options ) );

    return $clone;
};

1;

__END__

=head1 NAME

HTML::FormFu::Element::_Group - grouped form field base-class

=head1 DESCRIPTION

Base class for L<HTML::FormFu::Element::Checkboxgroup>,
L<HTML::FormFu::Element::Radiogroup>, and 
L<HTML::FormFu::Element::Select> fields.

=head1 METHODS

=head2 options

Arguments: none

Arguments: \@options

    ---
    elements:
      - type: Select
        name: foo
        options:
          - [ 01, January ]
          - [ 02, February ]
          - value: 03
            label: March
            attributes:
              style: highlighted
          - [ 04, April ]

If passed no arguments, it returns an arrayref of the currently set options.

Use to set the list of items in the select menu / radiogroup.

Its arguments must be an array-ref of items. Each item may be an array ref 
of the form C<[ $value, $label ]> or a hash-ref of the form 
C<< { value => $value, label => $label } >>. Each hash-ref may also have an
C<attributes> key.

Passing an item containing a C<group> key will, for 
L<Select fields|HTML::FormFu::Element::Select>, create an optgroup. And for 
L<Radiogroup fields|HTML::FormFu::Element::Radiogroup> or
L<Checkboxgroup fields|HTML::FormFu::Element::Checkboxgroup>, create a
sub-group of radiobuttons or checkboxes with a new C<span> block, with the
classname C<subgroup>.

An example of Select optgroups:

    ---
    elements:
      - type: Select
        name: foo
        options:
          - label: "group 1"
            group:
              - [1a, 'item 1a']
              - [1b, 'item 1b']
          - label: "group 2"
            group:
              - [2a, 'item 2a']
              - [2b, 'item 2b']

When using the hash-ref construct, the C<label_xml> and C<label_loc> 
variants of C<label> are supported, as are the C<value_xml> and C<value_loc> 
variants of C<value>, the C<attributes_xml> variant of C<attributes> and the 
C<label_attributes_xml> variant of C<label_attributes>.

C<container_attributes> or C<container_attributes_xml> is used by 
L<HTML::FormFu::Element::Checkboxgroup> and 
L<HTML::FormFu::Element::Radiogroup> for the c<span> surrounding each
item's input and label. It is ignored by L<HTML::FormFu::Element::Select>
elements.

C<label_attributes> / C<label_attributes_xml> is used by 
L<HTML::FormFu::Element::Checkboxgroup> and 
L<HTML::FormFu::Element::Radiogroup> for the c<label> tag of each item.
It is ignored by L<HTML::FormFu::Element::Select> elements.

=head2 values

Arguments: \@values

    ---
    elements:
      - type: Radiogroup
        name: foo
        values:
          - jan
          - feb
          - mar
          - apr

A more concise alternative to L</options>. Use to set the list of values in 
the select menu / radiogroup.

Its arguments must be an array-ref of values. The labels used are the 
result of C<ucfirst($value)>.

=head2 value_range

Arguments: \@values

    ---
    elements:
      - type: Select
        name: foo
        value_range:
          - ""
          - 1
          - 12 

Similar to L</values>, but the last 2 values are expanded to a range. Any 
preceding values are used literally, allowing the common empty first item
in select menus.

=head2 empty_first

If true, then a blank option will be inserted at the start of the option list
(regardless of whether L</options>, L</values> or L</value_range> was used to
populate the options).  See also L</empty_first_label>.

=head2 empty_first_label

=head2 empty_first_label_xml

=head2 empty_first_label_loc

If L</empty_first> is true, and L</empty_first_label> is set, this value will
be used as the label for the first option - so only the first option's value
will be empty.

=head1 SEE ALSO

Is a sub-class of, and inherits methods from 
L<HTML::FormFu::Element::_Field>, L<HTML::FormFu::Element>

L<HTML::FormFu>

=head1 AUTHOR

Carl Franks, C<cfranks@cpan.org>

=head1 LICENSE

This library is free software, you can redistribute it and/or modify it under
the same terms as Perl itself.

=cut