Debian Codegraph @

lib/HTML/FormHandler/Field.pm

raw
1 package HTML::FormHandler::Field;
2 # ABSTRACT: base class for fields
3 $HTML::FormHandler::Field::VERSION = '0.410002';
4 use HTML::FormHandler::Moose;
5 use HTML::FormHandler::Field::Result;
6 use Try::Tiny;
7 use Moose::Util::TypeConstraints;
8 use HTML::FormHandler::Merge ('merge');
9 use HTML::FormHandler::Render::Util('cc_widget', 'ucc_widget');
10 use Sub::Name;
11
12 with 'HTML::FormHandler::Traits';
13 with 'HTML::FormHandler::Validate';
14 with 'HTML::FormHandler::Widget::ApplyRole';
15 with 'HTML::FormHandler::TraitFor::Types';
16
17
18 has 'name' => ( isa => 'Str', is => 'rw', required => 1 );
19 has 'type' => ( isa => 'Str', is => 'rw', default => sub { ref shift } );
20 has 'parent' => ( is => 'rw', predicate => 'has_parent', weak_ref => 1 );
21 sub has_fields { }
22 has 'input_without_param' => (
23 is => 'rw',
24 predicate => 'has_input_without_param'
25 );
26 has 'not_nullable' => ( is => 'rw', isa => 'Bool' );
27 has 'no_value_if_empty' => ( is => 'rw', isa => 'Bool' );
28 has 'validate_when_empty' => ( is => 'rw', isa => 'Bool' );
29 has 'init_value' => ( is => 'rw', clearer => 'clear_init_value', predicate => 'has_init_value' );
30 has 'default' => ( is => 'rw' );
31 has 'default_over_obj' => ( is => 'rw', builder => 'build_default_over_obj' );
32 sub build_default_over_obj { }
33 has 'result' => (
34 isa => 'HTML::FormHandler::Field::Result',
35 is => 'ro',
36 weak_ref => 1,
37 clearer => 'clear_result',
38 predicate => 'has_result', # warning: will still return true if value has been garbage-collected
39 writer => '_set_result',
40 handles => [
41 '_set_input', '_clear_input', '_set_value', '_clear_value',
42 'errors', 'all_errors', '_push_errors', 'num_errors', 'has_errors',
43 'clear_errors', 'validated', 'add_warning', 'all_warnings', 'num_warnings',
44 'has_warnings', 'warnings', 'missing',
45 ],
46 );
47 has '_pin_result' => ( is => 'ro', reader => '_get_pin_result', writer => '_set_pin_result' );
48
49 sub has_input {
50 my $self = shift;
51 return unless $self->has_result and $self->result;
52 return $self->result->has_input;
53 }
54
55 sub has_value {
56 my $self = shift;
57 return unless $self->has_result and $self->result;
58 return $self->result->has_value;
59 }
60
61 # these should normally only be called for field tests
62 sub reset_result {
63 my $self = shift;
64 $self->clear_result;
65 $self->build_result;
66 }
67 sub build_result {
68 my $self = shift;
69 my @parent;
70 @parent = ( 'parent' => $self->parent->result )
71 if ( $self->parent && $self->parent->result );
72 my $result = HTML::FormHandler::Field::Result->new(
73 name => $self->name,
74 field_def => $self,
75 @parent
76 );
77 $self->_set_pin_result($result); # to prevent garbage collection of result
78 $self->_set_result($result);
79 }
80
81 sub input {
82 my $self = shift;
83
84 # allow testing fields individually by creating result if no form
85 return undef unless $self->has_result || !$self->form;
86 my $result = $self->result;
87 return undef unless $result;
88 return $result->_set_input(@_) if @_;
89 return $result->input;
90 }
91
92 sub value {
93 my $self = shift;
94
95 # allow testing fields individually by creating result if no form
96 return undef unless $self->has_result || !$self->form;
97 my $result = $self->result;
98 return undef unless $result;
99 return $result->_set_value(@_) if @_;
100 return $result->value;
101 }
102 # for compatibility. deprecate and remove at some point
103 sub clear_input { shift->_clear_input }
104 sub clear_value { shift->_clear_value }
105 sub clear_data {
106 my $self = shift;
107 $self->clear_result;
108 $self->clear_active;
109 }
110 # this is a kludge to allow testing field deflation
111 sub _deflate_and_set_value {
112 my ( $self, $value ) = @_;
113 if( $self->_can_deflate ) {
114 $value = $self->_apply_deflation($value);
115 }
116 $self->_set_value($value);
117 }
118
119 sub is_repeatable { }
120
121 has 'fif_from_value' => ( isa => 'Str', is => 'ro' );
122
123 sub fif {
124 my ( $self, $result ) = @_;
125
126 return if ( $self->inactive && !$self->_active );
127 return '' if $self->password;
128 return unless $result || $self->has_result;
129 my $lresult = $result || $self->result;
130 return unless $lresult;
131 if ( ( $self->has_result && $self->has_input && !$self->fif_from_value ) ||
132 ( $self->fif_from_value && !defined $lresult->value ) )
133 {
134 return defined $lresult->input ? $lresult->input : '';
135 }
136 if ( $lresult->has_value ) {
137 my $value;
138 if( $self->_can_deflate ) {
139 $value = $self->_apply_deflation($lresult->value);
140 }
141 else {
142 $value = $lresult->value;
143 }
144 return ( defined $value ? $value : '' );
145 }
146 elsif ( defined $self->value ) {
147 # this is because checkboxes and submit buttons have their own 'value'
148 # needs to be fixed in some better way
149 return $self->value;
150 }
151 return '';
152 }
153
154 has 'accessor' => (
155 isa => 'Str',
156 is => 'rw',
157 lazy => 1,
158 default => sub {
159 my $self = shift;
160 my $accessor = $self->name;
161 $accessor =~ s/^(.*)\.//g if ( $accessor =~ /\./ );
162 return $accessor;
163 }
164 );
165 has 'is_contains' => ( is => 'rw', isa => 'Bool' );
166 has 'temp' => ( is => 'rw' );
167
168 sub has_flag {
169 my ( $self, $flag_name ) = @_;
170 return unless $self->can($flag_name);
171 return $self->$flag_name;
172 }
173
174 has 'label' => (
175 isa => 'Maybe[Str]',
176 is => 'rw',
177 lazy => 1,
178 builder => 'build_label',
179 );
180 has 'do_label' => ( isa => 'Bool', is => 'rw', default => 1 );
181 has 'build_label_method' => ( is => 'rw', isa => 'CodeRef',
182 traits => ['Code'], handles => { 'build_label' => 'execute_method' },
183 default => sub { \&default_build_label },
184 );
185 sub default_build_label {
186 my $self = shift;
187 my $label = $self->name;
188 $label =~ s/_/ /g;
189 $label = ucfirst($label);
190 return $label;
191 }
192 sub loc_label {
193 my $self = shift;
194 return $self->_localize($self->label);
195 }
196 has 'wrap_label_method' => (
197 traits => ['Code'],
198 is => 'ro',
199 isa => 'CodeRef',
200 predicate => 'does_wrap_label',
201 handles => { 'wrap_label' => 'execute_method' },
202 );
203 has 'title' => ( isa => 'Str', is => 'rw' );
204 has 'style' => ( isa => 'Str', is => 'rw' );
205 has 'form' => (
206 isa => 'HTML::FormHandler',
207 is => 'rw',
208 weak_ref => 1,
209 predicate => 'has_form',
210 );
211 sub is_form { 0 }
212 has 'html_name' => (
213 isa => 'Str',
214 is => 'rw',
215 lazy => 1,
216 builder => 'build_html_name'
217 );
218
219 sub build_html_name {
220 my $self = shift;
221 my $prefix = ( $self->form && $self->form->html_prefix ) ? $self->form->name . "." : '';
222 return $prefix . $self->full_name;
223 }
224 has 'widget' => ( isa => 'Str', is => 'rw' );
225 has 'widget_wrapper' => ( isa => 'Str', is => 'rw' );
226 has 'do_wrapper' => ( is => 'rw', default => 1 );
227 sub wrapper { shift->widget_wrapper || '' }
228 sub uwrapper { ucc_widget( shift->widget_wrapper || '' ) || 'simple' }
229 sub twrapper { shift->uwrapper . ".tt" }
230 sub uwidget { ucc_widget( shift->widget || '' ) || 'simple' }
231 sub twidget { shift->uwidget . ".tt" }
232 # for use of wrapper classes
233 has 'wrapper_tags' => (
234 isa => 'HashRef',
235 traits => ['Hash'],
236 is => 'rw',
237 builder => 'build_wrapper_tags',
238 handles => {
239 has_wrapper_tags => 'count'
240 }
241 );
242 sub build_wrapper_tags { {} }
243 has 'tags' => (
244 traits => ['Hash'],
245 isa => 'HashRef',
246 is => 'rw',
247 builder => 'build_tags',
248 handles => {
249 _get_tag => 'get',
250 set_tag => 'set',
251 has_tag => 'exists',
252 tag_exists => 'exists',
253 delete_tag => 'delete',
254 },
255 );
256 sub build_tags {{}}
257 sub merge_tags {
258 my ( $self, $new ) = @_;
259 my $old = $self->tags;
260 $self->tags( merge($new, $old) );
261 }
262 sub get_tag {
263 my ( $self, $name ) = @_;
264 return '' unless $self->tag_exists($name);
265 my $tag = $self->_get_tag($name);
266 return $self->$tag if ref $tag eq 'CODE';
267 return $tag unless $tag =~ /^%/;
268 ( my $block_name = $tag ) =~ s/^%//;
269 return $self->form->block($block_name)->render
270 if ( $self->form && $self->form->block_exists($block_name) );
271 return '';
272 }
273
274 has 'widget_name_space' => (
275 isa => 'HFH::ArrayRefStr',
276 is => 'rw',
277 traits => ['Array'],
278 default => sub {[]},
279 coerce => 1,
280 handles => {
281 push_widget_name_space => 'push',
282 },
283 );
284
285 sub add_widget_name_space {
286 my ( $self, @ns ) = @_;
287 @ns = @{$ns[0]}if( scalar @ns && ref $ns[0] eq 'ARRAY' );
288 $self->push_widget_name_space(@ns);
289 }
290
291 has 'order' => ( isa => 'Int', is => 'rw', default => 0 );
292 # 'inactive' is set in the field declaration, and is static. Default status.
293 has 'inactive' => ( isa => 'Bool', is => 'rw', clearer => 'clear_inactive' );
294 # 'active' is cleared whenever the form is cleared. Ephemeral activation.
295 has '_active' => ( isa => 'Bool', is => 'rw', clearer => 'clear_active', predicate => 'has__active' );
296 sub is_active {
297 my $self = shift;
298 return ! $self->is_inactive;
299 }
300 sub is_inactive {
301 my $self = shift;
302 return (($self->inactive && !$self->_active) || (!$self->inactive && $self->has__active && $self->_active == 0 ) );
303 }
304 has 'id' => ( isa => 'Str', is => 'rw', lazy => 1, builder => 'build_id' );
305 has 'build_id_method' => ( is => 'rw', isa => 'CodeRef', traits => ['Code'],
306 default => sub { sub { shift->html_name } },
307 handles => { build_id => 'execute_method' },
308 );
309
310 # html attributes
311 has 'password' => ( isa => 'Bool', is => 'rw' );
312 has 'disabled' => ( isa => 'Bool', is => 'rw' );
313 has 'readonly' => ( isa => 'Bool', is => 'rw' );
314 has 'tabindex' => ( is => 'rw', isa => 'Int' );
315
316 sub html_element { 'input' }
317 has 'type_attr' => ( is => 'rw', isa => 'Str', default => 'text' );
318 has 'html5_type_attr' => ( isa => 'Str', is => 'ro', default => 'text' );
319 sub input_type {
320 my $self = shift;
321 return $self->html5_type_attr if ( $self->form && $self->form->has_flag('is_html5') );
322 return $self->type_attr;
323 }
324 # temporary methods for compatibility after name change
325 sub html_attr { shift->element_attr(@_) }
326 sub has_html_attr { shift->has_element_attr(@_) }
327 sub get_html_attr { shift->get_element_attr(@_) }
328 sub set_html_attr { shift->set_element_attr(@_) }
329
330 {
331 # create the attributes and methods for
332 # element_attr, build_element_attr, element_class,
333 # label_attr, build_label_attr, label_class,
334 # wrapper_attr, build_wrapper_atrr, wrapper_class
335 no strict 'refs';
336 foreach my $attr ('wrapper', 'element', 'label' ) {
337 # trigger to move 'class' set via _attr to the class slot
338 my $add_meth = "add_${attr}_class";
339 my $trigger_sub = sub {
340 my ( $self, $value ) = @_;
341 if( my $class = delete $self->{"${attr}_attr"}->{class} ) {
342 $self->$add_meth($class);
343 }
344 };
345 has "${attr}_attr" => ( is => 'rw', traits => ['Hash'],
346 builder => "build_${attr}_attr",
347 handles => {
348 "has_${attr}_attr" => 'count',
349 "get_${attr}_attr" => 'get',
350 "set_${attr}_attr" => 'set',
351 "delete_${attr}_attr" => 'delete',
352 "exists_${attr}_attr" => 'exists',
353 },
354 trigger => $trigger_sub,
355 );
356 # create builders fo _attrs
357 my $attr_builder = __PACKAGE__ . "::build_${attr}_attr";
358 *$attr_builder = subname $attr_builder, sub {{}};
359 # create the 'class' slots
360 has "${attr}_class" => ( is => 'rw', isa => 'HFH::ArrayRefStr',
361 traits => ['Array'],
362 coerce => 1,
363 builder => "build_${attr}_class",
364 handles => {
365 "has_${attr}_class" => 'count',
366 "_add_${attr}_class" => 'push',
367 },
368 );
369 # create builders for classes
370 my $class_builder = __PACKAGE__ . "::build_${attr}_class";
371 *$class_builder = subname $class_builder, sub {[]};
372 # create wrapper for add_to_ to accept arrayref
373 my $add_to_class = __PACKAGE__ . "::add_${attr}_class";
374 my $_add_meth = __PACKAGE__ . "::_add_${attr}_class";
375 *$add_to_class = subname $add_to_class, sub { shift->$_add_meth((ref $_[0] eq 'ARRAY' ? @{$_[0]} : @_)); }
376 }
377 }
378
379 # we're assuming that the only attribute we want in an element wrapper is a class
380 has 'element_wrapper_class' => (
381 is => 'rw', isa => 'HFH::ArrayRefStr',
382 traits => ['Array'],
383 coerce => 1,
384 builder => "build_element_wrapper_class",
385 handles => {
386 has_element_wrapper_class => 'count',
387 _add_element_wrapper_class => 'push',
388 },
389 );
390 sub add_element_wrapper_class { shift->_add_element_wrapper_class((ref $_[0] eq 'ARRAY' ? @{$_[0]} : @_)); }
391 sub build_element_wrapper_class { [] }
392 sub element_wrapper_attributes {
393 my ( $self, $result ) = @_;
394 $result ||= $self->result;
395 # local copy of label_attr
396 my $attr = {};
397 my $class = [@{$self->element_wrapper_class}];
398 $self->add_standard_element_wrapper_classes( $result, $class );
399 $attr->{class} = $class if @$class;
400 # call form hook
401 my $mod_attr;
402 $mod_attr = $self->form->html_attributes($self, 'element_wrapper', $attr, $result) if $self->form;
403 return ref($mod_attr) eq 'HASH' ? $mod_attr : $attr;
404 }
405 sub add_standard_element_wrapper_classes {
406 my ( $self, $result, $class ) = @_;
407 }
408
409 sub attributes { shift->element_attributes(@_) }
410 sub element_attributes {
411 my ( $self, $result ) = @_;
412 $result ||= $self->result;
413 my $attr = {};
414 # handle html5 attributes
415 if ($self->form && $self->form->has_flag('is_html5')) {
416 $attr->{required} = 'required' if $self->required && $self->html5_type_attr ne 'hidden';
417 $attr->{min} = $self->range_start if defined $self->range_start;
418 $attr->{max} = $self->range_end if defined $self->range_end;
419 }
420 # pull in deprecated attributes for backward compatibility
421 for my $dep_attr ( 'readonly', 'disabled' ) {
422 $attr->{$dep_attr} = $dep_attr if $self->$dep_attr;
423 }
424 for my $dep_attr ( 'style', 'title', 'tabindex' ) {
425 $attr->{$dep_attr} = $self->$dep_attr if defined $self->$dep_attr;
426 }
427 $attr = {%$attr, %{$self->element_attr}};
428 my $class = [@{$self->element_class}];
429 $self->add_standard_element_classes($result, $class);
430 $attr->{class} = $class if @$class;
431 # call form hook
432 my $mod_attr;
433 $mod_attr = $self->form->html_attributes($self, 'element', $attr, $result) if $self->form;
434 return ref($mod_attr) eq 'HASH' ? $mod_attr : $attr;
435 }
436
437 sub add_standard_element_classes {
438 my ( $self, $result, $class ) = @_;
439 push @$class, 'error' if $result->has_errors;
440 push @$class, 'warning' if $result->has_warnings;
441 push @$class, 'disabled' if $self->disabled;
442 }
443
444 sub label_attributes {
445 my ( $self, $result ) = @_;
446 $result ||= $self->result;
447 # local copy of label_attr
448 my $attr = {%{$self->label_attr}};
449 my $class = [@{$self->label_class}];
450 $self->add_standard_label_classes($result, $class);
451 $attr->{class} = $class if @$class;
452 # call form hook
453 my $mod_attr;
454 $mod_attr = $self->form->html_attributes($self, 'label', $attr, $result) if $self->form;
455 return ref($mod_attr) eq 'HASH' ? $mod_attr : $attr;
456 }
457
458 sub add_standard_label_classes {
459 my ( $self, $result, $class ) = @_;
460 }
461
462 sub wrapper_attributes {
463 my ( $self, $result ) = @_;
464 $result ||= $self->result;
465 # copy wrapper
466 my $attr = {%{$self->wrapper_attr}};
467 my $class = [@{$self->wrapper_class}];
468 # add 'error' to class
469 $self->add_standard_wrapper_classes($result, $class);
470 $attr->{class} = $class if @$class;
471 # add id if compound field and id doesn't exist unless 'no_wrapper_id' tag
472 $attr->{id} = $self->id
473 if ( $self->has_flag('is_compound') && not exists $attr->{id} && ! $self->get_tag('no_wrapper_id') );
474 # call form hook
475 my $mod_attr;
476 $mod_attr = $self->form->html_attributes($self, 'wrapper', $attr, $result) if $self->form;
477 return ref($mod_attr) eq 'HASH' ? $mod_attr : $attr;
478 }
479
480 sub add_standard_wrapper_classes {
481 my ( $self, $result, $class ) = @_;
482 push @$class, 'error' if ( $result->has_error_results || $result->has_errors );
483 push @$class, 'warning' if $result->has_warnings;
484 }
485
486
487 sub wrapper_tag {
488 my $self = shift;
489 return $self->get_tag('wrapper_tag') || 'div';
490 }
491
492 #=====================
493 # these may be temporary
494 sub field_filename {
495 my $self = shift;
496 return 'checkbox_tag.tt' if $self->input_type eq 'checkbox';
497 return 'input_tag.tt';
498 }
499 sub label_tag {
500 my $self = shift;
501 return $self->get_tag('label_tag') || 'label';
502 }
503 #===================
504
505 has 'writeonly' => ( isa => 'Bool', is => 'rw' );
506 has 'noupdate' => ( isa => 'Bool', is => 'rw' );
507
508 #==============
509 sub convert_full_name {
510 my $full_name = shift;
511 $full_name =~ s/\.\d+\./_/g;
512 $full_name =~ s/\./_/g;
513 return $full_name;
514 }
515 has 'validate_method' => (
516 traits => ['Code'],
517 is => 'ro',
518 isa => 'CodeRef',
519 lazy => 1,
520 builder => 'build_validate_method',
521 handles => { '_validate' => 'execute_method' },
522 );
523 has 'set_validate' => ( isa => 'Str', is => 'ro',);
524 sub build_validate_method {
525 my $self = shift;
526 my $set_validate = $self->set_validate;
527 $set_validate ||= "validate_" . convert_full_name($self->full_name);
528 return sub { my $self = shift; $self->form->$set_validate($self); }
529 if ( $set_validate ne 'validate_model' && $self->form && $self->form->can($set_validate) );
530 return sub { };
531 }
532
533 has 'default_method' => (
534 traits => ['Code'],
535 is => 'ro',
536 isa => 'CodeRef',
537 writer => '_set_default_method',
538 predicate => 'has_default_method',
539 handles => { '_default' => 'execute_method' },
540 );
541 has 'set_default' => ( isa => 'Str', is => 'ro', writer => '_set_default');
542 # this is not a "true" builder, because sometimes 'default_method' is not set
543 sub build_default_method {
544 my $self = shift;
545 my $set_default = $self->set_default;
546 $set_default ||= "default_" . convert_full_name($self->full_name);
547 if ( $self->form && $self->form->can($set_default) ) {
548 $self->_set_default_method(
549 sub { my $self = shift; return $self->form->$set_default($self, $self->form->item); }
550 );
551 }
552 }
553
554 sub get_default_value {
555 my $self = shift;
556 if ( $self->has_default_method ) {
557 return $self->_default;
558 }
559 elsif ( defined $self->default ) {
560 return $self->default;
561 }
562 return;
563 }
564 {
565 # create inflation/deflation methods
566 foreach my $type ( 'inflate_default', 'deflate_value', 'inflate', 'deflate' ) {
567 has "${type}_method" => ( is => 'ro', traits => ['Code'],
568 isa => 'CodeRef',
569 writer => "_set_${type}_method",
570 predicate => "has_${type}_method",
571 handles => {
572 $type => 'execute_method',
573 },
574 );
575 }
576 }
577
578 has 'deflation' => (
579 is => 'rw',
580 predicate => 'has_deflation',
581 );
582 has 'trim' => (
583 is => 'rw',
584 default => sub { { transform => \&default_trim } }
585 );
586
587 sub default_trim {
588 my $value = shift;
589 return unless defined $value;
590 my @values = ref $value eq 'ARRAY' ? @$value : ($value);
591 for (@values) {
592 next if ref $_ or !defined;
593 s/^\s+//;
594 s/\s+$//;
595 }
596 return ref $value eq 'ARRAY' ? \@values : $values[0];
597 }
598 has 'render_filter' => (
599 traits => ['Code'],
600 is => 'ro',
601 isa => 'CodeRef',
602 lazy => 1,
603 builder => 'build_render_filter',
604 handles => { html_filter => 'execute' },
605 );
606
607 sub build_render_filter {
608 my $self = shift;
609
610 if( $self->form && $self->form->can('render_filter') ) {
611 my $coderef = $self->form->can('render_filter');
612 return $coderef;
613 }
614 else {
615 return \&default_render_filter;
616 }
617 }
618
619 sub default_render_filter {
620 my $string = shift;
621 return '' if (!defined $string);
622 $string =~ s/&/&/g;
623 $string =~ s/</&lt;/g;
624 $string =~ s/>/&gt;/g;
625 $string =~ s/"/&quot;/g;
626 return $string;
627 }
628
629 has 'input_param' => ( is => 'rw', isa => 'Str' );
630
631 has 'language_handle' => (
632 isa => duck_type( [ qw(maketext) ] ),
633 is => 'rw',
634 reader => 'get_language_handle',
635 writer => 'set_language_handle',
636 predicate => 'has_language_handle'
637 );
638
639 sub language_handle {
640 my ( $self, $value ) = @_;
641 if( $value ) {
642 $self->set_language_handle($value);
643 return;
644 }
645 return $self->get_language_handle if( $self->has_language_handle );
646 # if language handle isn't set use form language handle if possible
647 return $self->form->language_handle if ( $self->has_form );
648 # no form, no language handle. This should only happen when
649 # testing fields.
650 my $lh;
651 if ( $ENV{LANGUAGE_HANDLE} ) {
652 if ( blessed $ENV{LANGUAGE_HANDLE} ) {
653 $lh = $ENV{LANGUAGE_HANDLE};
654 }
655 else {
656 $lh = HTML::FormHandler::I18N->get_handle( $ENV{LANGUAGE_HANDLE} );
657 }
658 }
659 else {
660 require HTML::FormHandler::I18N;
661 $lh = HTML::FormHandler::I18N->get_handle;
662 }
663 $self->set_language_handle($lh);
664 return $lh;
665 }
666
667 has 'localize_meth' => (
668 traits => ['Code'],
669 is => 'ro',
670 isa => 'CodeRef',
671 lazy => 1,
672 builder => 'build_localize_meth',
673 handles => { '_localize' => 'execute_method' },
674 );
675
676 sub build_localize_meth {
677 my $self = shift;
678
679 if( $self->form && $self->form->can('localize_meth') ) {
680 my $coderef = $self->form->can('localize_meth');
681 return $coderef;
682 }
683 else {
684 return \&default_localize;
685 }
686 }
687
688 sub default_localize {
689 my ($self, @message) = @_;
690 my $message = $self->language_handle->maketext(@message);
691 return $message;
692 }
693
694 has 'messages' => ( is => 'rw',
695 isa => 'HashRef',
696 traits => ['Hash'],
697 default => sub {{}},
698 handles => {
699 '_get_field_message' => 'get',
700 '_has_field_message' => 'exists',
701 'set_message' => 'set',
702 },
703 );
704
705 our $class_messages = {
706 'field_invalid' => 'field is invalid',
707 'range_too_low' => 'Value must be greater than or equal to [_1]',
708 'range_too_high' => 'Value must be less than or equal to [_1]',
709 'range_incorrect' => 'Value must be between [_1] and [_2]',
710 'wrong_value' => 'Wrong value',
711 'no_match' => '[_1] does not match',
712 'not_allowed' => '[_1] not allowed',
713 'error_occurred' => 'error occurred',
714 'required' => '[_1] field is required',
715 'unique' => 'Duplicate value for [_1]',
716 };
717
718 sub get_class_messages {
719 my $self = shift;
720 my $messages = { %$class_messages };
721 $messages->{required} = $self->required_message
722 if $self->required_message;
723 $messages->{unique} = $self->unique_message
724 if $self->unique_message;
725 return $messages;
726 }
727
728 sub get_message {
729 my ( $self, $msg ) = @_;
730
731 # first look in messages set on individual field
732 return $self->_get_field_message($msg)
733 if $self->_has_field_message($msg);
734 # then look at form messages
735 return $self->form->_get_form_message($msg)
736 if $self->has_form && $self->form->_has_form_message($msg);
737 # then look for messages up through inherited field classes
738 return $self->get_class_messages->{$msg};
739 }
740 sub all_messages {
741 my $self = shift;
742 my $form_messages = $self->has_form ? $self->form->messages : {};
743 my $field_messages = $self->messages || {};
744 my $lclass_messages = $self->my_class_messages || {};
745 return {%{$lclass_messages}, %{$form_messages}, %{$field_messages}};
746 }
747
748 sub BUILDARGS {
749 my $class = shift;
750
751 # for backwards compatibility; these will be removed eventually
752 my @new;
753 push @new, ('element_attr', {@_}->{html_attr} )
754 if( exists {@_}->{html_attr} );
755 push @new, ('do_label', !{@_}->{no_render_label} )
756 if( exists {@_}->{no_render_label} );
757 return $class->SUPER::BUILDARGS(@_, @new);
758 }
759
760 sub BUILD {
761 my ( $self, $params ) = @_;
762
763 # temporary, for compatibility. move widget_tags to tags
764 $self->merge_tags($self->wrapper_tags) if $self->has_wrapper_tags;
765 # run default method builder
766 $self->build_default_method;
767 # build validate_method; needs to happen before validation
768 # in order to have the "real" repeatable field names, not the instances
769 $self->validate_method;
770 # merge form widget_name_space
771 $self->add_widget_name_space( $self->form->widget_name_space ) if $self->form;
772 # handle apply actions
773 $self->add_action( $self->trim ) if $self->trim;
774 $self->_build_apply_list;
775 $self->add_action( @{ $params->{apply} } ) if $params->{apply};
776 }
777
778 # this is the recursive routine that is used
779 # to initialize field results if there is no initial object and no params
780 sub _result_from_fields {
781 my ( $self, $result ) = @_;
782
783 if ( $self->disabled && $self->has_init_value ) {
784 $result->_set_value($self->init_value);
785 }
786 elsif ( my @values = $self->get_default_value ) {
787 if ( $self->has_inflate_default_method ) {
788 @values = $self->inflate_default(@values);
789 }
790 my $value = @values > 1 ? \@values : shift @values;
791 $self->init_value($value) if defined $value;
792 $result->_set_value($value) if defined $value;
793 }
794 $self->_set_result($result);
795 $result->_set_field_def($self);
796 return $result;
797 }
798
799 sub _result_from_input {
800 my ( $self, $result, $input, $exists ) = @_;
801
802 if ($exists) {
803 $result->_set_input($input);
804 }
805 elsif ( $self->disabled ) {
806 # This maybe should come from _result_from_object, but there's
807 # not a reliable way to get there from here. Field can handle...
808 return $self->_result_from_fields( $result );
809 }
810 elsif ( $self->form && $self->form->use_fields_for_input_without_param ) {
811 return $self->_result_from_fields( $result );
812 }
813 elsif ( $self->has_input_without_param ) {
814 $result->_set_input( $self->input_without_param );
815 }
816 $self->_set_result($result);
817 $result->_set_field_def($self);
818 return $result;
819 }
820
821 sub _result_from_object {
822 my ( $self, $result, $value ) = @_;
823
824 $self->_set_result($result);
825
826 if ( $self->form ) {
827 $self->form->init_value( $self, $value );
828 }
829 else {
830 $self->init_value($value);
831 $result->_set_value($value);
832 }
833 $result->_set_value(undef) if $self->writeonly;
834 $result->_set_field_def($self);
835 return $result;
836 }
837
838 sub full_name {
839 my $field = shift;
840
841 my $name = $field->name;
842 my $parent_name;
843 # field should always have a parent unless it's a standalone field test
844 if ( $field->parent ) {
845 $parent_name = $field->parent->full_name;
846 }
847 return $name unless defined $parent_name && length $parent_name;
848 return $parent_name . '.' . $name;
849 }
850
851 sub full_accessor {
852 my $field = shift;
853
854 my $parent = $field->parent;
855 if( $field->is_contains ) {
856 return '' unless $parent;
857 return $parent->full_accessor;
858 }
859 my $accessor = $field->accessor;
860 my $parent_accessor;
861 if ( $parent ) {
862 $parent_accessor = $parent->full_accessor;
863 }
864 return $accessor unless defined $parent_accessor && length $parent_accessor;
865 return $parent_accessor . '.' . $accessor;
866 }
867
868 sub add_error {
869 my ( $self, @message ) = @_;
870
871 unless ( defined $message[0] ) {
872 @message = ( $class_messages->{field_invalid});
873 }
874 if ( ref $message[0] eq 'ARRAY' ) {
875 # The list-or-arrayref spelling here is the same convenience idiom as
876 # add_element_class and friends. It is not documented for add_error,
877 # nothing in the distribution reaches it, and what does reach it is
878 # request data: $field->add_error($field->value), where the request
879 # parser folded a duplicate parameter into an arrayref, puts submitted
880 # text in element 0 -- which _localize hands to Locale::Maketext as the
881 # FORMAT. Dereference as before, but if element 0 could be parsed as a
882 # bracket group, pass it as an inert argument instead of as the format.
883 # A caller who really wants a compiled template passes it as a plain
884 # list, $field->add_error($template, @args), which is the documented
885 # spelling and is unchanged.
886 my @args = @{ $message[0] };
887 # Interpolate explicitly: '[_1]' alone returns its argument unchanged
888 # (see the note in Validate.pm's _needs_inert_format caller), and the
889 # errors attribute holds strings.
890 @message = $self->_needs_inert_format( $args[0] )
891 ? ( '[_1]', "$args[0]" )
892 : @args;
893 }
894 my $out;
895 try {
896 $out = $self->_localize(@message);
897 }
898 catch {
899 die "Error occurred localizing error message for " . $self->label . ". Check brackets. $_";
900 };
901 return $self->push_errors($out);;
902 }
903
904 sub push_errors {
905 my $self = shift;
906 $self->_push_errors(@_);
907 if ( $self->parent ) {
908 $self->parent->propagate_error($self->result);
909 }
910 return;
911 }
912
913 sub _apply_deflation {
914 my ( $self, $value ) = @_;
915
916 if ( $self->has_deflation ) {
917 $value = $self->deflation->($value);
918 }
919 elsif ( $self->has_deflate_method ) {
920 $value = $self->deflate($value);
921 }
922 return $value;
923 }
924 sub _can_deflate {
925 my $self = shift;
926 return $self->has_deflation || $self->has_deflate_method;
927 }
928
929 # use Class::MOP to clone
930 sub clone {
931 my ( $self, %params ) = @_;
932 $self->meta->clone_object( $self, %params );
933 }
934
935 sub value_changed {
936 my ($self) = @_;
937
938 my @cmp;
939 for ( 'init_value', 'value' ) {
940 my $val = $self->$_;
941 $val = '' unless defined $val;
942 push @cmp, join '|', sort
943 map { ref($_) && $_->isa('DateTime') ? $_->iso8601 : "$_" }
944 ref($val) eq 'ARRAY' ? @$val : $val;
945 }
946 return $cmp[0] ne $cmp[1];
947 }
948
949 sub required_text { shift->required ? 'required' : 'optional' }
950
951 sub input_defined {
952 my ($self) = @_;
953 return unless $self->has_input;
954 return has_some_value( $self->input );
955 }
956
957 sub dump {
958 my $self = shift;
959
960 require Data::Dumper;
961 warn "HFH: ----- ", $self->name, " -----\n";
962 warn "HFH: type: ", $self->type, "\n";
963 warn "HFH: required: ", ( $self->required || '0' ), "\n";
964 warn "HFH: label: ", $self->label, "\n";
965 warn "HFH: widget: ", $self->widget || '', "\n";
966 my $v = $self->value;
967 warn "HFH: value: ", Data::Dumper::Dumper($v) if $v;
968 my $iv = $self->init_value;
969 warn "HFH: init_value: ", Data::Dumper::Dumper($iv) if $iv;
970 my $i = $self->input;
971 warn "HFH: input: ", Data::Dumper::Dumper($i) if $i;
972 my $fif = $self->fif;
973 warn "HFH: fif: ", Data::Dumper::Dumper($fif) if $fif;
974
975 if ( $self->can('options') ) {
976 my $o = $self->options;
977 warn "HFH: options: " . Data::Dumper::Dumper($o);
978 }
979 }
980
981 sub apply_rendering_widgets {
982 my $self = shift;
983
984 if ( $self->widget ) {
985 warn "in apply_rendering_widgets " . $self->widget . " Field\n";
986 $self->apply_widget_role( $self, $self->widget, 'Field' );
987 }
988 my $widget_wrapper = $self->widget_wrapper;
989 $widget_wrapper ||= $self->form->widget_wrapper if $self->form;
990 $widget_wrapper ||= 'Simple';
991 unless ( $widget_wrapper eq 'none' ) {
992 $self->apply_widget_role( $self, $widget_wrapper, 'Wrapper' );
993 }
994 return;
995
996 }
997
998 sub peek {
999 my ( $self, $indent ) = @_;
1000
1001 $indent ||= '';
1002 my $string = $indent . 'field: "' . $self->name . '" type: ' . $self->type . "\n";
1003 if( $self->has_flag('has_contains') ) {
1004 $string .= $indent . "contains: \n";
1005 my $lindent = $indent . ' ';
1006 foreach my $field ( $self->contains->sorted_fields ) {
1007 $string .= $field->peek( $lindent );
1008 }
1009 }
1010 if( $self->has_fields ) {
1011 $string .= $indent . 'subfields of "' . $self->name . '": ' . $self->num_fields . "\n";
1012 my $lindent = $indent . ' ';
1013 foreach my $field ( $self->sorted_fields ) {
1014 $string .= $field->peek( $lindent );
1015 }
1016 }
1017 return $string;
1018 }
1019
1020 sub has_some_value {
1021 my $x = shift;
1022
1023 return unless defined $x;
1024 return $x =~ /\S/ if !ref $x;
1025 if ( ref $x eq 'ARRAY' ) {
1026 for my $elem (@$x) {
1027 return 1 if has_some_value($elem);
1028 }
1029 return 0;
1030 }
1031 if ( ref $x eq 'HASH' ) {
1032 for my $key ( keys %$x ) {
1033 return 1 if has_some_value( $x->{$key} );
1034 }
1035 return 0;
1036 }
1037 return 1 if blessed($x); # true if blessed, otherwise false
1038 return 1 if ref( $x );
1039 return;
1040 }
1041
1042 sub apply_traits {
1043 my ($class, @traits) = @_;
1044
1045 $class->meta->make_mutable;
1046 Moose::Util::apply_all_roles($class->meta, @traits);
1047 $class->meta->make_immutable;
1048 }
1049
1050 __PACKAGE__->meta->make_immutable;
1051 use namespace::autoclean;
1052 1;
1053
1054 __END__
1055
1056 =pod
1057
1058 =encoding UTF-8
1059
1060 =head1 NAME
1061
1062 HTML::FormHandler::Field - base class for fields
1063
1064 =head1 VERSION
1065
1066 version 0.410002
1067
1068 =head1 SYNOPSIS
1069
1070 Instances of Field subclasses are generally built by L<HTML::FormHandler>
1071 from 'has_field' declarations or the field_list, but they can also be constructed
1072 using new for test purposes (since there's no standard way to add a field to a form
1073 after construction).
1074
1075 use HTML::FormHandler::Field::Text;
1076 my $field = HTML::FormHandler::Field::Text->new( name => $name, ... );
1077
1078 In your custom field class:
1079
1080 package MyApp::Field::MyText;
1081 use HTML::FormHandler::Moose;
1082 extends 'HTML::FormHandler::Field::Text';
1083
1084 has 'my_attribute' => ( isa => 'Str', is => 'rw' );
1085
1086 apply [ { transform => sub { ... } },
1087 { check => ['fighter', 'bard', 'mage' ], message => '....' }
1088 ];
1089 1;
1090
1091 =head1 DESCRIPTION
1092
1093 This is the base class for form fields. The 'type' of a field class
1094 is used in the FormHandler field_list or has_field to identify which field class to
1095 load from the 'field_name_space' (or directly, when prefixed with '+').
1096 If the type is not specified, it defaults to Text.
1097
1098 See L<HTML::FormHandler::Manual::Fields> for a list of the fields and brief
1099 descriptions of their structure.
1100
1101 =head1 ATTRIBUTES
1102
1103 =head2 Names, types, accessor
1104
1105 =over
1106
1107 =item name
1108
1109 The name of the field. Used in the HTML form. Often a db accessor.
1110 The only required attribute.
1111
1112 =item type
1113
1114 The class or type of the field. The 'type' of L<HTML::FormHandler::Field::Money>
1115 is 'Money'. Classes that you define yourself are prefixed with '+'.
1116
1117 =item accessor
1118
1119 If the name of your field is different than your database accessor, use
1120 this attribute to provide the accessor.
1121
1122 =item full_name
1123
1124 The name of the field with all parents:
1125
1126 'event.start_date.month'
1127
1128 =item full_accessor
1129
1130 The field accessor with all parents.
1131
1132 =item html_name
1133
1134 The full_name plus the form name if 'html_prefix' is set.
1135
1136 =item input_param
1137
1138 By default we expect an input parameter based on the field name. This allows
1139 you to look for a different input parameter.
1140
1141 =back
1142
1143 =head2 Field data
1144
1145 =over
1146
1147 =item inactive, is_inactive, is_active
1148
1149 Set the 'inactive' attribute to 1 if this field is inactive. The 'inactive' attribute
1150 that isn't set or is set to 0 will make a field 'active'.
1151 This provides a way to define fields in the form and selectively set them to inactive.
1152 There is also an '_active' attribute, for internal use to indicate that the field has
1153 been activated/inactivated on 'process' by the form's 'active'/'inactive' attributes.
1154
1155 You can use the is_inactive and is_active methods to check whether this particular
1156 field is active.
1157
1158 if( $form->field('foo')->is_active ) { ... }
1159
1160 =item input
1161
1162 The input string from the parameters passed in.
1163
1164 =item value
1165
1166 The value as it would come from or go into the database, after being
1167 acted on by inflations/deflations and transforms. Used to construct the
1168 C<< $form->values >> hash. Validation and constraints act on 'value'.
1169
1170 See also L<HTML::FormHandler::Manual::InflationDeflation>.
1171
1172 =item fif
1173
1174 Values used to fill in the form. Read only. Use a deflation to get
1175 from 'value' to 'fif' if an inflator was used. Use 'fif_from_value'
1176 attribute if you want to use the field 'value' to fill in the form.
1177
1178 [% form.field('title').fif %]
1179
1180 =item init_value
1181
1182 Initial value populated by init_from_object. You can tell if a field
1183 has changed by comparing 'init_value' and 'value'. Read only.
1184
1185 =item input_without_param
1186
1187 Input for this field if there is no param. Set by default for Checkbox,
1188 and Select, since an unchecked checkbox or unselected pulldown
1189 does not return a parameter.
1190
1191 =back
1192
1193 =head2 Form, parent
1194
1195 =over
1196
1197 =item form
1198
1199 A reference to the containing form.
1200
1201 =item parent
1202
1203 A reference to the parent of this field. Compound fields are the
1204 parents for the fields they contain.
1205
1206 =back
1207
1208 =head2 Errors
1209
1210 =over
1211
1212 =item errors
1213
1214 Returns the error list for the field. Also provides 'num_errors',
1215 'has_errors', 'push_errors' and 'clear_errors' from Array
1216 trait. Use 'add_error' to add an error to the array if you
1217 want to use a MakeText language handle. Default is an empty list.
1218
1219 =item add_error
1220
1221 Add an error to the list of errors. Error message will be localized
1222 using '_localize' method.
1223 See also L<HTML::FormHandler::TraitFor::I18N>.
1224
1225 return $field->add_error( 'bad data' ) if $bad;
1226
1227 The first argument is the localization FORMAT, which for a
1228 L<Locale::Maketext> handle means bracket notation in it is compiled and
1229 executed. Do not build that argument out of submitted data: a value
1230 containing a C<[...]> group would be run as a method call rather than
1231 shown. Pass the value as an argument instead, where it is inert:
1232
1233 # wrong -- the submitted value becomes part of the format
1234 $field->add_error( "The value '" . $field->value . "' is not allowed" );
1235
1236 # right -- the format is yours, the value is just an argument
1237 $field->add_error( "The value '[_1]' is not allowed", $field->value );
1238
1239 Also note that the first argument is cached by L<Locale::Maketext>,
1240 without any size limits or purging of data. Passing error messages in
1241 the first argument that contain text submitted over the network opens
1242 up a system to memory consumption attacks.
1243
1244 =item error_fields
1245
1246 Compound fields will have an array of errors from the subfields.
1247
1248 =item localize_meth
1249
1250 Set the method used to localize.
1251
1252 =back
1253
1254 =head2 Attributes for creating HTML
1255
1256 The 'element_attr' hashref attribute can be used to set
1257 arbitrary HTML attributes on a field's input tag.
1258
1259 has_field 'foo' => ( element_attr => { readonly => 1, my_attr => 'abc' } );
1260
1261 Note that the 'id' and 'type' attributes are not set using element_attr. Use
1262 the field's 'id' attribute (or 'build_id_method') to set the id.
1263
1264 The 'label_attr' hashref is for label attributes, and the 'wrapper_attr'
1265 is for attributes on the wrapping element (a 'div' for the standard 'simple'
1266 wrapper).
1267
1268 A 'javascript' key in one of the '_attr' hashes will be inserted into the
1269 element as-is.
1270
1271 The following are used in rendering HTML, but are handled specially.
1272
1273 label - Text label for this field. Defaults to ucfirst field name.
1274 build_label_method - coderef for constructing the label
1275 wrap_label_method - coderef for constructing a wrapped label
1276 id - Useful for javascript (default is html_name. to prefix with
1277 form name, use 'html_prefix' in your form)
1278 build_id_method - coderef for constructing the id
1279 render_filter - Coderef for filtering fields before rendering. By default
1280 changes >, <, &, " to the html entities
1281 disabled - Boolean to set field disabled
1282
1283 The order attribute may be used to set the order in which fields are rendered.
1284
1285 order - Used for sorting errors and fields. Built automatically,
1286 but may also be explicitly set
1287
1288 The following are discouraged. Use 'element_attr', 'label_attr', and 'wrapper_attr'
1289 instead.
1290
1291 title - instead use element_attr => { title => '...' }
1292 style - instead use element_attr => { style => '...' }
1293 tabindex - instead use element_attr => { tabindex => 1 }
1294 readonly - instead use element_attr => { readonly => 'readonly' }
1295
1296 Rendering of the various HTML attributes is done by calling the 'process_attrs'
1297 function (from HTML::FormHandler::Render::Util) and passing in a method that
1298 adds in error classes, provides backward compatibility with the deprecated
1299 attributes, etc.
1300
1301 attribute hashref class attribute wrapping method
1302 ================= ================= ================
1303 element_attr element_class element_attributes
1304 label_attr label_class label_attributes
1305 wrapper_attr wrapper_class wrapper_attributes
1306 element_wrapper_class element_wrapper_attributes
1307
1308 ('element_wrapper' is for an inner div around the input element, not
1309 including the label. Used for Bootstrap3 rendering, but also available
1310 in the Simple wrapper.)
1311 The slots for the class attributes are arrayrefs; they will coerce a
1312 string into an arrayref.
1313 In addition, these 'wrapping methods' call a hook method in the form class,
1314 'html_attributes', which you can use to customize and localize the various
1315 attributes. (Field types: 'element', 'wrapper', 'label')
1316
1317 sub html_attributes {
1318 my ( $self, $field, $type, $attr ) = @_;
1319 $attr->{class} = 'label' if $type eq 'label';
1320 return $attr;
1321 }
1322
1323 The 'process_attrs' function will also handle an array of strings, such as for the
1324 'class' attribute.
1325
1326 =head2 tags
1327
1328 A hashref containing flags and strings for use in the rendering code.
1329 The value of a tag can be a string, a coderef (accessed as a method on the
1330 field) or a block specified with a percent followed by the blockname
1331 ('%blockname').
1332
1333 Retrieve a tag with 'get_tag'. It returns a '' if the tag doesn't exist.
1334
1335 This attribute used to be named 'widget_tags', which is deprecated.
1336
1337 =head2 html5_type_attr [string]
1338
1339 This string is used when rendering an input element as the value for the type attribute.
1340 It is used when the form has the is_html5 flag on.
1341
1342 =head2 widget
1343
1344 The 'widget' attribute is used in rendering, so if you are
1345 not using FormHandler's rendering facility, you don't need this
1346 attribute. It is used in generating HTML, in templates and the
1347 rendering roles. Fields of different type can use the same widget.
1348
1349 This attribute is set in the field classes, or in the fields
1350 defined in the form. If you want a new widget type, create a
1351 widget role, such as MyApp::Form::Widget::Field::MyWidget. Provide
1352 the name space in the 'widget_name_space' attribute, and set
1353 the 'widget' of your field to the package name after the
1354 Field/Form/Wrapper:
1355
1356 has_field 'my_field' => ( widget => 'MyWidget' );
1357
1358 If you are using a template based rendering system you will want
1359 to create a widget template.
1360 (see L<HTML::FormHandler::Manual::Templates>)
1361
1362 Widget types for some of the provided field classes:
1363
1364 Widget : Field classes
1365 -----------------------:---------------------------------
1366 Text : Text, Integer
1367 Checkbox : Checkbox, Boolean
1368 RadioGroup : Select, Multiple, IntRange (etc)
1369 Select : Select, Multiple, IntRange (etc)
1370 CheckboxGroup : Multiple select
1371 TextArea : TextArea
1372 Compound : Compound, Repeatable, DateTime
1373 Password : Password
1374 Hidden : Hidden
1375 Submit : Submit
1376 Reset : Reset
1377 NoRender :
1378 Upload : Upload
1379
1380 Widget roles are automatically applied to field classes
1381 unless they already have a 'render' method, and if the
1382 'no_widgets' flag in the form is not set.
1383
1384 You can create your own widget roles and specify the namespace
1385 in 'widget_name_space'. In the form:
1386
1387 has '+widget_name_space' => ( default => sub { ['MyApp::Widget'] } );
1388
1389 If you want to use a fully specified role name for a widget, you
1390 can prefix it with a '+':
1391
1392 widget => '+MyApp::Widget::SomeWidget'
1393
1394 For more about widgets, see L<HTML::FormHandler::Manual::Rendering>.
1395
1396 =head2 Flags
1397
1398 password - prevents the entered value from being displayed in the form
1399 writeonly - The initial value is not taken from the database
1400 noupdate - Do not update this field in the database (does not appear in $form->value)
1401
1402 =head2 Defaults
1403
1404 See also the documentation on L<HTML::FormHandler::Manual::Intro/Defaults>.
1405
1406 =over
1407
1408 =item default_method, set_default
1409
1410 Supply a coderef (which will be a method on the field) with 'default_method'
1411 or the name of a form method with 'set_default' (which will be a method on
1412 the form). If not specified and a form method with a name of
1413 C<< default_<field_name> >> exists, it will be used.
1414
1415 =item default
1416
1417 Provide an initial value just like the 'set_default' method, except in the field
1418 declaration:
1419
1420 has_field 'bax' => ( default => 'Default bax' );
1421
1422 FormHandler has flipped back and forth a couple of times about whether a default
1423 specified in the has_field definition should override values provided in an
1424 initial item or init_object. Sometimes people want one behavior, and sometimes
1425 the other. Now 'default' does *not* override.
1426
1427 If you pass in a model object with C<< item => $row >> or an initial object
1428 with C<< init_object => {....} >> the values in that object will be used instead
1429 of values provided in the field definition with 'default' or 'default_fieldname'.
1430 If you want defaults that override or supplement the item/init_object, you can use the form
1431 flags 'use_defaults_over_obj', 'use_init_obj_over_item', and
1432 'use_init_obj_when_no_accessor_in_item'.
1433
1434 You could also put your defaults into your row or init_object instead.
1435
1436 =item default_over_obj
1437
1438 This is deprecated; look into using 'use_defaults_over_obj' or 'use_init_obj_over_item'
1439 flags instead. They allow using the standard 'default' attribute.
1440
1441 Allows setting defaults which will override values provided with an item/init_object.
1442 (And only those. Will not be used for defaults without an item/init_object.)
1443
1444 has_field 'quux' => ( default_over_obj => 'default quux' );
1445
1446 At this time there is no equivalent of 'set_default', but the type of the attribute
1447 is not defined so you can provide default values in a variety of other ways,
1448 including providing a trait which does 'build_default_over_obj'. For examples,
1449 see tests in the distribution.
1450
1451 =back
1452
1453 =head1 Constraints and Validations
1454
1455 See also L<HTML::FormHandler::Manual::Validation>.
1456
1457 =head2 Constraints set in attributes
1458
1459 =over
1460
1461 =item required
1462
1463 Flag indicating whether this field must have a value
1464
1465 =item unique
1466
1467 For DB field - check for uniqueness. Action is performed by
1468 the DB model.
1469
1470 =item messages
1471
1472 messages => { required => '...', unique => '...' }
1473
1474 Set messages created by FormHandler by setting in the 'messages'
1475 hashref. Some field subclasses have additional settable messages.
1476
1477 required: Error message text added to errors if required field is not present.
1478 The default is "Field <field label> is required".
1479
1480 =item range_start
1481
1482 =item range_end
1483
1484 Field values are validated against the specified range if one
1485 or both of range_start and range_end are set and the field
1486 does not have 'options'.
1487
1488 The IntRange field uses this range to create a select list
1489 with a range of integers.
1490
1491 In a FormHandler field_list:
1492
1493 age => {
1494 type => 'Integer',
1495 range_start => 18,
1496 range_end => 120,
1497 }
1498
1499 =item not_nullable
1500
1501 Fields that contain 'empty' values such as '' are changed to undef in the validation process.
1502 If this flag is set, the value is not changed to undef. If your database column requires
1503 an empty string instead of a null value (such as a NOT NULL column), set this attribute.
1504
1505 has_field 'description' => (
1506 type => 'TextArea',
1507 not_nullable => 1,
1508 );
1509
1510 This attribute is also used when you want an empty array to stay an empty array and not
1511 be set to undef.
1512
1513 It's also used when you have a compound field and you want the 'value' returned
1514 to contain subfields with undef, instead of the whole field to be undef.
1515
1516 =back
1517
1518 =head2 apply
1519
1520 Use the 'apply' keyword to specify an ArrayRef of constraints and coercions to
1521 be executed on the field at validate_field time.
1522
1523 has_field 'test' => (
1524 apply => [ 'MooseType',
1525 { check => sub {...}, message => { } },
1526 { transform => sub { ... lc(shift) ... } }
1527 ],
1528 );
1529
1530 See more documentation in L<HTML::FormHandler::Manual::Validation>.
1531
1532 =head2 trim
1533
1534 An action to trim the field. By default
1535 this contains a transform to strip beginning and trailing spaces.
1536 Set this attribute to null to skip trimming, or supply a different
1537 transform.
1538
1539 trim => { transform => sub {
1540 my $string = shift;
1541 $string =~ s/^\s+//;
1542 $string =~ s/\s+$//;
1543 return $string;
1544 } }
1545 trim => { type => MyTypeConstraint }
1546
1547 Trimming is performed before any other defined actions.
1548
1549 =head2 Inflation/deflation
1550
1551 There are a number of methods to provide finely tuned inflation and deflation:
1552
1553 =over 4
1554
1555 =item inflate_method
1556
1557 Inflate to a data format desired for validation.
1558
1559 =item deflate_method
1560
1561 Deflate to a string format for presenting in HTML.
1562
1563 =item inflate_default_method
1564
1565 Modify the 'default' provided by an 'item' or 'init_object'.
1566
1567 =item deflate_value_method
1568
1569 Modify the value returned by C<< $form->value >>.
1570
1571 =item deflation
1572
1573 Another way of providing a deflation method.
1574
1575 =item transform
1576
1577 Another way of providing an inflation method.
1578
1579 =back
1580
1581 Normally if you have a deflation, you will need a matching inflation.
1582 There are two different flavors of inflation/deflation: one for inflating values
1583 to a format needed for validation and deflating for output, the other for
1584 inflating the initial provided values (usually from a database row) and deflating
1585 them for the 'values' returned.
1586
1587 See L<HTML::FormHandler::Manual::InflationDeflation>.
1588
1589 =head1 Processing and validating the field
1590
1591 =head2 validate_field
1592
1593 This is the base class validation routine. Most users will not
1594 do anything with this. It might be useful for method modifiers,
1595 if you want code that executed before or after the validation
1596 process.
1597
1598 =head2 validate
1599
1600 This field method can be used in addition to or instead of 'apply' actions
1601 in custom field classes.
1602 It should validate the field data and set error messages on
1603 errors with C<< $field->add_error >>.
1604
1605 sub validate {
1606 my $field = shift;
1607 my $value = $field->value;
1608 return $field->add_error( ... ) if ( ... );
1609 }
1610
1611 =head2 validate_method, set_validate
1612
1613 Supply a coderef (which will be a method on the field) with 'validate_method'
1614 or the name of a form method with 'set_validate' (which will be a method on
1615 the form). If not specified and a form method with a name of
1616 C<< validate_<field_name> >> exists, it will be used.
1617
1618 Periods in field names will be replaced by underscores, so that the field
1619 'addresses.city' will use the 'validate_addresses_city' method for validation.
1620
1621 has_field 'my_foo' => ( validate_method => \&my_foo_validation );
1622 sub my_foo_validation { ... }
1623 has_field 'title' => ( isa => 'Str', set_validate => 'check_title' );
1624
1625 =head1 AUTHOR
1626
1627 FormHandler Contributors - see HTML::FormHandler
1628
1629 =head1 COPYRIGHT AND LICENSE
1630
1631 This software is copyright (c) 2017 by Gerda Shank.
1632
1633 This is free software; you can redistribute it and/or modify it under
1634 the same terms as the Perl 5 programming language system itself.
1635
1636 =cut