Jifty/Action.pm

filter: Statementstmt 5.0% 15 / 300 Branchbran 0.0% 0 / 114 Conditioncond 0.0% 0 / 85 MC/DCmcdc 0.0% 0 / 50 Subroutinesub 8.0% 4 / 50 Podpod 100% 32 / 32 totaltotal 8.0% 51 / 631 CC 96 SCAR 43.9
CC
96
Cov
3%
_validate_argument
306.0
_form_widget
182.0
new
132.0
CRAP 80.4
« Jifty/Script/Adopt.pm ↑ Summary Jifty/Web/Form/Field/Checkboxes.pm »
1 113 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 113 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 package Jifty::Action;
5  
6 =head1 NAME
7  
8 Jifty::Action - The ability to Do Things in the framework
9  
10 =head1 SYNOPSIS
11  
12 package MyApp::Action::Foo;
13 use Jifty::Param::Schema;
14 use Jifty::Action schema {
15  
16 param bar =>
17 type is 'checkbox',
18 label is 'Want Bar?',
19 hints is 'Bar is this cool thing that you really want.',
20 default is 0;
21  
22 };
23
24 sub take_action {
25 ...
26 }
27
28 1;
29  
30 =head1 DESCRIPTION
31  
32 C<Jifty::Action> is the superclass for all actions in Jifty.
33 Action classes form the meat of the L<Jifty> framework; they
34 control how form elements interact with the underlying model.
35  
36 See also L<Jifty::Action::Record> for data-oriented actions,
37 L<Jifty::Result> for how to return values from actions.
38  
39 See L<Jifty::Param::Schema> for more details on the declarative
40 syntax.
41  
42 See L<Jifty::Manual::Actions> for examples of using actions.
43  
44 =cut
45  
46  
47 113 ▶use base qw/Jifty::Object Class::Accessor::Fast Class::Data::Inheritable/;
Subroutine BEGIN: called CC=1 SCAR=0.0
48  
49 113 __PACKAGE__->mk_accessors(qw(moniker argument_values values_from_request order result sticky_on_success sticky_on_failure));
50 113 __PACKAGE__->mk_classdata(qw/PARAMS/);
51  
52 =head1 COMMON METHODS
53  
54 These common methods provide the basic guts for the action.
55  
56 =head2 new
57  
58 B<Do not call this directly>; always go through C<< Jifty->web->new_action >>!
59  
60 This method constructs a new action. Subclasses who need do custom
61 initialization should start with:
62  
63 my $class = shift;
64 my $self = $class->SUPER::new(@_)
65  
66 The arguments that this will be called with include:
67  
68 =head3 Arguments
69  
70 =over
71  
72 =item moniker
73  
74 The L<moniker|Jifty::Manual::Glossary/moniker> of the action. Defaults to an
75 autogenerated moniker.
76  
77 =item order
78  
79 An integer that determines the ordering of the action's execution.
80 Lower numbers occur before higher numbers. Defaults to 0.
81  
82 =item arguments
83  
84 A hash reference of default values for the
85 L<arguments|Jifty::Manual::Glossary/argument> of the action. Defaults
86 to none.
87  
88 =item sticky_on_failure
89  
90 A boolean value that determines if the form fields are
91 L<sticky|Jifty::Manual::Glossary/sticky> when the action fails.
92 Defaults to true.
93  
94 =item sticky_on_success
95  
96 A boolean value that determines if the form fields are
97 L<sticky|Jifty::Manual::Glossary/sticky> when the action succeeds.
98 Defaults to false.
99  
100 =back
101  
102 =cut
103  
104 0 ▶sub new {
Subroutine new: not called CC=11 SCAR=48.8
Pod documented
105 0 my $class = shift;
106 0 my $self = bless {}, $class;
107 0 my %args = (
108 order => undef,
109 arguments => {},
110 request_arguments => {},
111 sticky_on_success => 0,
112 sticky_on_failure => 1,
113 current_user => undef,
114 @_);
115  
116 # Setup current user according to parameter or pickup the actual
117 0 ▶ if ($args{'current_user'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'current_user'}) { } 0 0 0
118 0 $self->current_user($args{current_user});
119 } else {
120 0 $self->_get_current_user();
121 }
122  
123 # If given a moniker, validate/sanitize it
124 0 ▶ if ( $args{'moniker'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"moniker"}) 0 0 0
125  
126 # XXX Should this be pickier about sanitized monikers?
127  
128 # Monikers must not contain semi-colons
129 0 ▶ if ( $args{'moniker'} =~ /[\;]/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"moniker"} =~ /[\;]/) 0 0 0
130  
131 # Replace the semis with underscores and warn
132 0 $args{'moniker'} =~ s/[\;]/_/g;
133 0 $self->log->warn(
134 0 "Moniker @{[$args{'moniker'}]} contains invalid characters. It should not contain any ';' characters. "
135 . "It has been autocorrected, but you should correct your code"
136 );
137 }
138  
139 # Monikers must not start with a digit
140 0 ▶ if ( $args{'moniker'} =~ /^\d/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"moniker"} =~ /^\d/) 0 0 0
141  
142 # Stick "fixup-" to the front and warn
143 0 $args{'moniker'} = "fixup-" . $args{'moniker'};
144 0 $self->log->warn(
145 0 "Moniker @{[$args{'moniker'}]} contains invalid characters. It can not begin with a digit. "
146 . "It has been autocorrected, but you should correct your code"
147 );
148  
149 }
150 }
151  
152 # Setup the moniker and run order
153 0 ▶ $self->moniker($args{'moniker'} || $self->_generate_moniker);
Condition0%0/3
$args{'moniker'} || $self->_generate_moniker
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'moniker'} || $self->_generate_moniker
$args{'moniker'} $self->_generate_moniker
Truth table0%0/3
A || B
A= $args{'moniker'}B= $self->_generate_moniker
ABresult
1X1
011
000
154 0 $self->order($args{'order'});
155  
156 # Fetch any arguments from a passed in request
157 0 my $action_in_request = Jifty->web->request->action( $self->moniker );
158 0 ▶ if ( $action_in_request and $action_in_request->arguments ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($action_in_request and $action_in_request->arguments) 0 0 0
Condition0%0/3
$action_in_request and $action_in_request->arguments
!ll&&!rl&&r
000
MC/DC0%0/2
$action_in_request and $action_in_request->arguments
$action_in_request $action_in_request->arguments
Truth table0%0/3
A and B
A= $action_in_requestB= $action_in_request->arguments
ABresult
0X0
100
111
159 0 $args{'request_arguments'} = $action_in_request->arguments;
160 }
161  
162 # Setup the argument values with the new_action arguments taking precedent
163 0 $self->argument_values( { %{ $args{'request_arguments' } }, %{ $args{'arguments'} } } );
164  
165 # Track how an argument was set, again new_action args taking precedent
166 0 $self->values_from_request({});
167 0 $self->values_from_request->{$_} = 1 for keys %{ $args{'request_arguments' } };
168 0 $self->values_from_request->{$_} = 0 for keys %{ $args{'arguments' } };
169
170 # Place this actions result in the response result if already processed
171 0 ▶ $self->result(Jifty->web->response->result($self->moniker) || Jifty::Result->new);
Condition0%0/3
'Jifty'->web->response->result($self->moniker) || 'Jifty::Result'->new
l!l&&r!l&&!r
000
MC/DC0%0/2
'Jifty'->web->response->result($self->moniker) || 'Jifty::Result'->new
'Jifty'->web->response->result($self->moniker) 'Jifty::Result'->new
Truth table0%0/3
A || B
A= 'Jifty'->web->response->result($self->moniker)B= 'Jifty::Result'->new
ABresult
1X1
011
000
172 0 $self->result->action_class(ref($self));
173  
174 # Remember stickiness
175 0 $self->sticky_on_success($args{sticky_on_success});
176 0 $self->sticky_on_failure($args{sticky_on_failure});
177  
178 0 return $self;
179 }
180  
181 =head2 _generate_moniker
182  
183 Construct a moniker for a new (or soon-to-be-constructed) action that
184 did not have an explicit moniker specified. The algorithm is simple:
185 We snapshot the call stack, prefix it with the action class, and then
186 append it with an per-request autoincrement counter in case the same
187 class/stack is encountered twice, which can happen if the programmer
188 placed a C<new_action> call inside a loop.
189  
190 Monikers generated this way are guaranteed to work across requests.
191  
192 =cut
193  
194 0 ▶sub _generate_moniker {
Subroutine _generate_moniker: not called CC=4 SCAR=26.3
195 0 my $self = shift;
196  
197 # We use Digest::MD5 to generate the moniker
198 113 ▶ use Digest::MD5 qw(md5_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
199  
200 # Use information from the call stack as the data for the digest
201 0 my $frame = 1;
202 0 ▶ my @stack = (ref($self) || $self);
Condition0%0/3
ref $self || $self
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table0%0/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
203 0 ▶ while (my ($pkg, $filename, $line) = caller($frame++)) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = caller $frame++) 0 0 0
204 0 push @stack, $pkg, $filename, $line;
205 }
206  
207 # Generate the digest that forms the basis of the auto-moniker
208 0 my $digest = md5_hex("@stack");
209  
210 # Increment the per-request moniker digest counter, for the case of looped action generation
211 # We should always have a stash. but if we don't, fake something up
212 # (some hiveminder tests create actions outside of a Jifty::Web)
213 # Multiple things happening here that need to be noted:
214 #
215 # 1. We have a per-request moniker digest counter, which handles the
216 # highly unlikely circumstance that the same digest were hit twice
217 # within the same request.
218 #
219 # 2. We should always have a stash, but sometimes we don't. (Specifically,
220 # some Hiveminder tests create actions outside of a Jifty::Web, which
221 # don't.) In that case, add more random data at the end and cross our
222 # fingers that we don't hit that one in a billion (or actually one in a
223 # significantly larger than a billion odds here).
224  
225 # Create a serial number that prevents collisions within a request
226 my $serial = Jifty->handler->stash
227 0 ▶ ? ++(Jifty->handler->stash->{monikers}{$digest})
Branch: 1 branch
BranchTrueFalseTotal
'Jifty'->handler->stash ? : 0 0 0
228 : rand();
229  
230 # Build the actual moniker from digest + serial
231 0 my $moniker = "auto-$digest-$serial";
232 0 $self->log->debug("Generating moniker $moniker from stack for $self");
233  
234 0 return $moniker;
235 }
236  
237 =head2 arguments
238  
239 B<Note>: this API is now deprecated in favour of the declarative syntax
240 offered by L<Jifty::Param::Schema>.
241  
242 This method, along with L</take_action>, is the most commonly
243 overridden method. It should return a hash which describes the
244 L<arguments|Jifty::Manual::Glossary/argument> this action takes:
245  
246 {
247 argument_name => {label => "properties go in this hash"},
248 another_argument => {mandatory => 1}
249 }
250  
251 Each argument listed in the hash will be turned into a
252 L<Jifty::Web::Form::Field> object. For each argument, the hash that
253 describes it is used to set up the L<Jifty::Web::Form::Field> object by
254 calling the keys as methods with the values as arguments. That is, in
255 the above example, Jifty will run code similar to the following:
256  
257 # For 'argument_name'
258 $f = Jifty::Web::Form::Field->new;
259 $f->name( "argument_name" );
260 $f->label( "Properties go in this hash" );
261  
262 If an action has parameters that B<must> be passed to it to execute,
263 these should have the L<constructor|Jifty::Manual::Glossary/constructor>
264 property set. This is separate from the
265 L<mandatory|Jifty::Manual::Glossary/mandatory> property, which deal with
266 requiring that the user enter a value for that field.
267  
268  
269 =cut
270  
271 0 ▶sub arguments {
Subroutine arguments: not called CC=2 SCAR=17.9
Pod documented
272 0 my $self= shift;
273 0 ▶ return($self->PARAMS || {});
Condition0%0/2
$self->PARAMS || {}
l!l
00
MC/DC0%0/1
$self->PARAMS || {}
$self->PARAMS
Truth table0%0/2
A
A= $self->PARAMS
Aresult
11
00
274 }
275  
276 =head2 run
277  
278 This routine, unsurprisingly, actually runs the action.
279  
280 If the result of the action is currently a success (validation did not
281 fail), C<run> calls L</take_action>, and finally L</cleanup>.
282  
283 If you're writing your own actions, you probably want to override
284 C<take_action> instead.
285  
286 =cut
287  
288 0 ▶sub run {
Subroutine run: not called CC=5 SCAR=34.0
Pod documented
289 0 my $self = shift;
290 0 $self->log->debug("Running action ".ref($self) . " " .$self->moniker);
291  
292 # We've already had a validation failure. STOP!
293 0 ▶ unless ($self->result->success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->result->success) 0 0 0
294 0 $self->log->debug("Not taking action, as it doesn't validate");
295  
296 # dump field warnings and errors to debug log
297 0 foreach my $what (qw/warnings errors/) {
298 0 my $f = "field_" . $what;
299 my @r =
300 map {
301 0 $_ . ": " . $self->result->{$f}->{$_}
302 0 } grep { $self->result->{$f}->{$_} }
303 0 keys %{ $self->result->{$f} };
304 0 ▶ $self->log->debug("Action result $what:\n\t", join("\n\t", @r)) if (@r);
Branch: 1 branch
BranchTrueFalseTotal
if @r 0 0 0
305 }
306  
307 0 return;
308 }
309  
310 # Made it past validation, continue...
311 0 $self->log->debug("Taking action ".ref($self) . " " .$self->moniker);
312  
313 # Take the action (user-defined)
314 0 my $ret = $self->take_action;
315 0 ▶ $self->log->debug("Result: ".(defined $ret ? $ret : "(undef)"));
Branch: 1 branch
BranchTrueFalseTotal
defined $ret ? : 0 0 0
316
317 # Perform post action clean-up (user-defined)
318 0 $self->cleanup;
319 }
320  
321 =head2 validate
322  
323 Checks authorization with L</check_authorization>, calls C</setup>,
324 canonicalizes and validates each argument that was submitted, but
325 doesn't actually call L</take_action>.
326  
327 The outcome of all of this is stored on the L</result> of the action.
328  
329 =cut
330  
331 0 ▶sub validate {
Subroutine validate: not called CC=3 SCAR=24.8
Pod documented
332 0 my $self = shift;
333 0 ▶ $self->check_authorization || return;
Branch: 1 branch
BranchTrueFalseTotal
$self->check_authorization or return 0 0 0
334 0 ▶ $self->setup || return;
Branch: 1 branch
BranchTrueFalseTotal
$self->setup or return 0 0 0
335 0 $self->_canonicalize_arguments;
336 0 $self->_validate_arguments;
337 }
338  
339 =head2 check_authorization
340  
341 Returns true if whoever invoked this action is authorized to perform
342 this action.
343  
344 By default, always returns true.
345  
346 =cut
347  
348 0 ▶sub check_authorization { 1; }
Subroutine check_authorization: not called CC=1 SCAR=6.9
Pod documented
349  
350 =head2 setup
351  
352 C<setup> is expected to return a true value, or
353 L</run> will skip all other actions.
354  
355 By default, does nothing.
356  
357 =cut
358  
359 0 ▶sub setup { 1; }
Subroutine setup: not called CC=1 SCAR=6.9
Pod documented
360  
361 =head2 take_action
362  
363 Do whatever the action is supposed to do. This and
364 L</arguments> are the most commonly overridden methods.
365  
366 By default, does nothing.
367  
368 The return value from this method is NOT returned. (Instead, you
369 should be using the L</result> object to store a result).
370  
371 =cut
372  
373 0 ▶sub take_action { 1; }
Subroutine take_action: not called CC=1 SCAR=6.9
Pod documented
374  
375 =head2 cleanup
376  
377 Perform any action-specific cleanup. By default, does nothing.
378  
379 Runs after L</take_action> -- whether or not L</take_action> returns success.
380  
381 =cut
382  
383 0 ▶sub cleanup { 1; }
Subroutine cleanup: not called CC=1 SCAR=6.9
Pod documented
384  
385 =head2 moniker
386  
387 Returns the L<moniker|Jifty::Manual::Glossary/moniker> for this action.
388  
389 =head2 argument_value ARGUMENT [VALUE]
390  
391 Returns the value from the argument with the given name, for this
392 action. If I<VALUE> is provided, sets the value.
393  
394 =cut
395  
396 0 ▶sub argument_value {
Subroutine argument_value: not called CC=2 SCAR=17.9
Pod documented
397 0 my $self = shift;
398 0 my $arg = shift;
399  
400 # Not only get it, but set it
401 0 ▶ if(@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 0 0
402 0 $self->values_from_request->{$arg} = 0;
403 0 $self->argument_values->{$arg} = shift;
404 }
405  
406 # Get it
407 0 return $self->argument_values->{$arg};
408 }
409  
410 =head2 has_argument ARGUMENT
411  
412 Returns true if the action has been provided with an value for the
413 given argument, including a default_value, and false if none was ever
414 passed in.
415  
416 =cut
417  
418 0 ▶sub has_argument {
Subroutine has_argument: not called CC=1 SCAR=6.9
Pod documented
419 0 my $self = shift;
420 0 my $arg = shift;
421  
422 0 return exists $self->argument_values->{$arg};
423 }
424  
425 =head2 form_field ARGUMENT
426  
427 Returns a L<Jifty::Web::Form::Field> object for this argument. If
428 there is no entry in the L</arguments> hash that matches the given
429 C<ARGUMENT>, returns C<undef>.
430  
431 =cut
432  
433 0 ▶sub form_field {
Subroutine form_field: not called CC=3 SCAR=24.8
Pod documented
434 0 my $self = shift;
435 0 my $arg_name = shift;
436  
437 # Determine whether we want reads or write on this field
438 0 my $mode = $self->arguments->{$arg_name}{'render_mode'};
439 0 ▶ $mode = 'update' unless $mode && $mode eq 'read';
Branch: 1 branch
BranchTrueFalseTotal
unless $mode and $mode eq "read" 0 0 0
Condition0%0/3
$mode and $mode eq "read"
!ll&&!rl&&r
000
MC/DC0%0/2
$mode and $mode eq "read"
$mode $mode eq "read"
Truth table0%0/3
A and B
A= $modeB= $mode eq "read"
ABresult
0X0
100
111
440  
441 # Return the widget
442 0 $self->_form_widget( argument => $arg_name,
443 render_mode => $mode,
444 @_);
445 }
446  
447  
448 =head2 form_value ARGUMENT
449  
450 Returns a L<Jifty::Web::Form::Field> object that renders a display
451 value instead of an editable widget for this argument. If there is no
452 entry in the L</arguments> hash that matches the given C<ARGUMENT>,
453 returns C<undef>.
454  
455 =cut
456  
457 0 ▶sub form_value {
Subroutine form_value: not called CC=1 SCAR=6.9
Pod documented
458 0 my $self = shift;
459 0 my $arg_name = shift;
460  
461 # Return the widget, but in read mode
462 0 $self->_form_widget( argument => $arg_name,
463 render_mode => 'read',
464 @_);
465  
466 }
467  
468 # Generalized helper for the two above
469 0 ▶sub _form_widget {
Subroutine _form_widget: not called CC=13 SCAR=52.0
470 0 my $self = shift;
471 0 my %args = (
472 argument => undef,
473 render_mode => 'update',
474 @_,
475 );
476 my $cache_key = join '!!',
477 0 ▶ map { $_ => defined $args{$_} ? $args{$_} : '' } keys %args;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{$_} ? : 0 0 0
478  
479 # Setup the field name
480 0 my $field = $args{'argument'};
481  
482 # This particular field hasn't been added to the form yet
483 0 ▶ if ( not exists $self->{_private_form_fields_hash}{$cache_key} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"_private_form_fields_hash"}{$cache_key}) 0 0 0
484 0 my $field_info = $self->arguments->{$field};
485 # The field name is not known by this action
486 0 ▶ unless ($field_info) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($field_info) 0 0 0
487 0 local $Log::Log4perl::caller_depth += 2;
488 0 $self->log->warn("$field isn't a valid field for $self");
489 0 return;
490 }
491 # It is in fact a form field for this action
492  
493 0 my $sticky = 0;
494 # $sticky can be overridden per-parameter
495 0 ▶ if ( defined $field_info->{sticky} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $field_info->{'sticky'}) { } 0 0 0
elsif ('Jifty'->web->response->result($self->moniker)) { } 0 0 0
496 0 $sticky = $field_info->{sticky};
497 }
498 # Check stickiness if the values came from the request
499 elsif (Jifty->web->response->result($self->moniker)) {
500 0 ▶ $sticky = 1 if $self->sticky_on_failure and $self->result->failure;
Branch: 1 branch
BranchTrueFalseTotal
if $self->sticky_on_failure and $self->result->failure 0 0 0
Condition0%0/3
$self->sticky_on_failure and $self->result->failure
!ll&&!rl&&r
000
MC/DC0%0/2
$self->sticky_on_failure and $self->result->failure
$self->sticky_on_failure $self->result->failure
Truth table0%0/3
A and B
A= $self->sticky_on_failureB= $self->result->failure
ABresult
0X0
100
111
501 0 ▶ $sticky = 1 if $self->sticky_on_success and $self->result->success;
Branch: 1 branch
BranchTrueFalseTotal
if $self->sticky_on_success and $self->result->success 0 0 0
Condition0%0/3
$self->sticky_on_success and $self->result->success
!ll&&!rl&&r
000
MC/DC0%0/2
$self->sticky_on_success and $self->result->success
$self->sticky_on_success $self->result->success
Truth table0%0/3
A and B
A= $self->sticky_on_successB= $self->result->success
ABresult
0X0
100
111
502 }
503  
504  
505 # form_fields overrides stickiness of what the user last entered.
506 0 my $default_value;
507 $default_value = $field_info->{'default_value'}
508 0 ▶ if exists $field_info->{'default_value'};
Branch: 1 branch
BranchTrueFalseTotal
if exists $field_info->{"default_value"} 0 0 0
509 $default_value = $self->argument_value($field)
510 0 ▶ if $self->has_argument($field) && !$self->values_from_request->{$field};
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_argument($field) and not $self->values_from_request->{$field} 0 0 0
Condition0%0/3
$self->has_argument($field) and not $self->values_from_request->{$field}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->has_argument($field) and not $self->values_from_request->{$field}
$self->has_argument($field) not $self->values_from_request->{$field}
Truth table0%0/3
A and not(B)
A= $self->has_argument($field)B= not $self->values_from_request->{$field}
ABresult
0X0
100
111
511  
512 my %field_args = (
513 %$field_info,
514 action => $self,
515 name => $field,
516 sticky => $sticky,
517 sticky_value => $self->argument_value($field),
518 default_value => $default_value,
519 0 render_mode => $args{'render_mode'},
520 %args,
521 );
522  
523 # Add the form field to the cache
524 0 $self->{_private_form_fields_hash}{$cache_key}
525 = Jifty::Web::Form::Field->new(%field_args);
526 }
527  
528 0 return $self->{_private_form_fields_hash}{$cache_key};
529 }
530  
531 =head2 hidden ARGUMENT VALUE
532  
533 A shortcut for specifying a form field C<ARGUMENT> which should render
534 as a hidden form field, with the default value C<VALUE>.
535  
536 =cut
537  
538 0 ▶sub hidden {
Subroutine hidden: not called CC=1 SCAR=6.9
Pod documented
539 0 my $self = shift;
540 0 my ($arg, $value, @other) = @_;
541  
542 # Return the control as a hidden widget
543 0 $self->form_field( $arg, render_as => 'hidden', default_value => $value, @other);
544 }
545  
546 =head2 order [INTEGER]
547  
548 Gets or sets the order that the action will be run in. This should be
549 an integer, with lower numbers being run first. Defaults to zero.
550  
551 =head2 result [RESULT]
552  
553 Returns the L<Jifty::Result> method associated with this action. If
554 an action with the same moniker existed in the B<last> request, then
555 this contains the results of that action.
556  
557 =head2 register
558  
559 Registers this action as being present, by outputting a snippet of
560 HTML. This expects that an HTML form has already been opened. Note
561 that this is not a guarantee that the action will be run, even if the
562 form is submitted. See L<Jifty::Request> for the definition of
563 "L<active|Jifty::Manual::Glossary/active>" actions.
564  
565 Normally, L<Jifty::Web/new_action> takes care of calling this when it
566 is needed.
567  
568 =cut
569  
570 0 ▶sub register {
Subroutine register: not called CC=4 SCAR=30.0
Pod documented
571 0 my $self = shift;
572  
573 # Add information about the action to the form
574 0 Jifty->web->out( qq!<div class="hidden"><input type="hidden"! .
575 0 qq! name="@{[$self->register_name]}"! .
576 0 qq! id="@{[$self->register_name]}"! .
577 0 qq! value="@{[ref($self)]}"! .
578 qq! /></div>\n! );
579  
580 # Add all the default values as hidden fields to the form
581 0 my %args = %{$self->arguments};
582 0 ▶ while ( my ( $name, $info ) = each %args ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %args) 0 0 0
583 0 ▶ next unless $info->{'constructor'};
Branch: 1 branch
BranchTrueFalseTotal
unless $info->{"constructor"} 0 0 0
584 Jifty::Web::Form::Field->new(
585 %$info,
586 action => $self,
587 input_name => $self->fallback_form_field_name($name),
588 sticky => 0,
589 0 ▶ default_value => ($self->argument_value($name) || $info->{'default_value'}),
Condition0%0/3
$self->argument_value($name) || $info->{'default_value'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->argument_value($name) || $info->{'default_value'}
$self->argument_value($name) $info->{'default_value'}
Truth table0%0/3
A || B
A= $self->argument_value($name)B= $info->{'default_value'}
ABresult
1X1
011
000
590 render_as => 'Hidden'
591 )->render();
592 }
593  
594 0 return '';
595 }
596  
597 =head2 render_errors
598  
599 Render any the L<Jifty::Result/error> of this action, if any, as HTML.
600 Returns nothing.
601  
602 =cut
603  
604 0 ▶sub render_errors {
Subroutine render_errors: not called CC=2 SCAR=17.9
Pod documented
605 0 my $self = shift;
606
607 # Render the span that contians errors
608 0 ▶ if (defined $self->result->error) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->result->error) 0 0 0
609 # XXX TODO FIXME escape?
610 0 Jifty->web->out( '<div class="form_errors">'
611 . '<span class="error">'
612 . $self->result->error
613 . '</span>'
614 . '</div>' );
615 }
616 0 return '';
617 }
618  
619 =head2 button arguments => { KEY => VALUE }, PARAMHASH
620  
621 Create and render a button. It functions nearly identically like
622 L<Jifty::Web/link>, except it takes C<arguments> in addition to
623 C<parameters>, and defaults to submitting this L<Jifty::Action>.
624 Returns nothing.
625  
626 Recommended reading: L<Jifty::Web::Form::Element>, where most of
627 the cool options to button and other things of its ilk are documented.
628  
629 =cut
630  
631 0 ▶sub button {
Subroutine button: not called CC=3 SCAR=24.8
Pod documented
632 0 my $self = shift;
633 0 my %args = ( arguments => {},
634 submit => $self,
635 register => 0,
636 @_);
637  
638 # The user has asked to register the action while we're at it
639 0 ▶ if ($args{register}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"register"}) 0 0 0
640  
641 # If they ask us to register the action, do so
642 0 Jifty->web->form->register_action( $self );
643 0 Jifty->web->form->print_action_registration($self->moniker);
644 }
645
646 # Add whatever additional arguments they've requested to the button
647 $args{parameters}{$self->form_field_name($_)} = $args{arguments}{$_}
648 0 for keys %{$args{arguments}};
649  
650 # Render us a button
651 0 Jifty->web->link(%args);
652 }
653  
654 =head3 return PARAMHASH
655  
656 Creates and renders a button, like L</button>, which additionally
657 defaults to calling the current continuation.
658  
659 Takes an additional argument, C<to>, which can specify a default path
660 to return to if there is no current continuation.
661  
662 =cut
663  
664 0 ▶sub return {
Subroutine return: not called CC=3 SCAR=24.8
Pod documented
665 0 my $self = shift;
666 0 my %args = (@_);
667  
668 # Fetch the current continuation or build a new one
669 0 my $continuation = Jifty->web->request->continuation;
670 0 ▶ if (not $continuation and $args{to}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $continuation and $args{"to"}) 0 0 0
Condition0%0/3
not $continuation and $args{"to"}
!ll&&!rl&&r
000
MC/DC0%0/2
not $continuation and $args{"to"}
not $continuation $args{"to"}
Truth table0%0/3
not(A) and B
A= not $continuationB= $args{"to"}
ABresult
0X0
100
111
671 0 $continuation = Jifty::Continuation->new(request => Jifty::Request->new(path => $args{to}));
672 }
673 0 delete $args{to};
674  
675 # Render a button that will call the continuation
676 0 $self->button( call => $continuation, %args );
677 }
678  
679 =head1 NAMING METHODS
680  
681 These methods return the names of HTML form elements related to this
682 action.
683  
684 =head2 register_name
685  
686 Returns the name of the "registration" query argument for this action
687 in a web form.
688  
689 =cut
690  
691 0 ▶sub register_name {
Subroutine register_name: not called CC=2 SCAR=17.9
Pod documented
692 0 my $self = shift;
693 0 ▶ return 'J:A-' . (defined $self->order ? $self->order . "-" : "") .$self->moniker;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->order ? : 0 0 0
694 }
695  
696 # prefixes a fieldname with a given prefix and follows it with the moniker
697 0 ▶sub _prefix_field {
Subroutine _prefix_field: not called CC=1 SCAR=6.9
698 0 my $self = shift;
699 0 my ($field_name, $prefix) = @_;
700 0 return join("-", $prefix, $field_name, $self->moniker);
701 }
702  
703 =head2 form_field_name ARGUMENT
704  
705 Turn one of this action's L<arguments|Jifty::Manual::Glossary/arguments> into
706 a fully qualified name; takes the name of the field as an argument.
707  
708 =cut
709  
710 0 ▶sub form_field_name {
Subroutine form_field_name: not called CC=1 SCAR=6.9
Pod documented
711 0 my $self = shift;
712 0 return $self->_prefix_field(shift, "J:A:F");
713 }
714  
715 =head2 fallback_form_field_name ARGUMENT
716  
717 Turn one of this action's L<arguments|Jifty::Manual::Glossary/arguments> into
718 a fully qualified "fallback" name; takes the name of the field as an
719 argument.
720  
721 This is specifically to support checkboxes, which only show up in the
722 query string if they are checked. Jifty creates a checkbox with the
723 value of L<form_field_name> as its name and a value of 1, and a hidden
724 input with the value of L<fallback_form_field_name> as its name and a
725 value of 0; using this information, L<Jifty::Request> can both
726 determine if the checkbox was present at all in the form, as well as
727 its true value.
728  
729 =cut
730  
731 0 ▶sub fallback_form_field_name {
Subroutine fallback_form_field_name: not called CC=1 SCAR=6.9
Pod documented
732 0 my $self = shift;
733 0 return $self->_prefix_field(shift, "J:A:F:F");
734 }
735  
736 =head2 error_div_id ARGUMENT
737  
738 Turn one of this action's L<arguments|Jifty::Manual::Glossary/arguments> into
739 the id for the div in which its errors live; takes name of the field
740 as an argument.
741  
742 =cut
743  
744 0 ▶sub error_div_id {
Subroutine error_div_id: not called CC=1 SCAR=6.9
Pod documented
745 0 my $self = shift;
746 0 my $field_name = shift;
747 0 return 'errors-' . $self->form_field_name($field_name);
748 }
749  
750 =head2 warning_div_id ARGUMENT
751  
752 Turn one of this action's L<arguments|Jifty::Manual::Glossary/arguments> into
753 the id for the div in which its warnings live; takes name of the field
754 as an argument.
755  
756 =cut
757  
758 0 ▶sub warning_div_id {
Subroutine warning_div_id: not called CC=1 SCAR=6.9
Pod documented
759 0 my $self = shift;
760 0 my $field_name = shift;
761 0 return 'warnings-' . $self->form_field_name($field_name);
762 }
763  
764 =head2 canonicalization_note_div_id ARGUMENT
765  
766 Turn one of this action's L<arguments|Jifty::Manual::Glossary/arguments> into
767 the id for the div in which its canonicalization notes live; takes name of the field
768 as an argument.
769  
770 =cut
771  
772 0 ▶sub canonicalization_note_div_id {
Subroutine canonicalization_note_div_id: not called CC=1 SCAR=6.9
Pod documented
773 0 my $self = shift;
774 0 my $field_name = shift;
775 0 return 'canonicalization_note-' . $self->form_field_name($field_name);
776 }
777  
778 =head1 VALIDATION METHODS
779  
780 =head2 argument_names
781  
782 Returns the list of argument names. This information is extracted
783 from L</arguments>.
784  
785 =cut
786  
787 0 ▶sub argument_names {
Subroutine argument_names: not called CC=7 SCAR=40.3
Pod documented
788 0 my $self = shift;
789 0 my %arguments = %{ $self->arguments };
790 return (
791 sort {
792 0 (($arguments{$a}->{'sort_order'} ||0 ) <=> ($arguments{$b}->{'sort_order'} || 0))
793 0 ▶ || (($arguments{$a}->{'name'} || '') cmp ($arguments{$b}->{'name'} ||'' ))
Condition0%0/14
($arguments{$a}{'sort_order'} || 0) <=> ($arguments{$b}{'sort_order'} || 0) || ($arguments{$a}{'name'} || '') cmp ($arguments{$b}{'name'} || '') || $a cmp $b
l!l&&r!l&&!r
000
($arguments{$a}{"sort_order"} || 0) <=> ($arguments{$b}{"sort_order"} || 0) or ($arguments{$a}{"name"} || "") cmp ($arguments{$b}{"name"} || "")
l!l&&r!l&&!r
000
$arguments{$a}{'sort_order'} || 0
l!l
00
$arguments{$b}{'sort_order'} || 0
l!l
00
$arguments{$a}{'name'} || ''
l!l
00
$arguments{$b}{'name'} || ''
l!l
00
MC/DC0%0/3
($arguments{$a}{'sort_order'} || 0) <=> ($arguments{$b}{'sort_order'} || 0) || ($arguments{$a}{'name'} || '') cmp ($arguments{$b}{'name'} || '') || $a cmp $b
$arguments{$a}{'sort_order'} $arguments{$a}{'name'} $a cmp $b
MC/DC0%0/1
$arguments{$b}{'sort_order'} || 0
$arguments{$b}{'sort_order'}
MC/DC0%0/1
$arguments{$b}{'name'} || ''
$arguments{$b}{'name'}
Truth table0%0/4
A or B || C
A= $arguments{$a}{'sort_order'}B= $arguments{$a}{'name'}C= $a cmp $b
ABCresult
1XX1
01X1
0011
0000
Truth table0%0/2
A
A= $arguments{$b}{'sort_order'}
Aresult
11
00
Truth table0%0/2
A
A= $arguments{$b}{'name'}
Aresult
11
00
794 || $a cmp $b
795 } keys %arguments
796 );
797 }
798  
799 =head2 _canonicalize_arguments
800  
801 Canonicalizes each of the L<arguments|Jifty::Manual::Glossary/arguments> that
802 this action knows about.
803  
804 This is done by calling L</_canonicalize_argument> for each field
805 described by L</arguments>.
806  
807 =cut
808  
809 # XXX TODO: This is named with an underscore to prevent infinite
810 # looping with arguments named "argument" or "arguments". We need a
811 # better solution.
812 0 ▶sub _canonicalize_arguments {
Subroutine _canonicalize_arguments: not called CC=2 SCAR=17.9
813 0 my $self = shift;
814  
815 # For each, canonicalize them all
816 $self->_canonicalize_argument($_)
817 0 for $self->argument_names;
818 }
819  
820  
821 =head2 _canonicalize_argument ARGUMENT
822  
823 Canonicalizes the value of an L<argument|Jifty::Manual::Glossary/argument>.
824 If the argument has an attribute named B<canonicalizer>, call the
825 subroutine reference that attribute points points to.
826  
827 If it doesn't have a B<canonicalizer> attribute, but the action has a
828 C<canonicalize_I<ARGUMENT>> function, also invoke that function.
829  
830 If neither of those are true, by default canonicalize dates using
831 _canonicalize_date
832  
833 Note that it is possible that a canonicalizer will be called multiple
834 times on the same field -- canonicalizers should be careful to do
835 nothing to already-canonicalized data.
836  
837 =cut
838  
839 # XXX TODO: This is named with an underscore to prevent infinite
840 # looping with arguments named "argument" or "arguments". We need a
841 # better solution.
842 0 ▶sub _canonicalize_argument {
Subroutine _canonicalize_argument: not called CC=7 SCAR=40.3
843 0 my $self = shift;
844 0 my $field = shift;
845  
846 # Setup some variables
847 0 my $field_info = $self->arguments->{$field};
848 0 my $value = $self->argument_value($field);
849 0 my $default_method = 'canonicalize_' . $field;
850  
851 # XXX TODO: Do we really want to skip undef values?
852 0 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 0 0
853  
854 # Do we have a valid canonicalizer for this field?
855 0 ▶ if ( $field_info->{canonicalizer}
Branch: 3 branches
BranchTrueFalseTotal
if ($field_info->{'canonicalizer'} and defined &{$field_info->{'canonicalizer'};}) { } 0 0 0
elsif ($self->can($default_method)) { } 0 0 0
elsif (defined $field_info->{'render_as'} and lc $field_info->{'render_as'} eq 'date') { } 0 0 0
Condition0%0/3
$field_info->{"canonicalizer"} and defined &{$field_info->{"canonicalizer"};}
!ll&&!rl&&r
000
MC/DC0%0/2
$field_info->{"canonicalizer"} and defined &{$field_info->{"canonicalizer"};}
$field_info->{"canonicalizer"} defined &{$field_info->{"canonicalizer"};}
Truth table0%0/3
A and B
A= $field_info->{"canonicalizer"}B= defined &{$field_info->{"canonicalizer"};}
ABresult
0X0
100
111
856 0 and defined &{ $field_info->{canonicalizer} } ) {
857
858 # Run it, sucka
859 0 $value = $field_info->{canonicalizer}->( $self, $value, $self->argument_values, $self->_extra_canonicalizer_args );
860 }
861
862 # How about a method named canonicalize_$field?
863 elsif ( $self->can($default_method) ) {
864  
865 # Run that, foo'
866 0 $value = $self->$default_method( $value, $self->argument_values, $self->_extra_canonicalizer_args );
867 }
868
869 # Or is it a date?
870 ▶ elsif ( defined( $field_info->{render_as} )
Condition0%0/3
defined $field_info->{"render_as"} and lc $field_info->{"render_as"} eq "date"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $field_info->{"render_as"} and lc $field_info->{"render_as"} eq "date"
defined $field_info->{"render_as"} lc $field_info->{"render_as"} eq "date"
Truth table0%0/3
A and B
A= defined $field_info->{"render_as"}B= lc $field_info->{"render_as"} eq "date"
ABresult
0X0
100
111
871 && lc( $field_info->{render_as} ) eq 'date') {
872  
873 # Use the default date canonicalizer, Mr. T!
874 0 $value = $self->_canonicalize_date( $value, $self->argument_values, $self->_extra_canonicalizer_args );
875 }
876  
877 0 $self->argument_value($field => $value);
878 }
879  
880 =head2 _canonicalize_date DATE
881  
882 Parses and returns the date using L<Jifty::DateTime::new_from_string>.
883  
884 =cut
885  
886 0 ▶sub _canonicalize_date {
Subroutine _canonicalize_date: not called CC=4 SCAR=30.0
887 0 my $self = shift;
888 0 my $val = shift;
889 0 ▶ return undef unless defined $val and $val =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val and $val =~ /\S/ 0 0 0
Condition0%0/3
defined $val and $val =~ /\S/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $val and $val =~ /\S/
defined $val $val =~ /\S/
Truth table0%0/3
A and B
A= defined $valB= $val =~ /\S/
ABresult
0X0
100
111
890 0 ▶ return undef unless my $obj = Jifty::DateTime->new_from_string($val);
Branch: 1 branch
BranchTrueFalseTotal
unless my $obj = "Jifty::DateTime"->new_from_string($val) 0 0 0
891 0 return $obj->ymd;
892 }
893  
894 =head2 _validate_arguments
895  
896 Validates the form fields. This is done by calling
897 L</_validate_argument> for each field described by L</arguments>
898  
899 =cut
900  
901 # XXX TODO: This is named with an underscore to prevent infinite
902 # looping with arguments named "argument" or "arguments". We need a
903 # better solution.
904 0 ▶sub _validate_arguments {
Subroutine _validate_arguments: not called CC=2 SCAR=17.9
905 0 my $self = shift;
906
907 # Validate each argument
908 $self->_validate_argument($_)
909 0 for $self->argument_names;
910  
911 0 return $self->result->success;
912 }
913  
914 =head2 _validate_argument ARGUMENT
915  
916 Validate your form fields. If the field C<ARGUMENT> is mandatory,
917 checks for a value. If the field has an attribute named B<validator>,
918 call the subroutine reference validator points to.
919  
920 If the action doesn't have an explicit B<validator> attribute, but
921 does have a C<validate_I<ARGUMENT>> function, invoke that function.
922  
923 =cut
924  
925 # XXX TODO: This is named with an underscore to prevent infinite
926 # looping with arguments named "argument" or "arguments". We need a
927 # better solution.
928 0 ▶sub _validate_argument {
Subroutine _validate_argument: not called CC=17 SCAR=57.2
929 0 my $self = shift;
930 0 my $field = shift;
931  
932 # Do nothing if we don't have a field name
933 0 ▶ return unless $field;
Branch: 1 branch
BranchTrueFalseTotal
unless $field 0 0 0
934
935 0 $self->log->debug(" validating argument $field");
936  
937 # Do nothing if we don't know what that field is
938 0 my $field_info = $self->arguments->{$field};
939 0 ▶ return unless $field_info;
Branch: 1 branch
BranchTrueFalseTotal
unless $field_info 0 0 0
940  
941 # Grab the current value
942 0 my $value = $self->argument_value($field);
943
944 # When it isn't even given, check if it's mandatory and whine about it
945 0 ▶ if ( !defined $value || !length $value ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value and length $value) 0 0 0
Condition0%0/3
defined $value and length $value
!ll&&!rl&&r
000
MC/DC0%0/2
defined $value and length $value
defined $value length $value
Truth table0%0/3
A and B
A= defined $valueB= length $value
ABresult
0X0
100
111
946 0 ▶ if ( $field_info->{mandatory} and ($self->has_argument($field) or not defined $field_info->{default_value})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($field_info->{"mandatory"} and $self->has_argument($field) || !defined($field_info->{"default_value"})) 0 0 0
Condition0%0/6
$field_info->{"mandatory"} and $self->has_argument($field) || !defined($field_info->{"default_value"})
!ll&&!rl&&r
000
$self->has_argument($field) or not defined $field_info->{"default_value"}
l!l&&r!l&&!r
000
MC/DC0%0/3
$field_info->{"mandatory"} and $self->has_argument($field) || !defined($field_info->{"default_value"})
$field_info->{"mandatory"} $self->has_argument($field) not defined $field_info->{"default_value"}
Truth table0%0/4
A and B or not(C)
A= $field_info->{"mandatory"}B= $self->has_argument($field)C= not defined $field_info->{"default_value"}
ABCresult
0XX0
1000
11X1
1011
947 0 ▶ return $self->validation_error( $field => _("You need to fill in the '%1' field", $field_info->{label} || $field) );
Condition0%0/3
$field_info->{'label'} || $field
l!l&&r!l&&!r
000
MC/DC0%0/2
$field_info->{'label'} || $field
$field_info->{'label'} $field
Truth table0%0/3
A || B
A= $field_info->{'label'}B= $field
ABresult
1X1
011
000
948 }
949 }
950  
951 # If we have a set of allowed values, let's check that out.
952 0 ▶ if ( $value && $field_info->{valid_values} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value and $field_info->{"valid_values"}) 0 0 0
Condition0%0/3
$value and $field_info->{"valid_values"}
!ll&&!rl&&r
000
MC/DC0%0/2
$value and $field_info->{"valid_values"}
$value $field_info->{"valid_values"}
Truth table0%0/3
A and B
A= $valueB= $field_info->{"valid_values"}
ABresult
0X0
100
111
953 0 $self->_validate_valid_values($field => $value);
954 # ... but still check through a validator function even if it's in the list
955 0 ▶ return if $self->result->field_error($field);
Branch: 1 branch
BranchTrueFalseTotal
if $self->result->field_error($field) 0 0 0
956 }
957  
958 # the validator method name is validate_$field
959 0 my $default_validator = 'validate_' . $field;
960  
961 # Finally, fall back to running a validator sub
962 0 ▶ if ( $field_info->{validator}
Branch: 3 branches
BranchTrueFalseTotal
if ($field_info->{'validator'} and defined &{$field_info->{'validator'};}) { } 0 0 0
elsif ($self->can($default_validator)) { } 0 0 0
elsif ($self->result->field_error($field) or $self->result->field_warning($field)) { } 0 0 0
Condition0%0/3
$field_info->{"validator"} and defined &{$field_info->{"validator"};}
!ll&&!rl&&r
000
MC/DC0%0/2
$field_info->{"validator"} and defined &{$field_info->{"validator"};}
$field_info->{"validator"} defined &{$field_info->{"validator"};}
Truth table0%0/3
A and B
A= $field_info->{"validator"}B= defined &{$field_info->{"validator"};}
ABresult
0X0
100
111
963 0 and defined &{ $field_info->{validator} } )
964 {
965 0 return $field_info->{validator}->( $self, $value, $self->argument_values, $self->_extra_validator_args );
966 }
967  
968 # Check to see if it's the validate_$field method instead and use that
969 elsif ( $self->can($default_validator) ) {
970 0 return $self->$default_validator( $value, $self->argument_values, $self->_extra_validator_args );
971 }
972  
973 # Check if we already have a failure for it, from some other field
974 ▶ elsif ( $self->result->field_error($field) or $self->result->field_warning($field) ) {
Condition0%0/3
$self->result->field_error($field) or $self->result->field_warning($field)
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->result->field_error($field) or $self->result->field_warning($field)
$self->result->field_error($field) $self->result->field_warning($field)
Truth table0%0/3
A or B
A= $self->result->field_error($field)B= $self->result->field_warning($field)
ABresult
1X1
011
000
975 0 return 0;
976 }
977  
978 # If none of the checks have failed so far, then it's ok
979 else {
980 0 return $self->validation_ok($field);
981 }
982 }
983  
984 =head2 _extra_validator_args
985  
986 Returns a list of extra arguments to pass to validators. By default, an empty
987 hash reference, but subclasses can override it to pass, say, a better C<for>.
988  
989 =cut
990  
991 0 ▶sub _extra_validator_args {
Subroutine _extra_validator_args: not called CC=1 SCAR=6.9
992 0 return {};
993 }
994  
995 =head2 _extra_canonicalizer_args
996  
997 Returns a list of extra arguments to pass to canonicalizers. By default, an
998 empty hash reference, but subclasses can override it to pass, say, a better
999 C<for>.
1000  
1001 =cut
1002  
1003 0 ▶sub _extra_canonicalizer_args {
Subroutine _extra_canonicalizer_args: not called CC=1 SCAR=6.9
1004 0 return {};
1005 }
1006  
1007 =head2 _extra_autocompleter_args
1008  
1009 Returns a list of extra arguments to pass to autocompleters. By default, an
1010 empty hash reference, but subclasses can override it to pass, say, a better
1011 C<for>.
1012  
1013 =cut
1014  
1015 0 ▶sub _extra_autocompleter_args {
Subroutine _extra_autocompleter_args: not called CC=1 SCAR=6.9
1016 0 return {};
1017 }
1018  
1019 =head2 _autocomplete_argument ARGUMENT
1020  
1021 Get back a list of possible completions for C<ARGUMENT>. The list
1022 should either be a list of scalar values or a list of hash references.
1023 Each hash reference must have a key named C<value>. There can also
1024 additionally be a key named C<label> which, if present, will be used
1025 as the user visible label. If C<label> is not present then the
1026 contents of C<value> will be used for the label.
1027  
1028 If the field has an attribute named B<autocompleter>, call the
1029 subroutine reference B<autocompleter> points to.
1030  
1031 If the field doesn't have an explicit B<autocompleter> attribute, but
1032 does have a C<autocomplete_I<ARGUMENT>> function, invoke that
1033 function.
1034  
1035  
1036 =cut
1037  
1038 # XXX TODO: This is named with an underscore to prevent infinite
1039 # looping with arguments named "argument" or "arguments". We need a
1040 # better solution.
1041 0 ▶sub _autocomplete_argument {
Subroutine _autocomplete_argument: not called CC=3 SCAR=24.8
1042 0 my $self = shift;
1043 0 my $field = shift;
1044 0 my $field_info = $self->arguments->{$field};
1045 0 my $value = $self->argument_value($field);
1046  
1047 # the method is autocomplete_$field
1048 0 my $default_autocomplete = 'autocomplete_' . $field;
1049  
1050 # If it's defined on the field, use that autocompleter
1051 0 ▶ if ( $field_info->{autocompleter} )
Branch: 2 branches
BranchTrueFalseTotal
if ($field_info->{'autocompleter'}) { } 0 0 0
elsif ($self->can($default_autocomplete)) { } 0 0 0
1052 {
1053 0 return $field_info->{autocompleter}->( $self, $value, $self->argument_values, $self->_extra_autocompleter_args );
1054 }
1055  
1056 # If it's a method on the class, use that autocompleter
1057 elsif ( $self->can($default_autocomplete) ) {
1058 0 return $self->$default_autocomplete( $value, $self->argument_values, $self->_extra_autocompleter_args );
1059 }
1060  
1061 # Otherwise, return zip-zero-notta
1062 0 return();
1063 }
1064  
1065 =head2 valid_values ARGUMENT
1066  
1067 Given an L<parameter|Jifty::Manual::Glossary/parameter> name, returns the
1068 list of valid values for it, based on its C<valid_values> field.
1069  
1070 This method returns a hash reference with a C<display> field for the string
1071 to display for the value, and a C<value> field for the value to actually send
1072 to the server.
1073  
1074 (Avoid using this -- this is not the appropriate place for this logic
1075 to be!)
1076  
1077 =cut
1078  
1079 0 ▶sub valid_values {
Subroutine valid_values: not called CC=1 SCAR=6.9
Pod documented
1080 0 my $self = shift;
1081 0 my $field = shift;
1082  
1083 0 $self->_values_for_field( $field => 'valid' );
1084 }
1085  
1086 0 ▶sub _validate_valid_values {
Subroutine _validate_valid_values: not called CC=3 SCAR=24.8
1087 0 my $self = shift;
1088 0 my $field = shift;
1089 0 my $value = shift;
1090  
1091 # If you're not on the list, you can't come to the party
1092 0 ▶ unless ( grep {defined $_->{'value'} and $_->{'value'} eq $value}
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {defined $_->{"value"} and $_->{"value"} eq $value;} @{$self->valid_values($field);}) 0 0 0
Condition0%0/3
defined $_->{'value'} && $_->{'value'} eq $value
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_->{'value'} && $_->{'value'} eq $value
defined $_->{'value'} $_->{'value'} eq $value
Truth table0%0/3
A && B
A= defined $_->{'value'}B= $_->{'value'} eq $value
ABresult
0X0
100
111
1093 0 @{ $self->valid_values($field) } ) {
1094  
1095 0 return $self->validation_error(
1096 $field => _("That doesn't look like a correct value") );
1097 }
1098  
1099 0 return 1;
1100 }
1101  
1102 =head2 available_values ARGUMENT
1103  
1104 Just like L<valid_values>, but if our action has a set of available
1105 recommended values, returns that instead. (We use this to
1106 differentiate between a list of acceptable values and a list of
1107 suggested values)
1108  
1109 =cut
1110  
1111 0 ▶sub available_values {
Subroutine available_values: not called CC=2 SCAR=17.9
Pod documented
1112 0 my $self = shift;
1113 0 my $field = shift;
1114  
1115 0 ▶ $self->_values_for_field( $field => 'available' ) || $self->_values_for_field( $field => 'valid' );
Branch: 1 branch
BranchTrueFalseTotal
$self->_values_for_field($field, "available") or $self->_values_for_field($field, "valid") 0 0 0
1116  
1117 }
1118  
1119 # TODO XXX FIXME this is probably in the wrong place, logically
1120 0 ▶sub _values_for_field {
Subroutine _values_for_field: not called CC=10 SCAR=47.0
1121 0 my $self = shift;
1122 0 my $field = shift;
1123 0 my $type = shift;
1124  
1125 # Check for $type_values (valid_values or available_values)
1126 0 my $vv_orig = $self->arguments->{$field}{$type .'_values'};
1127 0 local $@;
1128  
1129 # Try making that into a list or just return it
1130 0 ▶ my @values = eval { @$vv_orig } or return $vv_orig;
Branch: 1 branch
BranchTrueFalseTotal
my(@values) = eval { do { @$vv_orig } } or return $vv_orig 0 0 0
1131  
1132 # This is a final return list
1133 0 my @vv;
1134  
1135 # For each value in the *_values list
1136 0 for my $v (@values) {
1137  
1138 # If it's a hash, it may be a collection spec or a display/value
1139 0 ▶ if ( ref $v eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq 'HASH') { } 0 0 0
1140  
1141 # Check for a collection spec
1142 0 ▶ if ( $v->{'collection'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v->{'collection'}) { } 0 0 0
1143  
1144 # Load the display_from/value_from parameters
1145 0 my $disp = $v->{'display_from'};
1146 0 my $val = $v->{'value_from'};
1147  
1148 0 ▶ if ($v->{'collection'}->count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v->{"collection"}->count) 0 0 0
1149 0 ▶ unless ($v->{'collection'}->first->can($disp)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($v->{"collection"}->first->can($disp)) 0 0 0
1150 0 $self->log->error("Invalid 'display_from' of $disp on $field");
1151 }
1152 0 ▶ unless ($v->{'collection'}->first->can($val)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($v->{"collection"}->first->can($val)) 0 0 0
1153 0 $self->log->error("Invalid 'value_from' of $val on $field");
1154 }
1155 }
1156  
1157 # XXX TODO: wrap this in an eval?
1158  
1159 # Fetch all the record from the given collection and keep'em
1160 push @vv, map {
1161 {
1162 0 ▶ display => ( $_->$disp() || '' ),
Condition0%0/4
$_->$disp || ''
l!l
00
$_->$val || ''
l!l
00
MC/DC0%0/1
$_->$disp || ''
$_->$disp
MC/DC0%0/1
$_->$val || ''
$_->$val
Truth table0%0/2
A
A= $_->$disp
Aresult
11
00
Truth table0%0/2
A
A= $_->$val
Aresult
11
00
1163 value => ( $_->$val() || '' )
1164 }
1165 0 } grep {$_->check_read_rights} @{ $v->{'collection'}->items_array_ref };
1166  
1167 }
1168  
1169 # Otherwise, push on the display/value hash
1170 else {
1171  
1172 # assume it's already display/value
1173 0 push @vv, $v;
1174 }
1175 }
1176  
1177 # Otherwise, treat plain string both display and value
1178 else {
1179  
1180 # just a string
1181 0 push @vv, { display => $v, value => $v };
1182 }
1183 }
1184  
1185 0 return \@vv;
1186 }
1187  
1188 =head2 validation_error ARGUMENT => ERROR TEXT, [OPTIONS]
1189  
1190 Used to report an error during validation. Inside a validator you
1191 should write:
1192  
1193 return $self->validation_error( $field => "error");
1194  
1195 ..where C<$field> is the name of the argument which is at fault. Any
1196 extra C<OPTIONS> are passed through to L<Jifty::Result/field_error>.
1197  
1198 =cut
1199  
1200 0 ▶sub validation_error {
Subroutine validation_error: not called CC=2 SCAR=17.9
Pod documented
1201 0 my $self = shift;
1202 0 my ($field, $error, %args) = @_;
1203 $self->log->warn("No such field '$field' -- did you forget to specify a field?")
1204 0 ▶ unless $self->arguments->{$field};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->arguments->{$field} 0 0 0
1205  
1206 0 $self->result->field_error($field => $error, %args);
1207  
1208 0 return 0;
1209 }
1210  
1211 =head2 validation_warning ARGUMENT => WARNING TEXT, [OPTIONS]
1212  
1213 Used to report a warning during validation. Inside a validator you
1214 should write:
1215  
1216 return $self->validation_warning( $field => _("warning"));
1217  
1218 ..where C<$field> is the name of the argument which is at fault. Any
1219 extra C<OPTIONS> are passed through to L<Jifty::Result/field_warning>.
1220  
1221 =cut
1222  
1223 0 ▶sub validation_warning {
Subroutine validation_warning: not called CC=2 SCAR=17.9
Pod documented
1224 0 my $self = shift;
1225 0 my ($field, $warning, %args) = @_;
1226 $self->log->warn("No such field '$field' -- did you forget to specify a field?")
1227 0 ▶ unless $self->arguments->{$field};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->arguments->{$field} 0 0 0
1228  
1229 0 $self->result->field_warning($field => $warning, %args);
1230  
1231 0 return 0;
1232 }
1233  
1234 =head2 validation_ok ARGUMENT, [OPTIONS]
1235  
1236 Used to report that a field B<does> validate. Inside a validator you
1237 should write:
1238  
1239 return $self->validation_ok($field);
1240  
1241 Any extra C<OPTIONS> are passed through to
1242 L<Jifty::Result/field_warning> and L<Jifty::Result/field_error> when
1243 unsetting them.
1244  
1245 =cut
1246  
1247 0 ▶sub validation_ok {
Subroutine validation_ok: not called CC=2 SCAR=17.9
Pod documented
1248 0 my $self = shift;
1249 0 my ($field, %args) = @_;
1250 $self->log->warn("No such field '$field' -- did you forget to specify a field?")
1251 0 ▶ unless $self->arguments->{$field};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->arguments->{$field} 0 0 0
1252  
1253 0 $self->result->field_error($field => undef, %args);
1254 0 $self->result->field_warning($field => undef, %args);
1255  
1256 0 return 1;
1257 }
1258  
1259 =head2 canonicalization_note ARGUMENT => NOTE
1260  
1261 Used to send an informational message to the user from the canonicalizer.
1262 Inside a canonicalizer you can write:
1263  
1264 $self->canonicalization_note( $field => _("I changed $field for you"));
1265  
1266 ..where C<$field> is the name of the argument which the canonicalizer is
1267 processing
1268  
1269 =cut
1270  
1271 0 ▶sub canonicalization_note {
Subroutine canonicalization_note: not called CC=1 SCAR=6.9
Pod documented
1272 0 my $self = shift;
1273 0 my $field = shift;
1274 0 my $info = shift;
1275
1276 0 $self->result->field_canonicalization_note($field => $info);
1277  
1278 0 return;
1279  
1280 }
1281  
1282 =head2 deny REASON
1283  
1284 When access to an action is denied by L<Jifty::API::is_allowed>
1285 the request handler calls this with a message.
1286  
1287 This should mark the action as failed and store the message
1288 but may also want to do other things (such as providing a nicer message
1289 or logging somewhere other than the jifty logs)
1290  
1291 =cut
1292  
1293 0 ▶sub deny {
Subroutine deny: not called CC=2 SCAR=17.9
Pod documented
1294 0 my $self = shift;
1295 0 ▶ my $message = shift||'';
Condition0%0/2
shift() || ''
l!l
00
MC/DC0%0/1
shift() || ''
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1296  
1297 0 $self->result->failure(1);
1298 0 $self->result->message($message);
1299  
1300 0 return;
1301 }
1302  
1303 =head2 TO_JSON
1304  
1305 Returns this action's moniker for JSON serialization. This is mostly to catch
1306 places where Jifty::Action objects are used instead of the moniker in a
1307 webservices request.
1308  
1309 Currently only L<Jifty::Web::Form::Element/javascript_attrs> enables the
1310 C<convert_blessed> option of L<JSON> (through L<Jifty::JSON>) which uses this
1311 method. Objects without a TO_JSON method cause fatal JSON errors.
1312  
1313 =cut
1314  
1315 0 ▶sub TO_JSON { shift->moniker }
Subroutine TO_JSON: not called CC=1 SCAR=6.9
Pod documented
1316  
1317 =head1 CUSTOMIZATION
1318  
1319 =head2 Canonicalization
1320  
1321 If you wish to have the data in a field normalized into a particular
1322 format (such as changing a date into C<YYYY-MM-DD> format, adding commas
1323 to numbers, capitalizing words, or whatever you need) you can do so
1324 using a canonicalizer.
1325  
1326 This is just a method titled C<canonicalize_FIELD> where C<FIELD> is
1327 the name of the field be normalized. Here is an example:
1328  
1329 sub canonicalize_foo {
1330 my ($self, $value, $other, $metadata) = @_;
1331  
1332 # do something to canonicalize the value
1333 my $normal_form = lc($value) . '-' . $other->{other_field};
1334 $normal_form .= '-update' if $metadata->{for} eq 'update';
1335
1336 return $normal_form;
1337 }
1338  
1339 The first parameter to your canonicalizer will be the value to be
1340 canonicalized. The next will be a hash reference of all the parameters
1341 submitted with this canonicalization, so you can be smarter. Finally, the third
1342 parameter is a hash reference of other metadata, such as C<for>, whose value
1343 will be C<create> or C<update>.
1344  
1345 While doing this you might also want to call the
1346 L</canonicalization_note> to inform the client of the modification:
1347  
1348 my $normal_form = lc($value);
1349 $self->canonicalization_note(
1350 foo => _('Foo values are always in lowercase.'));
1351  
1352 If the "foo" field has "ajax canoncalizes" set in the action schema,
1353 then this process will be performed automatically as the form is being
1354 filled without reloading the page.
1355  
1356 =head2 Validation
1357  
1358 If a value must follow a certain format, you can provide a validation
1359 method for fields to make sure that no value enters the database until
1360 it is in a valid form.
1361  
1362 A validation method is one named C<validate_FIELD> where C<FIELD> is
1363 the name of the field being checked. Here is an example:
1364  
1365 sub validate_foo {
1366 my ($self, $value, $other, $metadata) = @_;
1367  
1368 # Check for uppercase letters
1369 if ($value =~ /\p{Lu}/) {
1370 return $self->validation_warning(
1371 foo => _("Foo cannot contain uppercase letters."));
1372 }
1373  
1374 # Check for -, *, +, and ?
1375 elsif ($value =~ /[\-\*\+\?]/) {
1376 return $self->validation_error(
1377 foo => _("Foo cannot contain -, *, +, or ?."));
1378 }
1379  
1380 return 1;
1381 }
1382  
1383 Here the "foo" field should not contain uppercase letters and must not
1384 contain the characters '-', '*', '+', or '?'. You can use
1385 L</validation_error> and L</validation_warning> to return the results
1386 of your validation to the user or simply return 1 to indicate a valid
1387 value.
1388  
1389 Note that the parameters are the same as in L</Canonicalization>.
1390  
1391 If you just have a list of valid values, you may want to use the
1392 C<valid_values> schema parameter to perform this task instead.
1393  
1394 =head2 Autocompletion
1395  
1396 Autocompletion provides a way of suggesting choices to the client
1397 based upon partial data entry. This doesn't necessarily force the
1398 client to use one of the choices given but gives hints in an
1399 application specific way.
1400  
1401 To create an autocompletion field, you implement a method named
1402 C<autocomplete_FIELD> where C<FIELD> is the field to
1403 autocomplete. This is generally done with fields rendered as
1404 'Text'. Here is an example:
1405  
1406 sub autocomplete_foo {
1407 my ($self, $value) = @_;
1408  
1409 # Be careful to validate your input! You don't want a malicious user
1410 # hacking your system.
1411 my ($match_value) = $value =~ /^(\w+)$/;
1412  
1413 my $foos = MyApp::Model::FooCollection->new;
1414 $foos->limit(
1415 column => 'name',
1416 operator => 'LIKE',
1417 value => '%$value%',
1418 );
1419  
1420 return map { $_->name } @{ $foos->items_array_ref };
1421 }
1422  
1423 In this example, the "foo" field is autocompleted from names matched
1424 from the C<MyApp::Model::Foo> table. The match, in this case, matches
1425 any substring found in the database. I could have matched any item
1426 that starts with the string, ends with the string, matches other
1427 fields than the one returned, etc. It's up to you to decide.
1428  
1429 Note also that I have untainted the value coming in to make sure a
1430 malicious user doesn't get anyway. You should always perform a check
1431 like this when data is coming in from an outside source.
1432  
1433 If you need a more complicated solution, you can return the
1434 autocompletion values as a list of hash references containing the keys
1435 C<value> and (optionally) C<label>:
1436  
1437 return map { { value => $_->name, label => $_->label } }
1438 @{ $foos->items_array_ref };
1439  
1440 In this case, the labels will be shown to the client, but the selected
1441 value would be returned to your application.
1442  
1443 =cut
1444  
1445 =head1 SEE ALSO
1446  
1447 L<Jifty>, L<Jifty::API>, L<Jifty::Action::Record>, L<Jifty::Result>,
1448 L<Jifty::Param::Schema>, L<Jifty::Manual::Actions>
1449  
1450 =head1 LICENSE
1451  
1452 Jifty is Copyright 2005-2010 Best Practical Solutions, LLC.
1453 Jifty is distributed under the same terms as Perl itself.
1454  
1455 =cut
1456  
1457 113 1;
« Jifty/Script/Adopt.pm ↑ Summary Jifty/Web/Form/Field/Checkboxes.pm »