1Maypole::Model::CDBI::AUssFeorrmC(o3n)tributed Perl DocuMmaeynptoaltei:o:nModel::CDBI::AsForm(3)
2
3
4

NAME

6       Maypole::Model:CDBI::AsForm - Produce HTML form elements for database
7       columns
8

SYNOPSIS

10           package Music::CD;
11           use Maypole::Model::CDBI::AsForm;
12           use base 'Class::DBI';
13           use CGI;
14           ...
15
16           sub create_or_edit {
17               my $self = shift;
18               my %cgi_field = $self->to_cgi;
19               return start_form,
20                      (map { "<b>$_</b>: ". $cgi_field{$_}->as_HTML." <br>" }
21                           $class->Columns),
22                      end_form;
23           }
24
25          . . .
26
27           # Somewhere else in a Maypole application about beer...
28
29          $beer->to_field('brewery', 'textfield', {
30                       name => 'brewery_id', value => $beer->brewery,
31                       # however, no need to set value since $beer is object
32          });
33
34          # Rate a beer
35          $beer->to_field(rating =>  select => {
36                       items => [1 , 2, 3, 4, 5],
37          });
38
39          # Select a Brewery to visit in the UK
40          Brewery->to_field(brewery_id => {
41                       items => [ Brewery->search_like(location => 'UK') ],
42          });
43
44         # Make a select for a boolean field
45         $Pub->to_field('open' , { items => [ {'Open' => 1, 'Closed' => 0 } ] });
46
47          $beer->to_field('brewery', {
48                       selected => $beer->brewery, # again not necessary since caller is obj.
49          });
50
51           $beer->to_field('brewery', 'link_hidden', {r => $r, uri => 'www.maypole.perl.org/brewery/view/'.$beer->brewery});
52           # an html link that is also a hidden input to the object. R is required to
53           # make the uri  unless you  pass a  uri
54
55           #####################################################
56           # Templates Usage
57
58           <form ..>
59
60           ...
61
62           <label>
63
64            <span class="field"> [% classmetadata.colnames.$col %] : </span>
65
66            [% object.to_field(col).as_XML %]
67
68           </label>
69
70           . . .
71
72           <label>
73
74            <span class="field"> Brewery : </span>
75
76            [% object.to_field('brewery', { selected => 23} ).as_XML %]
77
78           </label>
79
80           . . .
81
82           </form>
83
84           #####################################################
85           # Advanced Usage
86
87           # has_many select
88           package Job;
89           __PACKAGE__->has_a('job_employer' => 'Employer');
90           __PACKAGE__->has_a('contact'  => 'Contact')
91
92           package Contact;
93           __PACKAGE__->has_a('cont_employer' => 'Employer');
94           __PACKAGE__->has_many('jobs'  => 'Job',
95                                 { join => { job_employer => 'cont_employer' },
96                                   constraint => { 'finshed' => 0  },
97                                   order_by   => "created ASC",
98                                 }
99                                );
100
101           package Employer;
102           __PACKAGE__->has_many('jobs'  => 'Job',);
103           __PACKAGE__->has_many('contacts'  => 'Contact',
104                                 order_by => 'name DESC',
105                                );
106
107         # Choose some jobs to add to a contact (has multiple attribute).
108         my $job_sel = Contact->to_field('jobs'); # Uses constraint and order by
109
110         # Choose a job from $contact->jobs
111         my $job_sel = $contact->to_field('jobs');
112
113         1;
114

DESCRIPTION

116       This module helps to generate HTML forms for creating new database rows
117       or editing existing rows. It maps column names in a database table to
118       HTML form elements which fit the schema. Large text fields are turned
119       into textareas, and fields with a has-a relationship to other
120       "Class::DBI" tables are turned into select drop-downs populated with
121       objects from the joined class.
122

ARGUMENTS HASH

