Valiant/HTML/Util/Form.pm

filter: Statementstmt 84.8% 123 / 145 Branchbran 62.5% 55 / 88 Conditioncond 48.7% 19 / 39 MC/DCmcdc 25.0% 6 / 24 Subroutinesub 86.9% 20 / 23 Podpod 40.0% 2 / 5 totaltotal 69.4% 225 / 324 CC 60 SCAR 21.2
CC
60
Cov
72%
_html_options_for_form_with
14.9
_instantiate_builder
13.7
_dom_id
12.0
CRAP 8.3
« Valiant/I18N.pm ↑ Summary DBIx/Class/Valiant/Validator/Result.pm »
1 package Valiant::HTML::Util::Form;
2  
3 3 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use Module::Runtime;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use Valiant::Naming;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 3 extends 'Valiant::HTML::Util::FormTags';
10  
11 3 has 'context' => (is=>'ro', required=>0, predicate=>'has_context'); # For the future
12 3 has 'controller' => (is=>'ro', required=>0); # For the future
13  
14 3 has 'form_with_generates_ids' => (
15 is => 'ro',
16 required => 1,
17 builder => '_form_with_generates_ids'
18 );
19  
20 2 ▶ sub _form_with_generates_ids { 0 }
Subroutine _form_with_generates_ids: called CC=1 SCAR=0.0
21  
22 3 has 'formbuilder_class' => (
23 is => 'ro',
24 required => 1,
25 lazy => 1,
26 builder => '_default_formbuilder_class',
27 );
28  
29 sub _default_formbuilder_class {
30 2 ▶ my $self = shift;
Subroutine _default_formbuilder_class: called CC=2 SCAR=7.1
31 2 ▶ return $self->view->formbuilder_class if $self->view->can('formbuilder_class');
Branch: 1 branch
BranchTrueFalseTotal
if $self->view->can("formbuilder_class") 0 2 2
32 2 return 'Valiant::HTML::FormBuilder';
33 };
34  
35 # for class and subclasses
36  
37 7 ▶sub _DEFAULT_ID_DELIM { '_' }
Subroutine _DEFAULT_ID_DELIM: called CC=1 SCAR=0.0
38  
39 sub _dom_class {
40 0 ▶ my ($self, $model, $prefix) = @_;
Subroutine _dom_class: not called CC=2 SCAR=17.9
41 0 my $singular = $self->_model_name_from_object_or_class($model)->param_key;
42 0 ▶ return $prefix ? "${prefix}@{[ _DEFAULT_ID_DELIM ]}${singular}" : $singular;
Branch: 1 branch
BranchTrueFalseTotal
$prefix ? : 0 0 0
43 }
44  
45 sub _dom_id {
46 0 ▶ my ($self, $model, $prefix) = @_;
Subroutine _dom_id: not called CC=3 SCAR=24.8
47 0 ▶ if(my $model_id = _model_id_for_dom_id($model)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $model_id = _model_id_for_dom_id($model)) { } 0 0 0
48 0 return "@{[ $self->_dom_class($model, $prefix) ]}@{[ _DEFAULT_ID_DELIM ]}${model_id}";
49 } else {
50 0 ▶ $prefix ||= 'new';
Condition0%0/2
$prefix ||= "new"
l!l
00
MC/DC0%0/1
$prefix ||= "new"
$prefix
Truth table0%0/2
A
A= $prefix
Aresult
11
00
51 0 return $self->_dom_class($model, $prefix)
52 }
53 }
54  
55 sub _model_id_for_dom_id {
56 0 ▶ my $model = shift;
Subroutine _model_id_for_dom_id: not called CC=3 SCAR=24.8
57 0 ▶ return unless $model->can('id') && defined($model->id);
Branch: 1 branch
BranchTrueFalseTotal
unless $model->can("id") and defined $model->id 0 0 0
Condition0%0/3
$model->can("id") and defined $model->id
!ll&&!rl&&r
000
MC/DC0%0/2
$model->can("id") and defined $model->id
$model->can("id") defined $model->id
Truth table0%0/3
A and B
A= $model->can("id")B= defined $model->id
ABresult
0X0
100
111
58 0 return join '_', ($model->id);
59 }
60  
61 sub _to_model {
62 28 ▶ my ($self, $model) = @_;
Subroutine _to_model: called CC=2 SCAR=7.1
63 28 ▶ return $model->to_model if $model->can('to_model');
Branch: 1 branch
BranchTrueFalseTotal
if $model->can("to_model") 0 28 28
64 28 return $model;
65 }
66  
67  
68 sub _model_name_from_object_or_class {
69 6 ▶ my ($self, $proto) = @_;
Subroutine _model_name_from_object_or_class: called CC=2 SCAR=7.6
70 6 my $model = $self->_to_model($proto);
71 6 ▶ return $model->model_name if $model->can('model_name');
Branch: 1 branch
BranchTrueFalseTotal
if $model->can("model_name") 6 0 6
72 0 return Valiant::Name->new(Valiant::Naming::prepare_model_name_args($model));
73 }
74  
75 sub _apply_form_options {
76 7 ▶ my ($self, $model, $options) = @_;
Subroutine _apply_form_options: called CC=7 SCAR=20.2
77 7 $model = $self->_to_model($model);
78  
79 7 ▶ my $as = exists $options->{as} ? $options->{as} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $options->{'as'} ? : 7 0 7
80 7 ▶ my $namespace = exists $options->{namespace} ? $options->{namespace} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $options->{'namespace'} ? : 0 7 7
81 7 ▶ my ($action, $method) = @{ $self->model_persisted($model) ? ['edit', 'patch']:['new', 'post'] };
Branch: 1 branch
BranchTrueFalseTotal
$self->model_persisted($model) ? : 4 3 7
82  
83 $options->{html} = $self->_merge_attrs(
84 ($options->{html} || +{}),
85 +{
86 class => $as ? "${action}_${as}" : $self->_dom_class($model, $action),
87 7 ▶ id => join(_DEFAULT_ID_DELIM, ( $as ? (grep { defined $_ } $namespace, $action, $as) : (grep { defined $_ } ($namespace, $self->_dom_id($model, $action))) )),
Branch: 2 branches
BranchTrueFalseTotal
$as ? : 7 0 7
$as ? : 7 0 7
Condition100%2/2
$options->{'html'} || {}
l!l
16
MC/DC100%1/1
$options->{'html'} || {}
$options->{'html'}
Truth table100%2/2
A
A= $options->{'html'}
Aresult
11
00
88 method => $method,
89 },
90 );
91  
92 7 return $options;
93 }
94  
95 # public methods
96  
97 sub model_persisted {
98 7 ▶ my ($self, $model) = @_;
Subroutine model_persisted: called CC=3 SCAR=16.5
Pod undocumented
99 7 ▶ return $model->persisted if $model->can('persisted');
Branch: 1 branch
BranchTrueFalseTotal
if $model->can("persisted") 7 0 7
100 0 ▶ return $model->in_storage if $model->can('in_storage');
Branch: 1 branch
BranchTrueFalseTotal
if $model->can("in_storage") 0 0 0
101 0 return 0;
102 }
103  
104 # form_for $model, \%options, \&block
105 # form_for $model, \&block
106 #
107 # Where %options are:
108 # action: actual url the action. not required
109 # method: default is POST
110 # namespace: additional prefix for form and element IDs for uniqueness. not required
111 # html: additional hash of values for html attributes
112  
113 sub form_for {
114 4 ▶ my $self = shift;
Subroutine form_for: called CC=10 SCAR=23.3
Pod documented
115 4 my $proto = shift; # required; at the start
116 4 my $content_block_coderef = pop; # required; at the end
117 4 ▶ my $options = ref($_[-1]||'') eq 'HASH' ? pop : +{};
Branch: 1 branch
BranchTrueFalseTotal
ref($_[-1] || '') eq 'HASH' ? : 3 1 4
Condition100%2/2
$_[-1] || ''
l!l
31
MC/DC100%1/1
$_[-1] || ''
$_[-1]
Truth table100%2/2
A
A= $_[-1]
Aresult
11
00
118  
119 4 ▶ carp "You must provide a content block to form_for" unless ref($content_block_coderef) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $content_block_coderef eq "CODE" 0 4 4
120  
121 4 my ($model, $object_name);
122 4 ▶ if( ref(\$proto) eq 'SCALAR') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref \$proto eq 'SCALAR') { } 2 2 4
elsif (builtin::blessed($proto)) { } 2 0 2
123 2 $object_name = $proto;
124 2 ▶ if(@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 1 1 2
125 1 $model = shift;
126 } else {
127 1 ▶ $model = $self->view->read_attribute_for_html($object_name)
Branch: 1 branch
BranchTrueFalseTotal
if $self->view->attribute_exists_for_html($object_name) 1 0 1
128 if $self->view->attribute_exists_for_html($object_name);
129 }
130 } elsif(Scalar::Util::blessed($proto)) {
131 2 $model = $proto;
132 $object_name = exists $options->{as} ?
133 $options->{as} :
134 2 ▶ $self->_model_name_from_object_or_class($model)->param_key;
Branch: 1 branch
BranchTrueFalseTotal
exists $options->{'as'} ? : 0 2 2
135 }
136  
137 4 $options->{model} = $model;
138 4 $options->{scope} = $object_name;
139 4 $options->{skip_default_ids} = 0;
140 $options->{allow_method_names_outside_object} = exists $options->{allow_method_names_outside_object} ?
141 4 ▶ $options->{allow_method_names_outside_object} : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $options->{'allow_method_names_outside_object'} ? : 0 4 4
142  
143 4 return $self->form_with($options, $content_block_coderef);
144 }
145  
146 sub form_with {
147 11 ▶ my $self = shift;
Subroutine form_with: called CC=8 SCAR=20.9
Pod undocumented
148 11 my $content_block_coderef = pop; # required; at the end
149 11 ▶ my $options = @_ ? shift : +{};
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 11 0 11
150 11 ▶ my $scope = exists $options->{scope} ? $options->{scope} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $options->{'scope'} ? : 6 5 11
151  
152 11 $options->{allow_method_names_outside_object} = 1;
153 11 $options->{skip_default_ids} = 0;
154  
155 11 my ($model, $url);
156 11 ▶ if($options->{model}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"model"}) 7 4 11
157 7 $model = $self->_to_model(delete $options->{model});
158 $scope = exists $options->{scope} ?
159 delete $options->{scope} :
160 7 ▶ $self->_model_name_from_object_or_class($model)->param_key;
Branch: 1 branch
BranchTrueFalseTotal
exists $options->{'scope'} ? : 4 3 7
161  
162 7 ▶ $options->{as} = $scope unless exists $options->{as};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $options->{"as"} 7 0 7
163  
164 7 $self->_apply_form_options($model, $options);
165
166 # TODO: This it where we need to be able to get a url from the model
167 # for the builder. Either the model itself should have a way to do
168 # this or possible the controller ($url = $self->controller->url_for_model($model))
169 # this method should DTRT in generating a url for a new or existing model and
170 # should be able to be overridden by args passed.
171 }
172  
173 11 ▶ $url ||= delete $options->{url} if exists $options->{url};
Branch: 1 branch
BranchTrueFalseTotal
if exists $options->{"url"} 9 2 11
Condition33%1/3
$url ||= delete $options->{"url"}
l!l&&r!l&&!r
090
MC/DC0%0/2
$url ||= delete $options->{"url"}
$url delete $options->{"url"}
Truth table33%1/3
A ||= B
A= $urlB= delete $options->{"url"}
ABresult
1X1
011
000
174  
175 11 my $builder = $self->_instantiate_builder($scope, $model, $options);
176 11 my $html_options = $self->_html_options_for_form_with($url, $model, $options);
177 my $output = $self->join_tags(
178 $self->form_tag($html_options, sub {
179 11 ▶ my @form_node = $content_block_coderef->($self->view, $builder, $model);
Subroutine __ANON__: called CC=1 SCAR=0.0
180 11 return $builder->view->safe_concat(@form_node);
181 })
182 11 );
183  
184 11 return $output;
185 }
186  
187 # _instantiate_builder($object)
188 # _instantiate_builder($object, \%options)
189 # _instantiate_builder($name, $object)
190 # _instantiate_builder($name, $object, \%options)
191  
192 sub _instantiate_builder {
193 43 ▶ my $self = shift;
Subroutine _instantiate_builder: called CC=10 SCAR=26.2
194 43 ▶ my $options = (ref($_[-1])||'') eq 'HASH' ? pop(@_) : +{};
Branch: 1 branch
BranchTrueFalseTotal
(ref $_[-1] || '') eq 'HASH' ? : 43 0 43
Condition50%1/2
ref $_[-1] || ''
l!l
430
MC/DC0%0/1
ref $_[-1] || ''
ref $_[-1]
Truth table50%1/2
A
A= ref $_[-1]
Aresult
11
00
195 43 ▶ my $object = Scalar::Util::blessed($_[-1]) ? pop(@_) : bless +{}, 'Valiant::HTML::FormBuilder::DefaultModel';
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($_[-1]) ? : 38 5 43
196 43 ▶ my $model_name = scalar(@_) ? shift(@_) : $self->_model_name_from_object_or_class($object)->param_key;
Branch: 1 branch
BranchTrueFalseTotal
scalar @_ ? : 43 0 43
197 my $builder = exists($options->{builder}) && defined($options->{builder}) ?
198 $options->{builder} :
199 43 ▶ $self->formbuilder_class;
Branch: 1 branch
BranchTrueFalseTotal
exists $options->{'builder'} && defined $options->{'builder'} ? : 23 20 43
Condition66%2/3
exists $options->{"builder"} and defined $options->{"builder"}
!ll&&!rl&&r
20023
MC/DC50%1/2
exists $options->{"builder"} and defined $options->{"builder"}
exists $options->{"builder"} defined $options->{"builder"}
Truth table66%2/3
A and B
A= exists $options->{"builder"}B= defined $options->{"builder"}
ABresult
0X0
100
111
200  
201 43 my %args = (
202 tag_helpers => $self,
203 model => $object,
204 name => $model_name,
205 options => $options
206 );
207  
208 43 $options->{builder} = $builder;
209 43 $self->_merge_attrs(\%args, $options, qw(namespace id index parent_builder theme));
210  
211 43 ▶ if( exists($options->{parent_builder}) && exists($options->{parent_builder}{theme}) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{"parent_builder"} and exists $options->{"parent_builder"}{"theme"}) 0 43 43
Condition66%2/3
exists $options->{"parent_builder"} and exists $options->{"parent_builder"}{"theme"}
!ll&&!rl&&r
16270
MC/DC0%0/2
exists $options->{"parent_builder"} and exists $options->{"parent_builder"}{"theme"}
exists $options->{"parent_builder"} exists $options->{"parent_builder"}{"theme"}
Truth table66%2/3
A and B
A= exists $options->{"parent_builder"}B= exists $options->{"parent_builder"}{"theme"}
ABresult
0X0
100
111
212 0 ▶ $args{theme} = +{ %{$args{theme}||+{}}, %{$options->{parent_builder}{theme}} };
Branch: 1 branch
BranchTrueFalseTotal
$args{"theme"} or {} 0 0 0
213 }
214  
215 43 return Module::Runtime::use_module($builder)->new(%args);
216 }
217  
218 sub _html_options_for_form_with {
219 11 ▶ my ($self, $url, $model, $options) = @_;
Subroutine _html_options_for_form_with: called CC=10 SCAR=27.0
220 11 ▶ my $html_options = $options->{html} || +{};
Condition100%2/2
$options->{'html'} || {}
l!l
74
MC/DC100%1/1
$options->{'html'} || {}
$options->{'html'}
Truth table100%2/2
A
A= $options->{'html'}
Aresult
11
00
221  
222 11 $self->_merge_attrs($html_options, $options, qw(action method data id csrf_token class style));
223  
224 11 ▶ $html_options->{action} = $url if $url;
Branch: 1 branch
BranchTrueFalseTotal
if $url 9 2 11
225 11 ▶ $html_options->{csrf_token} ||= $self->view->csrf_token if $self->view->can('csrf_token');
Branch: 1 branch
BranchTrueFalseTotal
if $self->view->can("csrf_token") 0 11 11
Condition0%0/3
$html_options->{"csrf_token"} ||= $self->view->csrf_token
l!l&&r!l&&!r
000
MC/DC0%0/2
$html_options->{"csrf_token"} ||= $self->view->csrf_token
$html_options->{"csrf_token"} $self->view->csrf_token
Truth table0%0/3
A ||= B
A= $html_options->{"csrf_token"}B= $self->view->csrf_token
ABresult
1X1
011
000
226 11 ▶ $html_options->{csrf_token} ||= $self->context->csrf_token if $self->has_context && $self->context->can('csrf_token');
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_context and $self->context->can("csrf_token") 0 11 11
Condition16%1/6
$self->has_context and $self->context->can("csrf_token")
!ll&&!rl&&r
1100
$html_options->{"csrf_token"} ||= $self->context->csrf_token
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->has_context and $self->context->can("csrf_token")
$self->has_context $self->context->can("csrf_token")
MC/DC0%0/2
$html_options->{"csrf_token"} ||= $self->context->csrf_token
$html_options->{"csrf_token"} $self->context->csrf_token
Truth table33%1/3
A and B
A= $self->has_contextB= $self->context->can("csrf_token")
ABresult
0X0
100
111
Truth table0%0/3
A ||= B
A= $html_options->{"csrf_token"}B= $self->context->csrf_token
ABresult
1X1
011
000
227 11 ▶ $html_options->{tunneled_method} = 1 unless exists $html_options->{tunneled_method};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $html_options->{"tunneled_method"} 11 0 11
228 11 ▶ $html_options->{method} = lc($html_options->{method}||'post'); # most common standards specify lowercase
Condition100%2/2
$html_options->{'method'} || 'post'
l!l
74
MC/DC100%1/1
$html_options->{'method'} || 'post'
$html_options->{'method'}
Truth table100%2/2
A
A= $html_options->{'method'}
Aresult
11
00
229  
230 # This is what Rails does but not sure I want to force that. It might break a
231 # lot of existing code people try to shoehorn this stuff into.
232 # $html_options->{enctype} ||= $html_options->{method} eq 'get' ?
233 # 'application/x-www-form-urlencoded' :
234 # 'multipart/form-data';
235  
236 11 return $html_options;
237 }
238  
239 sub fields_for {
240 10 ▶ my $self = shift;
Subroutine fields_for: called CC=6 SCAR=17.9
Pod documented
241 10 my ($name, $model);
242 10 my $proto = shift;
243  
244 10 ▶ if( Scalar::Util::blessed $proto ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($proto)) { } 1 9 10
245 1 $model = $proto;
246 } else {
247 9 $name = $proto;
248 9 ▶ if( @_ && Scalar::Util::blessed($_[0]) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and builtin::blessed($_[0])) { } 7 2 9
Condition66%2/3
@_ and builtin::blessed($_[0])
!ll&&!rl&&r
027
MC/DC50%1/2
@_ and builtin::blessed($_[0])
@_ builtin::blessed($_[0])
Truth table66%2/3
A and B
A= @_B= builtin::blessed($_[0])
ABresult
0X0
100
111
249 7 $model = shift;
250 } else {
251 2 ▶ $model = $self->view->read_attribute_for_html($proto)
Branch: 1 branch
BranchTrueFalseTotal
if $self->view->attribute_exists_for_html($proto) 1 1 2
252 if $self->view->attribute_exists_for_html($proto);
253 }
254 }
255 10 my $block = pop @_;
256 10 ▶ my $options = @_ ? shift(@_) : +{};
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 5 5 10
257  
258 10 $options = {
259 model => $model,
260 allow_method_names_outside_object => 0,
261 skip_default_ids => 0,
262 %$options
263 };
264  
265 10 return $self->fields($name, $options, $block);
266 }
267  
268 sub _object_for_form_builder {
269 8 ▶ my ($self, $object) = @_;
Subroutine _object_for_form_builder: called CC=2 SCAR=8.1
270 8 ▶ return $object if Scalar::Util::blessed($object);
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($object) 8 0 8
271 ## in Rails this returns a single model object when $object is an arrayref
272 ## but I don't think that makes sense here at least for the moment.
273 0 die "Missing required object";
274 }
275  
276 sub fields {
277 10 ▶ my ($self, $scope, $options, $block) = @_;
Subroutine fields: called CC=4 SCAR=13.9
Pod undocumented
278  
279 $options = {
280 allow_method_names_outside_object => 1,
281 skip_default_ids => $self->form_with_generates_ids,
282 10 ▶ %{$options||+{}},
Branch: 1 branch
BranchTrueFalseTotal
$options or {} 0 10 10
283 };
284  
285 10 ▶ if ($options->{model}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"model"}) 8 2 10
286 8 my $model = $self->_to_model($self->_object_for_form_builder($options->{model}));
287 8 ▶ $scope ||= $self->_model_name_from_object_or_class($model)->param_key;
Condition66%2/3
$scope ||= $self->_model_name_from_object_or_class($model)->param_key
l!l&&r!l&&!r
710
MC/DC0%0/2
$scope ||= $self->_model_name_from_object_or_class($model)->param_key
$scope $self->_model_name_from_object_or_class($model)->param_key
Truth table66%2/3
A ||= B
A= $scopeB= $self->_model_name_from_object_or_class($model)->param_key
ABresult
1X1
011
000
288 }
289  
290 10 my $builder = $self->_instantiate_builder($scope, $options->{model}, $options);
291 10 my $output = $self->join_tags($block->($self->view, $builder));
292  
293 10 return $output;
294 }
295  
296 3 1;
297  
298 =head1 NAME
299  
300 Valiant::HTML::Util::Form - HTML Form
301  
302 =head1 SYNOPSIS
303  
304 Given a model like:
305  
306 package Person;
307  
308 use Moo;
309 use Valiant::Validations;
310  
311 has first_name => (is=>'ro');
312 has last_name => (is=>'ro');
313  
314 validates ['first_name', 'last_name'] => (
315 length => {
316 maximum => 20,
317 minimum => 3,
318 }
319 );
320  
321 Wrap a formbuilder object around it and generate HTML form field controls:
322  
323 use Valiant::HTML::Util::Form;
324  
325 my $f = Valiant::HTML::Util::Form->new()
326 my $person = Local::Person->new(first_name=>'J', last_name=>'Napiorkowski');
327 $person->validate;
328  
329 $f->form_for($person, sub($fb, $person) {
330 return $fb->label('first_name'),
331 $fb->input('first_name'),
332 $fb->errors_for('first_name', +{ class=>'invalid-feedback' }),
333 $fb->label('last_name'),
334 $fb->input('last_name'),
335 $fb->errors_for('last_name'+{ class=>'invalid-feedback' });
336 });
337  
338 Generates something like:
339  
340 <form accept-charset="UTF-8" class="new_person" enctype="multipart/form-data" id="new_person" method="post">
341 <label for="person_first_name">First Name</label>
342 <input id="person_first_name" name="person.first_name" type="text" value="John"/>
343 <div class='invalid-feedback'>First Name is too short (minimum is 3 characters).</div>
344 <label for="person_last_name">Last Name</label>
345 <input id="person_last_name" name="person.last_name" type="text" value="Napiorkowski"/>
346 </form>
347  
348 =head1 DESCRIPTION
349  
350 Builds on L<Valiant::HTML::Util::TagBuilder> and L<Valiant::HTML::Util::FormTags> to provide a
351 wrapper around a model object that can be used to generate HTML form controls via a formbuilder
352 such as L<Valliant::HTML::FormBuilder>. or a subclass thereof.
353  
354 Like its parent classes, you can provide a view context to the constructor and it will be used
355 to provide attribute values as well as methods used to create safe strings. This is documented
356 extensively in L<Valiant::HTML::Util::TagBuilder> which you should review if you are creating
357 your own view integration. You can see an example view context in L<Valiant::HTML::Util::View>.
358  
359 =head1 INHERITED METHODS
360  
361 This class inherits all methods from L<Valiant::HTML::Util::TagBuilder> and
362 L<Valiant::HTML::Util::FormTags>.
363  
364 =head1 REQUIRED MODEL API
365  
366 This (and L<Valiant::HTML::FormBuilder>) wrap an object model that is expected to do the following
367 interface.
368  
369 =head2 to_model
370  
371 This is an optional method. If this is supported, we call C<to_model> on the wrapped object
372 before using it on the form methods. This allows you to delegate the required API to a secondard
373 object, which can result in a cleaner API depending on your designs and use cases.
374  
375 =head2 in_storage
376  
377 This is an optional method. If your object has a backing storage solution (such as your object
378 is an instance of a DBIC Result Source) you can provide this method to influence how your object
379 form tags are created. If provided this method should return a boolean when if true means that
380 the object is representing data which is stored in the backing storage solution. Please note that
381 this does not mean that the object is synchronized with the backing storage since its possible that
382 the object has been changed by the user.
383  
384 =head2 is_attribute_changed
385  
386 $model->is_attribute_changed($attr); # true or false
387  
388 Optional method. If provided returns a boolean if the attribute has been changed from its initial state,
389 as defined by either being different from the backing store (if it exists) or being changed from its default
390 value when created as a new model.
391  
392 =head2 human_attribute_name
393  
394 $model->human_attribute_name('user'); # User
395  
396 Optional. If provided, uses the model to look up a displayable version of the attribute name, for
397 example used in a label for an input control. If not present we use L<Valiant::HTML::FormTags\_humanize>
398 to create a displayable name from the attribute name.
399  
400 =head2 read_attribute_for_html
401  
402 $model->read_attribute_for_html('user'); # User
403  
404 Optional. If provided must access the string name of the field or attribute and should return the model
405 value for that attribute suitable for HTML form display. You might wish to use this as a way to deflate
406 or otherwise stringify non string values. If not provided we just use the attribute name and call it as an
407 accessor against the model.
408  
409 =head2 errors
410  
411 Optional. Should return an instances of L<Valiant::Errors>. If present will be used to lookup model and
412 attribute errors.
413  
414 Please note this currently is tried to behavior expected from L<Valiant::Errors> but in the future
415 we might try to make this tied to a defined interface rather than this concrete class.
416  
417 =head2 has_errors
418  
419 Optional if you don't use builder methods that are for displaying errors; required otherwise. A boolean
420 that indicates if your model has errors or not. Used to determined if C<error_classes> are merged into
421 C<class> and in a few similar places.
422  
423 =head2 i18n
424  
425 Optional. If provided should return an instance of L<Valiant::I18N>. Used in a few places to support
426 translation tags.
427  
428 =head2 model_name
429  
430 Optional. If provide should return an instance of L<Valiant::Name>. Used in a few places where we
431 default a value to a human readable version of the model name. If you don't have this method we
432 fall back to guessing something based on the string name of the model.
433  
434 =head2 primary_columns
435  
436 Optional. When a model does C<in_storage> and its a nested model, when this method exists we use it to
437 get a list of primary columns for the underlying storage and then add them as hidden fields. This is
438 needed particularly with one - many style relationships so that we find the right record in the storage
439 model to update.
440  
441 B<NOTE>: This method requirement is subject to change. It feels a bit too tightly bound to the idea of
442 and ORM and to L<DBIx::Class> in particular.
443  
444 =head2 is_marked_for_deletion
445  
446 Optional, but should be supported if your model supports a storage backend. A boolean that indicates if
447 the model is currently marked for deletion upon successful validation. Used for things like radio
448 and checkbox collections when the state should be 'unchecked' even if the model is still in storage.
449  
450 =head1 INSTANCE METHODS
451  
452 The following public instance methods are provided by this class.
453  
454 =head2 form_for
455  
456 $f->form_for($name, $model, \%options, \&block);
457 $f->form_for($model, \%options, \&block);
458 $f->form_for($model, \&block);
459 $f->form_for($name, \%options, \&block);
460 $f->form_for($name, \&block);
461  
462 Canonical xample. C<$person> is either an object or the name of an attribute on the C<$view> that
463 will supply the object.
464  
465 $f->form_for($person, sub($fb, $person) {
466 return $fb->label('name'),
467 $fb->input('name');
468 });
469  
470 # Generates something like:
471  
472 <form accept-charset="UTF-8" class="new_person" enctype="multipart/form-data" id="new_person" method="post">
473 <label for="person_name">Name</label>
474 <input id="person_name" name="person.name" type="text" value="John"/>
475 </form>
476  
477 Given a model as described above, wrap a L<Valiant::HTML::FormBuilder> instance around it which
478 provides methods for generating valid HTML form output. This provides a view logic centered
479 method for creating sensible and reusable form controls which include server generated error
480 output from validation.
481  
482 See L<Valiant::HTML::FormBuilder> for more on the formbuilder API.
483  
484 C<\%options> are used to influence the builder creation as well as pass attributes to the
485 generated C<form> tag. Options are as follows:
486  
487 =over 4
488  
489 =item as
490  
491 Supplies the C<name> argument for L<Valiant::HTML::FormBuilder>. This is generally used
492 to set the top namespace for your field IDs and C<name> attributes.
493  
494 =item method
495  
496 Sets the form attribute C<method>. Generally defaults to C<post> or C<patch> (when C<in_storage>
497 is supported and the model is marked for updating of an existing model).
498  
499 =item action
500  
501 Should be the URL that the form with post to.
502  
503 =item data
504  
505 a hashref of HTML tag <data> attributes.
506  
507 =item class
508  
509 =item style
510  
511 HTML attributes that get merged into the C<html> options (below)
512  
513 =item html
514  
515 a hashref of items that will get rendered as HTML attributes for the form.
516  
517 =item namespace
518  
519 Optional. Can use used to prepend a namespace to your form IDs
520  
521 =item index
522  
523 Optional. When processing a collection model this will be the index of the current
524 model.
525  
526 =item builder
527  
528 The form builder. Defaults to L<Valiant::HTML::FormBuilder>. You can set this if you
529 create your own formbuilder subclass and want to use that. If you don't provide a value
530 we also check the attached view object for a C<formbuilder_class> method and use that if it
531 exists.
532  
533 =item csrf_token
534  
535 Optional. If provided, will be used to generate a hidden field with the name C<csrf_token>.
536 This is useful for CSRF protection. If you don't provide a value we will try to use the
537 C<csrf_token> method on the current view object. If that doesn't exist we will try to use
538 the C<csrf_token> method on the current context object (if one exists). If you are using
539 L<Catalyst> with this you can use L<Catalyst::Plugin::CSRFToken> to generate a token.
540  
541 =back
542  
543 The last argument should be a reference to a subroute that will receive the created formbuilder
544 object and should return a string, or array of strings that will be flattened and displayed as
545 your form elements. Any strings returns not marked as C<safe> via L<Valiant::HTML::SafeString> will
546 be encoded and turned safe so be sure to mark any raw strings correctly unless you want double
547 encoding issues.
548  
549 You can also provide a string as the first argument to this method and it will be used to set the
550 overall scope of the formbuilder. This is useful if you want to use the same formbuilder for
551 multiple models. For example:
552  
553 $f->form_for('person', sub($fb, $person) {
554 $fb->input('name');
555 });
556  
557 $f->form_for('address', sub($fb, $address) {
558 $fb->input('street');
559 });
560  
561 # Generates something like:
562  
563 <form accept-charset="UTF-8" class="new_person" enctype="multipart/form-data" id="new_person" method="post">
564 <input id="person_name" name="person.name" type="text" value="John"/>
565 </form>
566  
567 <form accept-charset="UTF-8" class="new_address" enctype="multipart/form-data" id="new_address" method="post">
568 <input id="address_street" name="address.street" type="text" value="123 Main St"/>
569 </form>
570  
571 If the string name refers to an attribute on the current view object that attribute will be used
572 to provide model data. Lastly you can pass both a string name and a model object and the string
573 name will be used to set the scope of the formbuilder and the model object will be used to provide
574 the model data.
575  
576 Example:
577  
578 $f->form_for('foo', $person, sub($fb, $person) {
579 return $fb->label('name'),
580 $fb->input('name');
581 });
582  
583 # Generates something like:
584  
585 <form accept-charset="UTF-8" class="new_foo" enctype="multipart/form-data" id="new_foo" method="post">
586 <label for="foo_name">Name</label>
587 <input id="foo_name" name="foo.name" type="text" value="John"/>
588 </form>
589  
590 =head2 fields_for
591  
592 $f->fields_for($name, $model, \%options, \&block);
593 $f->fields_for($model, \%options, \&block);
594 $f->fields_for($model, \&block);
595 $f->fields_for($name, \%options, \&block);
596 $f->fields_for($name, \&block);
597  
598 Create an instance of a formbuilder that represents a model or a namespace in which to build
599 form elements. Its basically <form_for> without the C<form> tag. This is useful for building
600 nested forms or for building forms that are not the top level form.
601  
602 Examples:
603  
604 $f->fields_for($person, sub {
605 my ($fb) = @_;
606 return $fb->input('first_name'),
607 });
608  
609 # <input id="person_first_name" name="person.first_name" type="text" value="aa"/>
610  
611 # Assume that the view has a $person attribute
612 $f->fields_for('person', sub {
613 my ($fb) = @_;
614 return $fb->input('first_name'),
615 });
616  
617 # <input id="person_first_name" name="person.first_name" type="text" value="aa"/>
618  
619 $f->fields_for('foo', $person, sub {
620 my ($fb) = @_;
621 return $fb->input('first_name'),
622 });
623  
624 # <input id="foo_first_name" name="foo.first_name" type="text" value="aa"/>
625  
626 # In this case there is no model for the values or errors, we're just using the
627 # formbuilder to generate the correct names and ids for an empty form.
628  
629 $f->fields_for('foo', sub {
630 my ($fb) = @_;
631 return $fb->input('first_name'),
632 });
633  
634 # <input id="foo_first_name" name="foo.first_name" type="text" value=""/>
635 }
636  
637 done_testing;
638  
639 =head1 SEE ALSO
640
641 L<Valiant>, L<Valiant::HTML::FormBuilder>, L<Valiant::HTML::Util::FormTags>
642  
643 =head1 AUTHOR
644
645 See L<Valiant>
646  
647 =head1 COPYRIGHT & LICENSE
648
649 See L<Valiant>
650  
651 =cut
« Valiant/I18N.pm ↑ Summary DBIx/Class/Valiant/Validator/Result.pm »