MxScreen/Form/Field.pm untested

filter: Statementstmt 0.0% 0 / 116 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 35 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 214 CC 16 SCAR 28.8
CC
16
Cov
0%
store_value
56.0
validate
56.0
patch_value
12.0
CRAP 17.9
1 # -*- Mode: perl -*-
2 #
3 # $Id: Field.pm,v 0.1 2001/04/22 17:57:03 ram Exp $
4 #
5 # Copyright (c) 1998-2001, Raphael Manfredi
6 # Copyright (c) 2000-2001, Christophe Dehaudt
7 #
8 # You may redistribute only under the terms of the Artistic License,
9 # as specified in the README file that comes with the distribution.
10 #
11 # HISTORY
12 # $Log: Field.pm,v $
13 # Revision 0.1 2001/04/22 17:57:03 ram
14 # Baseline for first Alpha release.
15 #
16 # $EndLog$
17 #
18  
19 use strict;
20  
21 package CGI::MxScreen::Form::Field;
22  
23 use CGI;
24 use Carp::Datum;
25 use Log::Agent;
26 use Getargs::Long qw(ignorecase);
27  
28 # index of the array
29 BEGIN {
30 sub NAME () {0}
31 sub MANDATORY () {1}
32 sub VERIFY_ARG () {2} # VERIFY conflict with Carp::Datum's
33 sub STORAGE () {3}
34 sub PATCH () {4}
35 sub NOSTORAGE () {5}
36  
37 sub CGI_ARGS () {6}
38 sub VALUE () {7}
39 sub ERROR () {8}
40 }
41  
42  
43 #
44 # ->make
45 #
46 # Arguments: (that are considered, others values are kept aside)
47 # -name => string
48 # -mandatory => boolean
49 # -verify => 'routine' or ['routine', args ...]
50 # -patch => 'routine' or ['routine', args ...]
51 # -storage => 'symbol' or [objref, 'routine', arg] or [ref, 'symbol']
52 # -nostorage => boolean
53 #
54 sub make {
55 DFEATURE my $f_;
56 my $self = bless [], shift;
57 my ($name, $default) = cxgetargs(@_, { -strict => 0, -extra => 0 },
58 -name => 's',
59 -default => [],
60 );
61  
62 # Initial value at creation time
63 my $param = CGI::param($name);
64 $self->[VALUE] = defined($param) ? $param : $default;
65 $self->[ERROR] = '';
66  
67 $self->update(@_);
68 return DVAL $self;
69 }
70  
71  
72 #
73 # ->update
74 #
75 #
76 sub update {
77 DFEATURE my $f_;
78 my $self = shift;
79  
80 ($self->[NAME],
81 $self->[MANDATORY],
82 $self->[VERIFY_ARG],
83 $self->[STORAGE],
84 $self->[PATCH],
85 $self->[NOSTORAGE],
86 @{$self->[CGI_ARGS]}) =
87 cxgetargs(@_, {-strict => 0},
88 -name => 's',
89 -mandatory => ['i'],
90 -verify => [],
91 -storage => [],
92 -patch => [],
93 -nostorage => ['i']
94 );
95  
96 unshift @{$self->[CGI_ARGS]}, ('-name', $self->name);
97
98 return DVOID;
99 }
100  
101  
102 # Temporary method
103 #
104 # To Be Removed
105 # when storable would be able to select what is stored with
106 # Storable::Hook
107 sub cleanup {
108 DFEATURE my $f_;
109 my $self = shift;
110
111 $#{$self} = NOSTORAGE;
112  
113 return DVOID;
114 }
115  
116 #########################################################################
117 # Class Feature: usable from the external world #
118 #########################################################################
119 sub name { $_[0]->[NAME] }
120 sub mandatory { $_[0]->[MANDATORY] }
121 sub verify { $_[0]->[VERIFY_ARG] }
122 sub storage { $_[0]->[STORAGE] }
123 sub patch { $_[0]->[PATCH] }
124 sub nostorage { $_[0]->[NOSTORAGE] }
125  
126 sub value { $_[0]->[VALUE] }
127 sub error { $_[0]->[ERROR] }
128  
129 sub set_value { $_[0]->[VALUE] = $_[1] }
130 sub set_error { $_[0]->[ERROR] = $_[1] }
131  
132 #
133 # ->properties
134 #
135 # return the full list of arg that were given at creation time. The
136 # result can be used to supply the CGI functions.
137 #
138 # Return:
139 # a list of arguments.
140 #
141 sub properties {
142 DFEATURE my $f_;
143 my $self = shift;
144
145 return DARY (@{$self->[CGI_ARGS]});
146 }
147  
148  
149 #
150 # ->store_value
151 #
152 #
153 # Arguments:
154 # $var_ctx: context reference where data can be stored when the
155 # storage location is merly a string.
156 # Svalue: the value to store.
157 #
158 # Return:
159 # true (1) when the param has been stored somewhere (storage
160 # indication is defined), false (0) otherwise.
161 #
162 sub store_value {
163 DFEATURE my $f_;
164 my $self = shift;
165 my ($var_ctx, $value) = @_;
166 my $storage = $self->storage;
167  
168 # save it internally
169 $self->set_value($value);
170  
171 return DVAL ($self->nostorage != 0) unless defined $storage;
172  
173 # when storage indication is an array, the value is stored
174 # at the location defined by the 2 arrays elements. It is either
175 # a hashref and a key, or a list ref and an index, or an object ref
176 # and a method.
177 if (ref($storage) eq 'ARRAY') {
178 my ($ref, $name, @arg) = @{$storage};
179 my $target = ref($ref);
180
181 if ($target eq 'HASH') {
182 DTRACE "it is a hash ref";
183 $ref->{$name} = $value;
184 }
185 elsif ($target eq 'ARRAY') {
186 DTRACE "it is a list ref";
187 $ref->[$name] = $value;
188 }
189 elsif (is_blessed($ref)) {
190 DTRACE "it is an object ref ($ref)";
191 DASSERT $ref->can($name), "can call '->$name' on $ref";
192 if (@arg) {
193 $ref->$name($value, @arg);
194 } else {
195 $ref->$name($value);
196 }
197 } else {
198 my $name = $self->name;
199 logwarn "invalid -storage for $name: first listed item is '$ref'";
200 }
201 }
202 else {
203 # when storage indication is a scalar, the value is stored
204 # in the $var_ctx hash
205 DASSERT ref(\$storage) eq 'SCALAR';
206 $var_ctx->{$storage} = $value;
207 }
208
209 return DVAL 1;
210 }
211  
212 #
213 # ->patch_value
214 #
215 # Argument:
216 # value to patch (scalar, or ref to list of values)
217 #
218 # Returns:
219 # boolean indicating whether value was passed to a patching routine or not.
220 # patched value, when passed to patching routine.
221 #
222 sub patch_value {
223 DFEATURE my $f_;
224 my $self = shift;
225 my ($value) = @_;
226 my $ref = $self->patch;
227 return DARY (0) unless defined $ref; # Not patched
228  
229 #
230 # Patching routine can be a single routine name (which is then looked up
231 # in the util path), or a list ref indicating the routine name and the
232 # extra arguments to append, after the value to patch.
233 #
234  
235 my ($routine, @arg);
236 if (ref($ref) eq 'ARRAY') {
237 # handle array setting : -patch => ['float2float', 4]
238 ($routine, @arg) = @$ref;
239 }
240 else {
241 # handle scalar setting : -patch => 'float2int'
242 $routine = $ref;
243 }
244  
245 require CGI::MxScreen::Form::Utils;
246  
247 my $coderef = CGI::MxScreen::Form::Utils::lookup($routine);
248 VERIFY $coderef != 0, "found routine '$routine'";
249  
250 #
251 # NOTE: value to patch pre-pended to any extra args supplied by user
252 #
253  
254 return DARY (1, &{$coderef}($value, @arg)); # Patched
255 }
256  
257 #
258 # ->validate
259 #
260 # check that the value contained in this field matches the required
261 # criteria (mandatory or verify)
262 #
263 # Return:
264 # a boolean value which indicates the error status (false on error).
265 #
266 sub validate {
267 DFEATURE my $f_;
268 my $self = shift;
269 my $value = $self->value;
270  
271 if ($self->mandatory && $value eq "") {
272 $self->set_error('field is mandatory');
273 return DVAL 0;
274 }
275
276 # don't verify an empty field
277 return DVAL 1 if $value eq "";
278  
279 if (defined $self->verify) {
280 my $ref = $self->verify;
281  
282 my ($routine, @arg);
283 if (ref($ref) eq 'ARRAY') {
284 # handle array setting : -verify => ['is_greater', 4]
285 ($routine, @arg) = @$ref;
286 }
287 else {
288 # handle scalar setting : -verify => 'is_num'
289 $routine = $ref;
290 }
291  
292 require CGI::MxScreen::Form::Utils;
293  
294 my $coderef = CGI::MxScreen::Form::Utils::lookup($routine);
295 logdie "validation routine '$routine' not found for the \"%s\" field",
296 $self->name unless defined $coderef;
297  
298 my $error = &{$coderef}($self->value, @arg);
299 $self->set_error($error) if $error;
300 return DVAL !$error;
301 }
302
303 return DVAL 1; # there is no error
304 }
305  
306  
307 #
308 # is_blessed
309 #
310 # check whether a reference points onto an blessed object
311 #
312 # Return:
313 # a boolean value.
314 #
315 sub is_blessed { UNIVERSAL::isa($_[0], "UNIVERSAL") }
316  
317 1;
318  
319 =head1 NAME
320  
321 CGI::MxScreen::Form::Field - A recorded field
322  
323 =head1 SYNOPSIS
324  
325 # $self is a CGI::MxScreen::Screen
326  
327 use CGI qw/:standard/;
328  
329 my $amount = $self->record_field(
330 -name => "price",
331 -storage => [$order, 'set_amount'],
332 -default => $order->amount,
333 -override => 1,
334 -verify => 'is_positive',
335 -mandatory => 1,
336 -patch => 'strip_spurious_zeros',
337 -size => 10,
338 -maxlength => 10,
339 );
340 print textfield($amount->properties);
341  
342 my $menu = $self->record_field(
343 -name => "mode",
344 -values => ['replace', 'append', 'prepend'],
345 -default => 'append',
346 );
347 print popup_menu($menu->properties);
348  
349 =head1 DESCRIPTION
350  
351 This class models a recorded CGI control field. One does not manually create
352 objects from this class, they are created by C<CGI::MxScreen> when the
353 C<record_field()> routine is called on a screen object to declare a new
354 field.
355  
356 In order to attach application-specific storage information and validating
357 or patching callbacks to a CGI field, it is necessary to declare them
358 within the screen they belong, usually before generating the HTML code
359 for those fields. The declaration routine takes a set of meaningful
360 arguments, and lets the others pass through verbatim (they are recorded
361 to be given back when C<properties()> is called).
362  
363 You must at least supply the C<-name> argument. You will probably supply
364 C<-verify> as well if you wish to perform validation of control fields,
365 and C<-storage> to be able to store the value in some place, or perform
366 any other processing on it.
367  
368 =head1 INTERFACE
369  
370 Some of the arguments below take a plain I<routine> argument as a scalar.
371 This I<routine> is not a code reference but a name that will be looked up
372 in various packages unless it is already qualified, such as C<'main::f'>.
373 See L<CGI::MxScreen/Utility Path> for information about how to specify
374 the searching I<path>, so to speak.
375  
376 =head2 Creation Arguments
377  
378 The following named arguments may be given to C<record_field()>.
379 They are all optional but for C<-name>. Any argument not listed below
380 will be simply recorded and propagated via C<properties()>:
381  
382 =over 4
383  
384 =item C<-default> => I<value>
385  
386 Sets the default value, for the first time the field is shown.
387 Since C<CGI> routines create stateful fields, you may need to say:
388  
389 -default => $value,
390 -override => 1,
391  
392 to force the value of the field to C<$value>. That is, if you use the
393 C<CGI> routines to ultimately generate your field.
394  
395 This parameter is propagated via C<properties()>, but is intercepted
396 by. C<record_field> to set the C<value> attribute of the object. If no
397 C<-default> is given, then the value will be that of the CGI parameter
398 bearing the name you give via C<-name>.
399  
400 =item C<-mandatory> => I<flag>
401  
402 By default, fields are not mandatory. Setting I<flag> to true tells
403 C<CGI::MxScreen> that this parameter should be filled. However, this checking
404 only occurs when you list C<'validate'> as an action callback in the submit
405 buttons of your screen. See L<CGI::MxScreen::Form::Button>.
406  
407 =item C<-name> => I<name>
408  
409 Madantory parameter, giving the name of the field.
410 This is the CGI parameter name.
411  
412 =item C<-nostorage> => 1
413  
414 This directs C<CGI::MxScreen> to not handle the storage of the
415 parameter, at submit time. No trail will be left anywhere in the context.
416 This parameter is ignored when C<-storage> is also given.
417  
418 =item C<-patch> => I<routine>
419  
420 Specifies a patching routine, to be called on the field value to modify
421 it on-the-fly, before storage and verification take place.
422  
423 The routine is given the parameter value, and it must return a new (possibly
424 unchanged) value, which will be the one retained for further processing.
425 Everything will be as if the user had entered this value in the first place.
426  
427 For instance, assume you say:
428  
429 -patch => 'main::no_needless_zeros',
430  
431 and define:
432  
433 sub main::no_needless_zeros {
434 my ($v) = @_;
435 $v =~ s/^0+//;
436 $v =~ s/0+$//;
437 return $v;
438 }
439  
440 Then you if the user entered C<003.140> in a text field, it would be
441 patched to C<3.14>.
442  
443 See L<CGI::MxScreen/Utility Path> to learn how to avoid qualifying the
444 I<routine> and just give its "basename", here C<no_needless_zeros>.
445  
446 =item C<-storage> => I<scalar> | I<array_ref>
447  
448 Storage indication lets you store the value of the field in some place,
449 either directly in the global persistent hash, or in any other data
450 structure of your choice, or even by invoking a callback.
451  
452 If the argument is a I<scalar>, then it is taken as a key in the global
453 persistent hash. For instance:
454  
455 -storage => "user_id",
456  
457 would store the value of the field in the global hash, and would be accessed
458 within a screen by saying:
459  
460 my $id = $self->vars->{user_id};
461  
462 Or the argument to C<-storage> can be an array ref. In that case, the
463 meaning of the items in the list depend on the nature of its first item:
464  
465 If it is an array ref, then the following item must be an index, and the
466 value will be stored at that position in the array. For instance:
467  
468 my $array = $self->vars->{user_array};
469 my $field = $self->record_field(
470 -name => "id",
471 -storage => [$array, 2],
472 );
473  
474 If it is an hash ref, then the following item must be a key, and the
475 value will be store at that key in the hash. For instance:
476  
477 my $hash = $self->vars->{user_hash};
478 my $field = $self->record_field(
479 -name => "id",
480 -storage => [$hash, "uid"],
481 );
482  
483 If it is a blessed ref, then we have a callback specification of the
484 third kind, as described in L<CGI::MxScreen/Callbacks>. For instance:
485  
486 my $field = $self->record_field(
487 -name => "id",
488 -storage => [$object, 'record_uid', 4],
489 );
490  
491 The parameter value is prepended to the argument list, so the above would
492 raise the following call:
493  
494 $object->record_uid(CGI::param("id"), 4);
495  
496 so to speak.
497  
498 B<Note>: the storage specification is serialized into the context, and the
499 actual processing will occur once the user has submitted the form back to
500 the server, on the deserialized context. This means that anything you
501 specify needs to be persistent, and stay accessible throughout the section.
502  
503 That's why it's B<useless> to say:
504  
505 my $field = $self->record_field(
506 -name => "id",
507 -storage => [['a'], 2],
508 );
509  
510 because it will indeed store the value in an I<anonymous> array, which
511 is not otherwise accessible by the application. You should say something
512 along those lines:
513  
514 my $vars = $self->vars;
515  
516 my $array;
517 if (exists $vars->{user_array}) {
518 $array = $vars->{user_array};
519 } else {
520 $array = $vars->{user_array} = [];
521 }
522  
523 my $field = $self->record_field(
524 -name => "id",
525 -storage => [$array, 2],
526 );
527  
528 The C<exists()> check is there because by default, keys within the global
529 hash context are protected: it is a fatal error to access a non-existent
530 key (see L<CGI::MxScreen::Config> to learn how to disable that check).
531  
532 All the code examples given above were simplified, assuming the value
533 within the context was already properly initialized.
534  
535 =item C<-verify> => I<routine>
536  
537 Specifies a validation I<routine> to be run. The routine will not be
538 actually run unless the C<'validate'> action callback is not recorded
539 in the pressed submit button (see L<CGI::MxScreen::Form::Button>).
540  
541 The I<routine> can be specified as a single scalar, or as an array ref:
542  
543 ['is_greater', 4]
544  
545 The validation routine is passed the parameter value as a first argument,
546 and it must return C<0> if OK, an error message otherwise, which will be
547 stored in the C<error> field. In the example above,
548  
549 is_greater($value, 4);
550  
551 would be called, assuming C<$value> is the value of the field.
552  
553 =back
554  
555 Any other argument will be recorded as-is and passed through when
556 C<properties()> is called on the field object.
557  
558 =head2 Features
559  
560 Once created via C<record_field>, the following features may be called
561 on the object:
562  
563 =over 4
564  
565 =item C<error>
566  
567 The error message returned by the validation routine. If it evaluates to
568 I<false>, there is no error condition for this field.
569  
570 =item C<name>
571  
572 Returns the field name.
573  
574 =item C<properties>
575  
576 Generates the list of CGI arguments suitable to use with the routines
577 in the C<CGI> modules. An easy way to generate a popup menu is to
578 do:
579  
580 print popup_menu($menu->properties);
581  
582 assuming C<$menu> was obtained through a C<record_field()> call and
583 included such things as C<-values>. Otherwise, you may add those
584 additional switches now, like in:
585  
586 print popup_menu($menu->properties, -values => ['a', 'b']);
587  
588 but it might be better to group properties at the same place, i.e. when
589 C<record_field()> is called.
590  
591 =item C<value>
592  
593 Returns the recorded field value.
594  
595 When recording a field within a screen, the C<value> attribute is
596 automatically set to the CGI parameter value.
597  
598 =back
599  
600 =head1 AUTHORS
601  
602 The original authors are
603 Raphael Manfredi F<E<lt>Raphael_Manfredi@pobox.comE<gt>>
604 and
605 Christophe Dehaudt F<E<lt>Christophe.Dehaudt@teamlog.frE<gt>>.
606  
607 Send bug reports, suggestions, problems or questions to
608 Jason Purdy F<E<lt>Jason@Purdy.INFOE<gt>>
609  
610 =head1 SEE ALSO
611  
612 CGI::MxScreen(3), CGI::MxScreen::Form::Button(3),
613 CGI::MxScreen::Form::Utils(3).
614  
615 =cut
616