-
Notifications
You must be signed in to change notification settings - Fork 75
/
Field.pm
1572 lines (1292 loc) · 47.5 KB
/
Field.pm
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package HTML::FormHandler::Field;
# ABSTRACT: base class for fields
use HTML::FormHandler::Moose;
use HTML::FormHandler::Field::Result;
use Try::Tiny;
use Moose::Util::TypeConstraints;
use HTML::FormHandler::Merge ('merge');
use HTML::FormHandler::Render::Util('cc_widget', 'ucc_widget');
use Sub::Name;
with 'HTML::FormHandler::Traits';
with 'HTML::FormHandler::Validate';
with 'HTML::FormHandler::Widget::ApplyRole';
with 'HTML::FormHandler::TraitFor::Types';
our $VERSION = '0.02';
=head1 SYNOPSIS
Instances of Field subclasses are generally built by L<HTML::FormHandler>
from 'has_field' declarations or the field_list, but they can also be constructed
using new for test purposes (since there's no standard way to add a field to a form
after construction).
use HTML::FormHandler::Field::Text;
my $field = HTML::FormHandler::Field::Text->new( name => $name, ... );
In your custom field class:
package MyApp::Field::MyText;
use HTML::FormHandler::Moose;
extends 'HTML::FormHandler::Field::Text';
has 'my_attribute' => ( isa => 'Str', is => 'rw' );
apply [ { transform => sub { ... } },
{ check => ['fighter', 'bard', 'mage' ], message => '....' }
];
1;
=head1 DESCRIPTION
This is the base class for form fields. The 'type' of a field class
is used in the FormHandler field_list or has_field to identify which field class to
load from the 'field_name_space' (or directly, when prefixed with '+').
If the type is not specified, it defaults to Text.
See L<HTML::FormHandler::Manual::Fields> for a list of the fields and brief
descriptions of their structure.
=head1 ATTRIBUTES
=head2 Names, types, accessor
=over
=item name
The name of the field. Used in the HTML form. Often a db accessor.
The only required attribute.
=item type
The class or type of the field. The 'type' of L<HTML::FormHandler::Field::Money>
is 'Money'. Classes that you define yourself are prefixed with '+'.
=item accessor
If the name of your field is different than your database accessor, use
this attribute to provide the accessor.
=item full_name
The name of the field with all parents:
'event.start_date.month'
=item full_accessor
The field accessor with all parents.
=item html_name
The full_name plus the form name if 'html_prefix' is set.
=item input_param
By default we expect an input parameter based on the field name. This allows
you to look for a different input parameter.
=back
=head2 Field data
=over
=item inactive, is_inactive, is_active
Set the 'inactive' attribute to 1 if this field is inactive. The 'inactive' attribute
that isn't set or is set to 0 will make a field 'active'.
This provides a way to define fields in the form and selectively set them to inactive.
There is also an '_active' attribute, for internal use to indicate that the field has
been activated/inactivated on 'process' by the form's 'active'/'inactive' attributes.
You can use the is_inactive and is_active methods to check whether this particular
field is active.
if( $form->field('foo')->is_active ) { ... }
=item input
The input string from the parameters passed in.
=item value
The value as it would come from or go into the database, after being
acted on by inflations/deflations and transforms. Used to construct the
C<< $form->values >> hash. Validation and constraints act on 'value'.
See also L<HTML::FormHandler::Manual::InflationDeflation>.
=item fif
Values used to fill in the form. Read only. Use a deflation to get
from 'value' to 'fif' if an inflator was used. Use 'fif_from_value'
attribute if you want to use the field 'value' to fill in the form.
[% form.field('title').fif %]
=item init_value
Initial value populated by init_from_object. You can tell if a field
has changed by comparing 'init_value' and 'value'. Read only.
=item input_without_param
Input for this field if there is no param. Set by default for Checkbox,
and Select, since an unchecked checkbox or unselected pulldown
does not return a parameter.
=back
=head2 Form, parent
=over
=item form
A reference to the containing form.
=item parent
A reference to the parent of this field. Compound fields are the
parents for the fields they contain.
=back
=head2 Errors
=over
=item errors
Returns the error list for the field. Also provides 'num_errors',
'has_errors', 'push_errors' and 'clear_errors' from Array
trait. Use 'add_error' to add an error to the array if you
want to use a MakeText language handle. Default is an empty list.
=item add_error
Add an error to the list of errors. Error message will be localized
using '_localize' method.
See also L<HTML::FormHandler::TraitFor::I18N>.
return $field->add_error( 'bad data' ) if $bad;
=item error_fields
Compound fields will have an array of errors from the subfields.
=item localize_meth
Set the method used to localize.
=back
=head2 Attributes for creating HTML
The 'element_attr' hashref attribute can be used to set
arbitrary HTML attributes on a field's input tag.
has_field 'foo' => ( element_attr => { readonly => 1, my_attr => 'abc' } );
Note that the 'id' and 'type' attributes are not set using element_attr. Use
the field's 'id' attribute (or 'build_id_method') to set the id.
The 'label_attr' hashref is for label attributes, and the 'wrapper_attr'
is for attributes on the wrapping element (a 'div' for the standard 'simple'
wrapper).
A 'javascript' key in one of the '_attr' hashes will be inserted into the
element as-is.
The following are used in rendering HTML, but are handled specially.
label - Text label for this field. Defaults to ucfirst field name.
build_label_method - coderef for constructing the label
wrap_label_method - coderef for constructing a wrapped label
id - Useful for javascript (default is html_name. to prefix with
form name, use 'html_prefix' in your form)
build_id_method - coderef for constructing the id
render_filter - Coderef for filtering fields before rendering. By default
changes >, <, &, " to the html entities
disabled - Boolean to set field disabled
The order attribute may be used to set the order in which fields are rendered.
order - Used for sorting errors and fields. Built automatically,
but may also be explicitly set
The following are discouraged. Use 'element_attr', 'label_attr', and 'wrapper_attr'
instead.
title - instead use element_attr => { title => '...' }
style - instead use element_attr => { style => '...' }
tabindex - instead use element_attr => { tabindex => 1 }
readonly - instead use element_attr => { readonly => 'readonly' }
Rendering of the various HTML attributes is done by calling the 'process_attrs'
function (from HTML::FormHandler::Render::Util) and passing in a method that
adds in error classes, provides backward compatibility with the deprecated
attributes, etc.
attribute hashref class attribute wrapping method
================= ================= ================
element_attr element_class element_attributes
label_attr label_class label_attributes
wrapper_attr wrapper_class wrapper_attributes
element_wrapper_class element_wrapper_attributes
('element_wrapper' is for an inner div around the input element, not
including the label. Used for Bootstrap3 rendering, but also available
in the Simple wrapper.)
The slots for the class attributes are arrayrefs; they will coerce a
string into an arrayref.
In addition, these 'wrapping methods' call a hook method in the form class,
'html_attributes', which you can use to customize and localize the various
attributes. (Field types: 'element', 'wrapper', 'label')
sub html_attributes {
my ( $self, $field, $type, $attr ) = @_;
$attr->{class} = 'label' if $type eq 'label';
return $attr;
}
The 'process_attrs' function will also handle an array of strings, such as for the
'class' attribute.
=head2 tags
A hashref containing flags and strings for use in the rendering code.
The value of a tag can be a string, a coderef (accessed as a method on the
field) or a block specified with a percent followed by the blockname
('%blockname').
Retrieve a tag with 'get_tag'. It returns a '' if the tag doesn't exist.
This attribute used to be named 'widget_tags', which is deprecated.
=head2 html5_type_attr [string]
This string is used when rendering an input element as the value for the type attribute.
It is used when the form has the is_html5 flag on.
=head2 widget
The 'widget' attribute is used in rendering, so if you are
not using FormHandler's rendering facility, you don't need this
attribute. It is used in generating HTML, in templates and the
rendering roles. Fields of different type can use the same widget.
This attribute is set in the field classes, or in the fields
defined in the form. If you want a new widget type, create a
widget role, such as MyApp::Form::Widget::Field::MyWidget. Provide
the name space in the 'widget_name_space' attribute, and set
the 'widget' of your field to the package name after the
Field/Form/Wrapper:
has_field 'my_field' => ( widget => 'MyWidget' );
If you are using a template based rendering system you will want
to create a widget template.
(see L<HTML::FormHandler::Manual::Templates>)
Widget types for some of the provided field classes:
Widget : Field classes
-----------------------:---------------------------------
Text : Text, Integer
Checkbox : Checkbox, Boolean
RadioGroup : Select, Multiple, IntRange (etc)
Select : Select, Multiple, IntRange (etc)
CheckboxGroup : Multiple select
TextArea : TextArea
Compound : Compound, Repeatable, DateTime
Password : Password
Hidden : Hidden
Submit : Submit
Reset : Reset
NoRender :
Upload : Upload
Widget roles are automatically applied to field classes
unless they already have a 'render' method, and if the
'no_widgets' flag in the form is not set.
You can create your own widget roles and specify the namespace
in 'widget_name_space'. In the form:
has '+widget_name_space' => ( default => sub { ['MyApp::Widget'] } );
If you want to use a fully specified role name for a widget, you
can prefix it with a '+':
widget => '+MyApp::Widget::SomeWidget'
For more about widgets, see L<HTML::FormHandler::Manual::Rendering>.
=head2 Flags
password - prevents the entered value from being displayed in the form
writeonly - The initial value is not taken from the database
noupdate - Do not update this field in the database (does not appear in $form->value)
=head2 Defaults
See also the documentation on L<HTML::FormHandler::Manual::Intro/Defaults>.
=over
=item default_method, set_default
Supply a coderef (which will be a method on the field) with 'default_method'
or the name of a form method with 'set_default' (which will be a method on
the form). If not specified and a form method with a name of
C<< default_<field_name> >> exists, it will be used.
=item default
Provide an initial value just like the 'set_default' method, except in the field
declaration:
has_field 'bax' => ( default => 'Default bax' );
FormHandler has flipped back and forth a couple of times about whether a default
specified in the has_field definition should override values provided in an
initial item or init_object. Sometimes people want one behavior, and sometimes
the other. Now 'default' does *not* override.
If you pass in a model object with C<< item => $row >> or an initial object
with C<< init_object => {....} >> the values in that object will be used instead
of values provided in the field definition with 'default' or 'default_fieldname'.
If you want defaults that override or supplement the item/init_object, you can use the form
flags 'use_defaults_over_obj', 'use_init_obj_over_item', and
'use_init_obj_when_no_accessor_in_item'.
You could also put your defaults into your row or init_object instead.
=item default_over_obj
This is deprecated; look into using 'use_defaults_over_obj' or 'use_init_obj_over_item'
flags instead. They allow using the standard 'default' attribute.
Allows setting defaults which will override values provided with an item/init_object.
(And only those. Will not be used for defaults without an item/init_object.)
has_field 'quux' => ( default_over_obj => 'default quux' );
At this time there is no equivalent of 'set_default', but the type of the attribute
is not defined so you can provide default values in a variety of other ways,
including providing a trait which does 'build_default_over_obj'. For examples,
see tests in the distribution.
=back
=head1 Constraints and Validations
See also L<HTML::FormHandler::Manual::Validation>.
=head2 Constraints set in attributes
=over
=item required
Flag indicating whether this field must have a value
=item unique
For DB field - check for uniqueness. Action is performed by
the DB model.
=item messages
messages => { required => '...', unique => '...' }
Set messages created by FormHandler by setting in the 'messages'
hashref. Some field subclasses have additional settable messages.
required: Error message text added to errors if required field is not present.
The default is "Field <field label> is required".
=item range_start
=item range_end
Field values are validated against the specified range if one
or both of range_start and range_end are set and the field
does not have 'options'.
The IntRange field uses this range to create a select list
with a range of integers.
In a FormHandler field_list:
age => {
type => 'Integer',
range_start => 18,
range_end => 120,
}
=item not_nullable
Fields that contain 'empty' values such as '' are changed to undef in the validation process.
If this flag is set, the value is not changed to undef. If your database column requires
an empty string instead of a null value (such as a NOT NULL column), set this attribute.
has_field 'description' => (
type => 'TextArea',
not_nullable => 1,
);
This attribute is also used when you want an empty array to stay an empty array and not
be set to undef.
It's also used when you have a compound field and you want the 'value' returned
to contain subfields with undef, instead of the whole field to be undef.
=back
=head2 apply
Use the 'apply' keyword to specify an ArrayRef of constraints and coercions to
be executed on the field at validate_field time.
has_field 'test' => (
apply => [ 'MooseType',
{ check => sub {...}, message => { } },
{ transform => sub { ... lc(shift) ... } }
],
);
See more documentation in L<HTML::FormHandler::Manual::Validation>.
=head2 trim
An action to trim the field. By default
this contains a transform to strip beginning and trailing spaces.
Set this attribute to null to skip trimming, or supply a different
transform.
trim => { transform => sub {
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
} }
trim => { type => MyTypeConstraint }
Trimming is performed before any other defined actions.
=head2 Inflation/deflation
There are a number of methods to provide finely tuned inflation and deflation:
=over 4
=item inflate_method
Inflate to a data format desired for validation.
=item deflate_method
Deflate to a string format for presenting in HTML.
=item inflate_default_method
Modify the 'default' provided by an 'item' or 'init_object'.
=item deflate_value_method
Modify the value returned by C<< $form->value >>.
=item deflation
Another way of providing a deflation method.
=item transform
Another way of providing an inflation method.
=back
Normally if you have a deflation, you will need a matching inflation.
There are two different flavors of inflation/deflation: one for inflating values
to a format needed for validation and deflating for output, the other for
inflating the initial provided values (usually from a database row) and deflating
them for the 'values' returned.
See L<HTML::FormHandler::Manual::InflationDeflation>.
=head1 Processing and validating the field
=head2 validate_field
This is the base class validation routine. Most users will not
do anything with this. It might be useful for method modifiers,
if you want code that executed before or after the validation
process.
=head2 validate
This field method can be used in addition to or instead of 'apply' actions
in custom field classes.
It should validate the field data and set error messages on
errors with C<< $field->add_error >>.
sub validate {
my $field = shift;
my $value = $field->value;
return $field->add_error( ... ) if ( ... );
}
=head2 validate_method, set_validate
Supply a coderef (which will be a method on the field) with 'validate_method'
or the name of a form method with 'set_validate' (which will be a method on
the form). If not specified and a form method with a name of
C<< validate_<field_name> >> exists, it will be used.
Periods in field names will be replaced by underscores, so that the field
'addresses.city' will use the 'validate_addresses_city' method for validation.
has_field 'my_foo' => ( validate_method => \&my_foo_validation );
sub my_foo_validation { ... }
has_field 'title' => ( isa => 'Str', set_validate => 'check_title' );
=cut
has 'name' => ( isa => 'Str', is => 'rw', required => 1 );
has 'type' => ( isa => 'Str', is => 'rw', default => sub { ref shift } );
has 'parent' => ( is => 'rw', predicate => 'has_parent', weak_ref => 1 );
sub has_fields { }
has 'input_without_param' => (
is => 'rw',
predicate => 'has_input_without_param'
);
has 'not_nullable' => ( is => 'rw', isa => 'Bool' );
has 'no_value_if_empty' => ( is => 'rw', isa => 'Bool' );
has 'validate_when_empty' => ( is => 'rw', isa => 'Bool' );
has 'init_value' => ( is => 'rw', clearer => 'clear_init_value', predicate => 'has_init_value' );
has 'default' => ( is => 'rw' );
has 'default_over_obj' => ( is => 'rw', builder => 'build_default_over_obj' );
sub build_default_over_obj { }
has 'result' => (
isa => 'HTML::FormHandler::Field::Result',
is => 'ro',
weak_ref => 1,
clearer => 'clear_result',
predicate => 'has_result',
writer => '_set_result',
handles => [
'_set_input', '_clear_input', '_set_value', '_clear_value',
'errors', 'all_errors', '_push_errors', 'num_errors', 'has_errors',
'clear_errors', 'validated', 'add_warning', 'all_warnings', 'num_warnings',
'has_warnings', 'warnings', 'missing',
],
);
has '_pin_result' => ( is => 'ro', reader => '_get_pin_result', writer => '_set_pin_result' );
sub has_input {
my $self = shift;
return unless $self->has_result;
return $self->result->has_input;
}
sub has_value {
my $self = shift;
return unless $self->has_result;
return $self->result->has_value;
}
# these should normally only be called for field tests
sub reset_result {
my $self = shift;
$self->clear_result;
$self->build_result;
}
sub build_result {
my $self = shift;
my @parent = ( 'parent' => $self->parent->result )
if ( $self->parent && $self->parent->result );
my $result = HTML::FormHandler::Field::Result->new(
name => $self->name,
field_def => $self,
@parent
);
$self->_set_pin_result($result); # to prevent garbage collection of result
$self->_set_result($result);
}
sub input {
my $self = shift;
# allow testing fields individually by creating result if no form
return undef unless $self->has_result || !$self->form;
my $result = $self->result;
return $result->_set_input(@_) if @_;
return $result->input;
}
sub value {
my $self = shift;
# allow testing fields individually by creating result if no form
return undef unless $self->has_result || !$self->form;
my $result = $self->result;
return undef unless $result;
return $result->_set_value(@_) if @_;
return $result->value;
}
# for compatibility. deprecate and remove at some point
sub clear_input { shift->_clear_input }
sub clear_value { shift->_clear_value }
sub clear_data {
my $self = shift;
$self->clear_result;
$self->clear_active;
}
# this is a kludge to allow testing field deflation
sub _deflate_and_set_value {
my ( $self, $value ) = @_;
if( $self->_can_deflate ) {
$value = $self->_apply_deflation($value);
}
$self->_set_value($value);
}
sub is_repeatable { }
has 'fif_from_value' => ( isa => 'Str', is => 'ro' );
sub fif {
my ( $self, $result ) = @_;
return if ( $self->inactive && !$self->_active );
return '' if $self->password;
return unless $result || $self->has_result;
my $lresult = $result || $self->result;
if ( ( $self->has_result && $self->has_input && !$self->fif_from_value ) ||
( $self->fif_from_value && !defined $lresult->value ) )
{
return defined $lresult->input ? $lresult->input : '';
}
if ( $lresult->has_value ) {
my $value;
if( $self->_can_deflate ) {
$value = $self->_apply_deflation($lresult->value);
}
else {
$value = $lresult->value;
}
return ( defined $value ? $value : '' );
}
elsif ( defined $self->value ) {
# this is because checkboxes and submit buttons have their own 'value'
# needs to be fixed in some better way
return $self->value;
}
return '';
}
has 'accessor' => (
isa => 'Str',
is => 'rw',
lazy => 1,
default => sub {
my $self = shift;
my $accessor = $self->name;
$accessor =~ s/^(.*)\.//g if ( $accessor =~ /\./ );
return $accessor;
}
);
has 'is_contains' => ( is => 'rw', isa => 'Bool' );
has 'temp' => ( is => 'rw' );
sub has_flag {
my ( $self, $flag_name ) = @_;
return unless $self->can($flag_name);
return $self->$flag_name;
}
has 'label' => (
isa => 'Maybe[Str]',
is => 'rw',
lazy => 1,
builder => 'build_label',
);
has 'do_label' => ( isa => 'Bool', is => 'rw', default => 1 );
has 'build_label_method' => ( is => 'rw', isa => 'CodeRef',
traits => ['Code'], handles => { 'build_label' => 'execute_method' },
default => sub { \&default_build_label },
);
sub default_build_label {
my $self = shift;
my $label = $self->name;
$label =~ s/_/ /g;
$label = ucfirst($label);
return $label;
}
sub loc_label {
my $self = shift;
return $self->_localize($self->label);
}
has 'wrap_label_method' => (
traits => ['Code'],
is => 'ro',
isa => 'CodeRef',
predicate => 'does_wrap_label',
handles => { 'wrap_label' => 'execute_method' },
);
has 'title' => ( isa => 'Str', is => 'rw' );
has 'style' => ( isa => 'Str', is => 'rw' );
has 'form' => (
isa => 'HTML::FormHandler',
is => 'rw',
weak_ref => 1,
predicate => 'has_form',
);
sub is_form { 0 }
has 'html_name' => (
isa => 'Str',
is => 'rw',
lazy => 1,
builder => 'build_html_name'
);
sub build_html_name {
my $self = shift;
my $prefix = ( $self->form && $self->form->html_prefix ) ? $self->form->name . "." : '';
return $prefix . $self->full_name;
}
has 'widget' => ( isa => 'Str', is => 'rw' );
has 'widget_wrapper' => ( isa => 'Str', is => 'rw' );
has 'do_wrapper' => ( is => 'rw', default => 1 );
sub wrapper { shift->widget_wrapper || '' }
sub uwrapper { ucc_widget( shift->widget_wrapper || '' ) || 'simple' }
sub twrapper { shift->uwrapper . ".tt" }
sub uwidget { ucc_widget( shift->widget || '' ) || 'simple' }
sub twidget { shift->uwidget . ".tt" }
# for use of wrapper classes
has 'wrapper_tags' => (
isa => 'HashRef',
traits => ['Hash'],
is => 'rw',
builder => 'build_wrapper_tags',
handles => {
has_wrapper_tags => 'count'
}
);
sub build_wrapper_tags { {} }
has 'tags' => (
traits => ['Hash'],
isa => 'HashRef',
is => 'rw',
builder => 'build_tags',
handles => {
_get_tag => 'get',
set_tag => 'set',
has_tag => 'exists',
tag_exists => 'exists',
delete_tag => 'delete',
},
);
sub build_tags {{}}
sub merge_tags {
my ( $self, $new ) = @_;
my $old = $self->tags;
$self->tags( merge($new, $old) );
}
sub get_tag {
my ( $self, $name ) = @_;
return '' unless $self->tag_exists($name);
my $tag = $self->_get_tag($name);
return $self->$tag if ref $tag eq 'CODE';
return $tag unless $tag =~ /^%/;
( my $block_name = $tag ) =~ s/^%//;
return $self->form->block($block_name)->render
if ( $self->form && $self->form->block_exists($block_name) );
return '';
}
has 'widget_name_space' => (
isa => 'HFH::ArrayRefStr',
is => 'rw',
traits => ['Array'],
default => sub {[]},
coerce => 1,
handles => {
push_widget_name_space => 'push',
},
);
sub add_widget_name_space {
my ( $self, @ns ) = @_;
@ns = @{$ns[0]}if( scalar @ns && ref $ns[0] eq 'ARRAY' );
$self->push_widget_name_space(@ns);
}
has 'order' => ( isa => 'Int', is => 'rw', default => 0 );
# 'inactive' is set in the field declaration, and is static. Default status.
has 'inactive' => ( isa => 'Bool', is => 'rw', clearer => 'clear_inactive' );
# 'active' is cleared whenever the form is cleared. Ephemeral activation.
has '_active' => ( isa => 'Bool', is => 'rw', clearer => 'clear_active', predicate => 'has__active' );
sub is_active {
my $self = shift;
return ! $self->is_inactive;
}
sub is_inactive {
my $self = shift;
return (($self->inactive && !$self->_active) || (!$self->inactive && $self->has__active && $self->_active == 0 ) );
}
has 'id' => ( isa => 'Str', is => 'rw', lazy => 1, builder => 'build_id' );
has 'build_id_method' => ( is => 'rw', isa => 'CodeRef', traits => ['Code'],
default => sub { sub { shift->html_name } },
handles => { build_id => 'execute_method' },
);
# html attributes
has 'password' => ( isa => 'Bool', is => 'rw' );
has 'disabled' => ( isa => 'Bool', is => 'rw' );
has 'readonly' => ( isa => 'Bool', is => 'rw' );
has 'tabindex' => ( is => 'rw', isa => 'Int' );
sub html_element { 'input' }
has 'type_attr' => ( is => 'rw', isa => 'Str', default => 'text' );
has 'html5_type_attr' => ( isa => 'Str', is => 'ro', default => 'text' );
sub input_type {
my $self = shift;
return $self->html5_type_attr if ( $self->form && $self->form->has_flag('is_html5') );
return $self->type_attr;
}
# temporary methods for compatibility after name change
sub html_attr { shift->element_attr(@_) }
sub has_html_attr { shift->has_element_attr(@_) }
sub get_html_attr { shift->get_element_attr(@_) }
sub set_html_attr { shift->set_element_attr(@_) }
{
# create the attributes and methods for
# element_attr, build_element_attr, element_class,
# label_attr, build_label_attr, label_class,
# wrapper_attr, build_wrapper_atrr, wrapper_class
no strict 'refs';
foreach my $attr ('wrapper', 'element', 'label' ) {
# trigger to move 'class' set via _attr to the class slot
my $add_meth = "add_${attr}_class";
my $trigger_sub = sub {
my ( $self, $value ) = @_;
if( my $class = delete $self->{"${attr}_attr"}->{class} ) {
$self->$add_meth($class);
}
};
has "${attr}_attr" => ( is => 'rw', traits => ['Hash'],
builder => "build_${attr}_attr",
handles => {
"has_${attr}_attr" => 'count',
"get_${attr}_attr" => 'get',
"set_${attr}_attr" => 'set',
"delete_${attr}_attr" => 'delete',
"exists_${attr}_attr" => 'exists',
},
trigger => $trigger_sub,
);
# create builders fo _attrs
my $attr_builder = __PACKAGE__ . "::build_${attr}_attr";
*$attr_builder = subname $attr_builder, sub {{}};
# create the 'class' slots
has "${attr}_class" => ( is => 'rw', isa => 'HFH::ArrayRefStr',
traits => ['Array'],
coerce => 1,
builder => "build_${attr}_class",
handles => {
"has_${attr}_class" => 'count',
"_add_${attr}_class" => 'push',
},
);
# create builders for classes
my $class_builder = __PACKAGE__ . "::build_${attr}_class";
*$class_builder = subname $class_builder, sub {[]};
# create wrapper for add_to_ to accept arrayref
my $add_to_class = __PACKAGE__ . "::add_${attr}_class";
my $_add_meth = __PACKAGE__ . "::_add_${attr}_class";
*$add_to_class = subname $add_to_class, sub { shift->$_add_meth((ref $_[0] eq 'ARRAY' ? @{$_[0]} : @_)); }
}
}
# we're assuming that the only attribute we want in an element wrapper is a class
has 'element_wrapper_class' => (
is => 'rw', isa => 'HFH::ArrayRefStr',
traits => ['Array'],
coerce => 1,
builder => "build_element_wrapper_class",
handles => {
has_element_wrapper_class => 'count',
_add_element_wrapper_class => 'push',
},
);
sub add_element_wrapper_class { shift->_add_element_wrapper_class((ref $_[0] eq 'ARRAY' ? @{$_[0]} : @_)); }
sub build_element_wrapper_class { [] }
sub element_wrapper_attributes {
my ( $self, $result ) = @_;
$result ||= $self->result;
# local copy of label_attr
my $attr = {};
my $class = [@{$self->element_wrapper_class}];
$self->add_standard_element_wrapper_classes( $result, $class );
$attr->{class} = $class if @$class;
# call form hook
my $mod_attr = $self->form->html_attributes($self, 'element_wrapper', $attr, $result) if $self->form;
return ref($mod_attr) eq 'HASH' ? $mod_attr : $attr;
}
sub add_standard_element_wrapper_classes {
my ( $self, $result, $class ) = @_;
}
sub attributes { shift->element_attributes(@_) }
sub element_attributes {
my ( $self, $result ) = @_;
$result ||= $self->result;
my $attr = {};
# handle html5 attributes
if ($self->form && $self->form->has_flag('is_html5')) {
$attr->{required} = 'required' if $self->required;
$attr->{min} = $self->range_start if defined $self->range_start;
$attr->{max} = $self->range_end if defined $self->range_end;
}
# pull in deprecated attributes for backward compatibility
for my $dep_attr ( 'readonly', 'disabled' ) {
$attr->{$dep_attr} = $dep_attr if $self->$dep_attr;
}
for my $dep_attr ( 'style', 'title', 'tabindex' ) {
$attr->{$dep_attr} = $self->$dep_attr if defined $self->$dep_attr;
}
$attr = {%$attr, %{$self->element_attr}};
my $class = [@{$self->element_class}];
$self->add_standard_element_classes($result, $class);
$attr->{class} = $class if @$class;
# call form hook
my $mod_attr = $self->form->html_attributes($self, 'element', $attr, $result) if $self->form;
return ref($mod_attr) eq 'HASH' ? $mod_attr : $attr;
}
sub add_standard_element_classes {
my ( $self, $result, $class ) = @_;
push @$class, 'error' if $result->has_errors;
push @$class, 'warning' if $result->has_warnings;
push @$class, 'disabled' if $self->disabled;
}
sub label_attributes {
my ( $self, $result ) = @_;
$result ||= $self->result;
# local copy of label_attr
my $attr = {%{$self->label_attr}};
my $class = [@{$self->label_class}];
$self->add_standard_label_classes($result, $class);
$attr->{class} = $class if @$class;
# call form hook
my $mod_attr = $self->form->html_attributes($self, 'label', $attr, $result) if $self->form;
return ref($mod_attr) eq 'HASH' ? $mod_attr : $attr;
}
sub add_standard_label_classes {
my ( $self, $result, $class ) = @_;
}