124       This provides a convenient way to tweak AsForm's behavior in excep‐
125       tional or not so exceptional instances. Below describes the arguments
126       hash and example usages.
127
128         $beer->to_field($col, $how, $args);
129         $beer->to_field($col, $args);
130
131       Not all _to_* methods pay attention to all arguments. For example,
132       '_to_textfield' does not look in $args->{'items'} at all.
133
134       name -- the name the element will have , this trumps the derived name.
135             $beer->to_field('brewery', 'readonly', {
136                           name => 'brewery_id'
137             });
138
139       value -- the initial value the element will have, trumps derived value
140             $beer->to_field('brewery', 'textfield', {
141                           name => 'brewery_id', value => $beer->brewery,
142                           # however, no need to set value since $beer is object
143             });
144
145       items -- array of items generally used to make select box options
146           Can be array of objects, hashes, arrays, or strings, or just a
147           hash.
148
149              # Rate a beer
150              $beer->to_field(rating =>  select => {
151                           items => [1 , 2, 3, 4, 5],
152              });
153
154              # Select a Brewery to visit in the UK
155              Brewery->to_field(brewery_id => {
156                           items => [ Brewery->search_like(location => 'UK') ],
157              });
158
159             # Make a select for a boolean field
160             $Pub->to_field('open' , { items => [ {'Open' => 1, 'Closed' => 0 } ] });
161
162       selected -- something representing which item is selected in a select
163       box
164              $beer->to_field('brewery', {
165                           selected => $beer->brewery, # again not necessary since caller is obj.
166              });
167
168           Can be an simple scalar id, an object, or an array of either
169
170       class -- the class for which the input being made for field pertains
171       to.
172           This in almost always derived in cases where it may be difficult to
173           derive, --
174              # Select beers to serve on handpump
175              Pub->to_field(handpumps => select => {           class =>
176           'Beer', order_by => 'name ASC', multiple => 1,      });
177
178       column_type -- a string representing column type
179             $pub->to_field('open', 'bool_select', {
180                           column_type => "bool('Closed', 'Open'),
181             });
182
183       column_nullable -- flag saying if column is nullable or not
184           Generally this can be set to get or not get a null/empty option
185           added to a select box.  AsForm attempts to call "$class->col‐
186           umn_nullable" to set this and it defaults to true if there is no
187           shuch method.
188
189             $beer->to_field('brewery', { column_nullable => 1 });
190
191       r or request  -- the Mapyole request object
192       uri -- uri for a link , used in methods such as _to_link_hidden
193            $beer->to_field('brewery', 'link_hidden',
194                     {r => $r, uri => 'www.maypole.perl.org/brewery/view/'.$beer->brewery});
195            # an html link that is also a hidden input to the object. R is required to
196            # make the uri  unless you  pass a  uri
197
198       order_by, constraint, join
199           These are used in making select boxes. order_by is a simple order
200           by clause and constraint and join are hashes used to limit the rows
201           selected. The difference is that join uses methods of the object
202           and constraint uses static values. You can also specify these in
203           the relationship definitions.  See the relationships documentation
204           of how to set arbitrayr meta info.
205
206             BeerDB::LondonBeer->has_a('brewery', 'BeerDB::Brewery',
207                              order_by     => 'brewery_name ASC',
208                      constraint   => {location  => 'London'},
209                      'join'       => {'brewery_tablecolumn  => 'beer_obj_column'},
210                     );
211
212       no_hidden_constraints --
213           Tell AsForm not to make hidden inputs for relationship constraints.
214           It does this  sometimes when making foreign inputs. However, i
215           think it should not do this and that the FromCGI 's _create_related
216           method should do it.
217
218       to_cgi
219
220         $self->to_cgi([@columns, $args]);
221
222       This returns a hash mapping all the column names to HTML::Element
223       objects representing form widgets.  It takes two opitonal arguments --
224       a list of columns and a hashref of hashes of arguments for each column.
225       If called with an object like for editing, the inputs will have the
226       object's values.
227
228         $self->to_cgi(); # uses $self->columns;  # most used
229         $self->to_cgi(qw/brewery style rating/); # sometimes
230         # and on rare occassions this is desireable if you have a lot of fields
231         # and dont want to call to_field a bunch of times just to tweak one or
232         # two of them.
233         $self->to_cgi(@cols, {brewery => {
234                                                                                how => 'textfield' # too big for select
235                                                                          },
236                                                       style   => {
237                                                                                column_nullable => 0,
238                                                                                how => 'select',
239                                                                                items => ['Ale', 'Lager']
240                                                                          }
241                                                       });
242
243       to_field($field [, $how][, $args])
244
245       This maps an individual column to a form element. The "how" argument
246       can be used to force the field type into any you want. All that you
247       need is a method named "_to_$how" in your class. Your class inherits
248       many from AsForm  already.
249
250       If "how" is specified but the class cannot call the method it maps to,
251       then AsForm will issue a warning and the default input will be made.
252       You can write your own "_to_$how" methods and AsForm comes with many.
253       See "HOW Methods". You can also pass this argument in $args->{how}.
254
255       search_inputs
256
257         my $cgi = $class->search_inputs ([$args]); # optional $args
258
259       Returns hash or hashref of search inputs elements for a class making
260       sure the inputs are empty of any initial values.  You can specify what
261       columns you want inputs for in $args->{columns} or by the method
262       "search_columns". The default is  "display_columns".  If you want to te
263       search on columns in related classes you can do that by specifying a
264       one element hashref in place of the column name where the key is the
265       related "column" (has_a or has_many method for example) and the value
266       is a list ref of columns to search on in the related class.
267
268       Example:
269         sub  BeerDB::Beer::search_columns {       return ( 'name' , 'rating',
270       { brewery => [ 'name', 'location'] } );
271         }
272
273         # Now foreign inputs are made for Brewery name and location and the
274         # there will be no name clashing and processing can be automated.
275
276       unselect_element
277
278         unselect any selected elements in a HTML::Element select list widget
279
280       _field_from_how($field, $how,$args)
281
282       Returns an input element based the "how" parameter or nothing at all.
283       Override at will.
284
285       _field_from_relationship($field, $args)
286
287       Returns an input based on the relationship associated with the field or
288       nothing.  Override at will.
289
290       For has_a it will give select box
291
292       _field_from_column($field, $args)
293
294       Returns an input based on the column's characteristics, namely type, or
295       nothing.  Override at will.
296
297       recognized arguments
298
299         selected => $object⎪$id,
300         name     => $name,
301         value    => $value,
302         where    => SQL 'WHERE' clause,
303         order_by => SQL 'ORDER BY' clause,
304         constraint => hash of constraints to search
305         limit    => SQL 'LIMIT' clause,
306         items    => [ @items_of_same_type_to_select_from ],
307         class => $class_we_are_selecting_from
308         stringify => $stringify_coderef⎪$method_name
309
310       # select box requirements # 1. a select box for objecs of a has_a
311       related class -- DONE =head2  1. a select box out of a has_a or
312       has_many related class.
313         # For has_a the default behavior is to make a select box of every
314       element in
315         # related class and you choose one.
316         #Or explicitly you can create one and pass options like where and
317       order
318         BeerDB::Beer->to_field('brewery','select', {where => "location =
319       'Germany'");
320
321         # For has_many the default is to get a multiple select box with all objects.
322         # If called as an object method, the objects existing ones will be selected.
323         Brewery::BeerDB->to_field('beers','select', {where => "rating > 5"});
324
325       2. a select box for objects of arbitrary class -- say BeerDB::Beer for
326       fun. # general BeerDB::Beer->to_field('', 'select', $options)
327
328         BeerDB::Beer->to_field('', 'select'); # Select box of all the rows in class
329                                                                         # with PK as ID, $Class->to_field() same.
330         BeerDB::Beer->to_field('','select',{ where => "rating > 3 AND class like 'Ale'", order_by => 'rating DESC, beer_id ASC' , limit => 10});
331         # specify exact where clause
332
333       3. If you already have a list of objects to select from  --
334
335         BeerDB:;Beer->to_field($col, 'select' , {items => $objects});
336
337       # 3. a select box for arbitrary set of objects
338        # Pass array ref of objects as first arg rather than field
339        $any_class_or_obj->to_field([BeerDB::Beer->search(favorite => 1)],
340       'select',);
341
342       _to_enum_select
343
344       Returns a select box for the an enum column type.
345
346       _to_bool_select
347
348       Returns a "No/Yes"  select box for a boolean column type.
349
350       _to_hidden($field, $args)
351
352       This makes a hidden html element input. It uses the "name" and "value"
353       arguments. If one or both are not there, it will look for an object in
354       "items->[0]" or the caller. Then it will use $field or the primary key
355       for name  and the value of the column by the derived name.
356
357       _to_link_hidden($col, $args)
358
359       Makes a link with a hidden input with the id of $obj as the value and
360       name.  Name defaults to the objects primary key. The object defaults to
361       self.
362
363       _to_foreign_inputs
364
365       Creates inputs for a foreign class, usually related to the calling
366       class or object. In names them so they do not clash with other names
367       and so they can be processed generically.  See _rename_foreign_inputs
368       below  and Maypole::Model::CDBI::FromCGI::classify_foreign_inputs.
369
370       Arguments this recognizes are :
371
372               related_meta -- if you have this, great, othervise it will determine or die
373               columns  -- list of columns to make inputs for
374               request (r) -- TODO the Maypole request so we can see what action
375
376       _hash_selected
377
378       *Function* to make sense out of the "selected" argument which has val‐
379       ues of the options that should be selected by default when making a
380       select box.  It can be in a number formats.  This method returns a map
381       of which options to select with the values being the keys in the map (
382       {val1 => 1, val2 = 1} ).
383
384       Currently this method  handles the following formats for the "selected"
385       argument and in the following ways
386
387         Object                                -- uses the id method  to get the value
388         Scalar                                -- assumes it *is* the value
389         Array ref of objects  -- same as Object
390         Arrays of data                -- uses the 0th element in each
391         Hashes of data                -- uses key named 'id'
392
393       _select_guts
394
395       Internal api  method to make the actual select box form elements.  the
396       data.
397
398       Items to make options out of can be
399         Hash, Array,
400         Array of CDBI objects.
401         Array of scalars ,
402         Array or  Array refs with cols from class,
403         Array of hashes
404
405       _options_from_objects ( $objects, $args);
406
407       Private method to makes a options out of  objects. It attempts to call
408       each objects stringify method specified in $args->{stringify} as the
409       content. Otherwise the default stringification prevails.
410
411       *Note only  single primary keys supported
412
413       _to_checkbox
414
415       Makes a checkbox element -- TODO
416
417       _to_radio
418
419       Makes a radio button element -- TODO
420
421       _rename_foreign_input
422
423       _rename_foreign_input($html_el_or_hash_of_them); # changes made by ref‐
424       erence
425
426       Recursively renames the foreign inputs made by _to_foreign_inputs so
427       they can be processed generically.  It uses foreign_input_delimiter.
428
429       So if an Employee is a Person who has_many  Addresses and you call and
430       the method 'foreign_input_delimiter' returns '__AF__' then
431
432         Employee->to_field("person");
433
434       will get inputs for the Person as well as their Address (by default,
435       override _field_from_relationship to change logic) named like this:
436
437         person__AF__address__AF__street
438         person__AF__address__AF__city
439         person__AF__address__AF__state
440         person__AF__address__AF__zip
441
442       And the processor would know to create this address, put the address id
443       in person->{address} data slot, insert the person and put the person id
444       in the employee->{person} data slot and then insert the employee with
445       that data.
446
447       foreign_input_delimiter
448
449       This tells AsForm what to use to delmit forieign input names. This is
450       important to avoid name clashes as well as automating processing of
451       forms.
452
453       _box($value)
454
455       This functions computes the dimensions of a textarea based on the value
456       or the defaults.
457

CHANGES

459       1.0 15-07-2004 -- Initial version =head1 MAINTAINER
460
461       Maypole Developers
462

AUTHORS

464       Peter Speltz, Aaron Trevena
465

AUTHORS EMERITUS

467       Simon Cozens, Tony Bowden
468

TODO

470         Documenting
471         Testing - lots
472         chekbox generalization
473         radio generalization
474         select work
475         Make link_hidden use standard make_url stuff when it gets in Maypole
476         How do you tell AF --" I want a has_many select box for this every time so,
477            when you call "to_field($this_hasmany)" you get a select box
478

BUGS and QUERIES

480       Please direct all correspondence regarding this module to:
481        Maypole list.
482
484       Copyright 2003-2004 by Simon Cozens / Tony Bowden
485
486       This library is free software; you can redistribute it and/or modify it
487       under the same terms as Perl itself.
488

SEE ALSO

490       Class::DBI, Class::DBI::FromCGI, HTML::Element.
491
492
493
494perl v5.8.8                       2005-11-23   Maypole::Model::CDBI::AsForm(3)
Impressum