| 1 |
package HTML::FormHandler::Manual::Cookbook; |
| 2 |
# ABSTRACT: FormHandler use recipes |
| 3 |
|
| 4 |
__END__ |
| 5 |
|
| 6 |
=pod |
| 7 |
|
| 8 |
=encoding UTF-8 |
| 9 |
|
| 10 |
=head1 NAME |
| 11 |
|
| 12 |
HTML::FormHandler::Manual::Cookbook - FormHandler use recipes |
| 13 |
|
| 14 |
=head1 VERSION |
| 15 |
|
| 16 |
version 0.410002 |
| 17 |
|
| 18 |
=head1 SYNOPSIS |
| 19 |
|
| 20 |
L<Manual Index|HTML::FormHandler::Manual> |
| 21 |
|
| 22 |
Collection of use recipes for L<HTML::FormHandler> |
| 23 |
|
| 24 |
=head2 No form file, no template file... |
| 25 |
|
| 26 |
I had to create a tiny little form this week for admins to enter a comment, and |
| 27 |
it seemed silly to have to create a form file and a template file. I remembered |
| 28 |
that you can set the TT 'template' to a string reference and not use a template |
| 29 |
at all, which is nice when FormHandler will create the form HTML for you anyway. |
| 30 |
|
| 31 |
sub comment : Chained('base_sub') PathPart('comment') Args(0) { |
| 32 |
my ( $self, $c ) = @_; |
| 33 |
|
| 34 |
my $form = HTML::FormHandler->new( field_list => |
| 35 |
[ comment => { type => 'Text', size => 60 }, |
| 36 |
submit => {type => 'Submit'} ] ); |
| 37 |
$form->process($c->req->params); |
| 38 |
if ( $form->validated ) { |
| 39 |
$self->admin_log( $c, "Admin::Queue", "admin comment", |
| 40 |
$form->field('comment')->value ); |
| 41 |
$c->flash( message => 'Comment added' ); |
| 42 |
$c->res->redirect( $c->stash->{urilist}->{view} ); |
| 43 |
} |
| 44 |
my $rendered_form = $form->render; |
| 45 |
$c->stash( template => \$rendered_form ); |
| 46 |
} |
| 47 |
|
| 48 |
This creates the form on the fly with a comment field and a submit button, |
| 49 |
renders it using the default TT wrappers, then logs the comment. No other files |
| 50 |
at all.... |
| 51 |
|
| 52 |
FormHandler isn't really necessary for validation here, but it does make it |
| 53 |
possible to have a simple, standalone method. |
| 54 |
|
| 55 |
=head2 Dynamically change the active fields |
| 56 |
|
| 57 |
A common use case is for forms with some fields that should be displayed in |
| 58 |
some circumstances and not in others. There are a number of ways to do this. |
| 59 |
One way is to use the 'field_list' method: |
| 60 |
|
| 61 |
sub field_list { |
| 62 |
my $self = shift; |
| 63 |
my @fields; |
| 64 |
<build list of fields> |
| 65 |
return \@fields; |
| 66 |
} |
| 67 |
|
| 68 |
This only happens at form construction time, however. Another method that |
| 69 |
works is to define all of the possible fields in your form, and mark some |
| 70 |
of them 'inactive'; |
| 71 |
|
| 72 |
package MyApp::Variable::Form; |
| 73 |
use HTML::FormHandler::Moose; |
| 74 |
extends 'HTML::FormHandler'; |
| 75 |
|
| 76 |
has_field 'foo'; |
| 77 |
has_field 'bar' => ( inactive => 1 ); |
| 78 |
1; |
| 79 |
|
| 80 |
Set to 'active' or 'inactive' on the 'process' call: |
| 81 |
|
| 82 |
$form->process( params => $params, active => ['foo', 'bar'] ); |
| 83 |
... |
| 84 |
$form->process( params => $params, inactive => ['bar'] ); |
| 85 |
|
| 86 |
If you need to check some other state to determine whether or not a field should |
| 87 |
be active, you can do that using a Moose method modifier on 'set_active': |
| 88 |
|
| 89 |
before 'set_active' => sub { |
| 90 |
my $self = shift; |
| 91 |
$self->active(['foo', bar']) if ( <some_condition> ); |
| 92 |
}; |
| 93 |
|
| 94 |
Fields set to active/inactive on the 'process' call are automatically set back |
| 95 |
to inactive when the form is cleared, so there's no need to reset. |
| 96 |
|
| 97 |
If you want the fields activated for the life of an object, set active on new: |
| 98 |
|
| 99 |
my $form = MyApp::Form::User->new( active => ['opt_in', 'active']); |
| 100 |
|
| 101 |
=head2 Add custom attributes to FormHandler fields |
| 102 |
|
| 103 |
If you want to add custom attributes to the FormHandler fields but don't want |
| 104 |
to subclass all the fields, you can apply a role containing the new |
| 105 |
attributes to an L<HTML::FormHandler::Field> in your form. |
| 106 |
|
| 107 |
Use 'traits' on the individual fields to apply a role to field instances. |
| 108 |
Use the form attribute 'field_traits' to apply a role to all field instances in |
| 109 |
the form. |
| 110 |
|
| 111 |
package MyApp::Form::Test; |
| 112 |
use HTML::FormHandler::Moose; |
| 113 |
extends 'HTML::FormHandler'; |
| 114 |
|
| 115 |
has_field 'foo' => ( traits => ['MyApp::TraitFor::Test'] ); |
| 116 |
has '+field_traits' => ( default => sub { ['Some::Trait', 'Another::Trait'] } ); |
| 117 |
|
| 118 |
Or set the traits on new: |
| 119 |
|
| 120 |
my $form = MyApp::Form::User->new( field_traits => ['MyApp::TraitFor::Test'] ); |
| 121 |
my $form = MyApp::Form::User->new( |
| 122 |
field_list => [ '+foo' => { traits => [...] } ]); |
| 123 |
|
| 124 |
To apply the role to a field base class, use 'apply_traits' on that class: |
| 125 |
|
| 126 |
HTML::FormHandler::Field->apply_traits( 'Some::Test' ); |
| 127 |
HTML::FormHandler::Field::Text->apply_traits( 'Another::Trait' ); |
| 128 |
|
| 129 |
=head2 Select lists |
| 130 |
|
| 131 |
If you want to set the default value of a select field to 0, you can just |
| 132 |
use 'default' on the field: |
| 133 |
|
| 134 |
has_field 'license' => ( default => 0 ); |
| 135 |
|
| 136 |
If there is logic involved, you can use a 'default_<field_name>' method: |
| 137 |
|
| 138 |
sub default_license { |
| 139 |
my ( $self, $field, $item ) = @_; |
| 140 |
return 0 unless $item && $item->license_id; |
| 141 |
return $item->license_id; |
| 142 |
} |
| 143 |
|
| 144 |
If the table defining the choices for a select list doesn't include |
| 145 |
a 'no choice' choice, you can set 'empty_select' in your field if you |
| 146 |
are using FormHandler rendering: |
| 147 |
|
| 148 |
has_field 'subject_class' => ( type => 'Select', |
| 149 |
empty_select => '--- Choose Subject Class ---' ); |
| 150 |
|
| 151 |
Or you can do in a template: |
| 152 |
|
| 153 |
[% f = form.field('subject_class') %] |
| 154 |
<select id="select_sc" name="[% f.name %]"> |
| 155 |
<option value="">--- Choose Subject Class---</option> |
| 156 |
[% FOR option IN f.options %] |
| 157 |
<option value="[% option.value %]" |
| 158 |
[% IF option.value == f.fif %]selected="selected"[% END %]> |
| 159 |
[% option.label | html %]</option> |
| 160 |
[% END %] |
| 161 |
</select> |
| 162 |
|
| 163 |
You can create a custom select list in an 'options_' method: |
| 164 |
|
| 165 |
sub options_country { |
| 166 |
my $self = shift; |
| 167 |
return unless $self->schema; |
| 168 |
my @rows = |
| 169 |
$self->schema->resultset( 'Country' )-> |
| 170 |
search( {}, { order_by => ['rank', 'country_name'] } )->all; |
| 171 |
return [ map { $_->digraph, $_->country_name } @rows ]; |
| 172 |
} |
| 173 |
|
| 174 |
=head2 The database and FormHandler forms |
| 175 |
|
| 176 |
If you have to process the input data before saving to the database, and |
| 177 |
this is something that would be useful in other places besides your form, |
| 178 |
you should do that processing in the DBIx::Class result class. |
| 179 |
|
| 180 |
If the pre-processing is only relevant to HTML form input, you might want |
| 181 |
to do it in the form by setting a flag to prevent database updates, performing |
| 182 |
the pre-processing, and then updating the database yourself. |
| 183 |
|
| 184 |
has_field 'my_complex_field' => ( type => 'Text', noupdate => 1 ); |
| 185 |
|
| 186 |
The 'noupdate' flag is set in order to skip an attempt to update the database |
| 187 |
for this field (it would not be necessary if the field doesn't actually exist |
| 188 |
in the database...). You can process the input for the non-updatable field |
| 189 |
field in a number of different places, depending on what is most logical. |
| 190 |
Some of the choices are: |
| 191 |
|
| 192 |
1) validate (for the form or field) |
| 193 |
2) validate_model |
| 194 |
3) update_model |
| 195 |
|
| 196 |
When the field is flagged 'writeonly', the value from the database will not |
| 197 |
be used to fill in the form (put in the C<< $form->fif >> hash, or the |
| 198 |
field C<< $field->fif >>), but a value entered in the form WILL be used |
| 199 |
to update the database. |
| 200 |
|
| 201 |
If you want to enter fields from an additional table that is related to |
| 202 |
this one in a 'single' relationship, you can use the DBIx::Class 'proxy' |
| 203 |
feature to create accessors for those fields. |
| 204 |
|
| 205 |
=head2 Set up form base classes or roles for your application |
| 206 |
|
| 207 |
You can add whatever attributes you want to your form classes. Maybe you |
| 208 |
want to save a title, or a particular navigation widget. You could even |
| 209 |
save bits of text, or retrieve them from the database. |
| 210 |
|
| 211 |
package MyApp::Form::Base; |
| 212 |
use Moose; |
| 213 |
extends 'HTML::FormHandler::Model::DBIC'; |
| 214 |
|
| 215 |
has 'title' => ( isa => 'Str', is => 'rw' ); |
| 216 |
has 'nav_bar' => ( isa => 'Str', is => 'rw' ); |
| 217 |
has_block 'reg_header' => ( tag => 'fieldset', label => 'Registration form', |
| 218 |
content => 'We take your membership seriously...' ); |
| 219 |
|
| 220 |
sub summary { |
| 221 |
my $self = shift; |
| 222 |
my $schema = $self->schema; |
| 223 |
my $text = $schema->resultset('Summary')->find( ... )->text; |
| 224 |
return $text; |
| 225 |
} |
| 226 |
1; |
| 227 |
|
| 228 |
Then: |
| 229 |
|
| 230 |
package MyApp::Form::Whatsup; |
| 231 |
use Moose; |
| 232 |
extends 'MyApp::Form::Base'; |
| 233 |
|
| 234 |
has '+title' => ( default => 'This page is an example of what to expect...' ); |
| 235 |
has '+nav_bar' => ( default => ... ); |
| 236 |
... |
| 237 |
1; |
| 238 |
|
| 239 |
And in the template: |
| 240 |
|
| 241 |
<h1>[% form.title %]</h1> |
| 242 |
[% form.nav_bar %] |
| 243 |
[% form.block('reg_header')->render %] |
| 244 |
<p><b>Summary: </b>[% form.summary %]</p> |
| 245 |
|
| 246 |
Or you can make these customizations Moose roles. |
| 247 |
|
| 248 |
package MyApp::Form::Role::Base; |
| 249 |
use Moose::Role; |
| 250 |
... |
| 251 |
|
| 252 |
package MyApp::Form::Whatsup; |
| 253 |
use Moose; |
| 254 |
with 'MyApp::Form::Role::Base'; |
| 255 |
... |
| 256 |
|
| 257 |
=head2 Split up your forms into reusable pieces |
| 258 |
|
| 259 |
An address field: |
| 260 |
|
| 261 |
package Form::Field::Address; |
| 262 |
use HTML::FormHandler::Moose; |
| 263 |
extends 'HTML::FormHandler::Field::Compound'; |
| 264 |
|
| 265 |
has_field 'street'; |
| 266 |
has_field 'city'; |
| 267 |
has_field 'state' => ( type => 'Select', options_method => \&options_state ); |
| 268 |
has_field 'zip' => ( type => '+Zip' ); |
| 269 |
|
| 270 |
sub options_state { |
| 271 |
... |
| 272 |
} |
| 273 |
|
| 274 |
no HTML::FormHandler::Moose; |
| 275 |
1; |
| 276 |
|
| 277 |
A person form that includes an address field: |
| 278 |
|
| 279 |
package Form::Person; |
| 280 |
use HTML::FormHandler::Moose; |
| 281 |
extends 'HTML::FormHandler'; |
| 282 |
|
| 283 |
has '+widget_name_space' => ( default => sub {['Form::Field']} ); |
| 284 |
has_field 'name'; |
| 285 |
has_field 'telephone'; |
| 286 |
has_field 'email' => ( type => 'Email' ); |
| 287 |
has_field 'address' => ( type => 'Address' ); |
| 288 |
|
| 289 |
sub validate_name { |
| 290 |
.... |
| 291 |
} |
| 292 |
|
| 293 |
no HTML::FormHandler::Moose; |
| 294 |
1; |
| 295 |
|
| 296 |
Or you can use roles; |
| 297 |
|
| 298 |
package Form::Role::Address; |
| 299 |
use HTML::FormHandler::Moose::Role; |
| 300 |
|
| 301 |
has_field 'street'; |
| 302 |
has_field 'city'; |
| 303 |
has_field 'state' => ( type => 'Select' ); |
| 304 |
has_field 'zip' => ( type => '+Zip' ); |
| 305 |
|
| 306 |
sub options_state { |
| 307 |
... |
| 308 |
} |
| 309 |
|
| 310 |
no HTML::FormHandler::Moose::Role; |
| 311 |
1; |
| 312 |
|
| 313 |
You could make roles that are collections of validations: |
| 314 |
|
| 315 |
package Form::Role::Member; |
| 316 |
use Moose::Role; |
| 317 |
|
| 318 |
sub check_zip { |
| 319 |
... |
| 320 |
} |
| 321 |
sub check_email { |
| 322 |
... |
| 323 |
} |
| 324 |
|
| 325 |
1; |
| 326 |
|
| 327 |
And if the validations apply to fields with different names, specify the |
| 328 |
'validate_method' on the fields: |
| 329 |
|
| 330 |
with 'Form::Role::Member'; |
| 331 |
has_field 'zip' => ( type => 'Integer', validate_method => \&check_zip ); |
| 332 |
|
| 333 |
=head2 Access a user record in the form |
| 334 |
|
| 335 |
You might need the user_id to create specialized select lists, or do other form processing. Add a user_id attribute to your form: |
| 336 |
|
| 337 |
has 'user_id' => ( isa => 'Int', is => 'rw' ); |
| 338 |
|
| 339 |
Then pass it in when you process the form: |
| 340 |
|
| 341 |
$form->process( item => $item, params => $c->req->parameters, user_id => $c->user->user_id ); |
| 342 |
|
| 343 |
=head2 Handle extra database fields |
| 344 |
|
| 345 |
If there is another database field that needs to be updated when a row is |
| 346 |
created, add an attribute to the form, and then process it with |
| 347 |
C< before 'update_model' >. |
| 348 |
|
| 349 |
In the form: |
| 350 |
|
| 351 |
has 'hostname' => ( isa => 'Int', is => 'rw' ); |
| 352 |
|
| 353 |
before 'update_model' => sub { |
| 354 |
my $self = shift; |
| 355 |
$self->item->hostname( $self->hostname ); |
| 356 |
}; |
| 357 |
|
| 358 |
Then just use an additional parameter when you create/process your form: |
| 359 |
|
| 360 |
$form->process( item => $item, params => $params, hostname => $c->req->host ); |
| 361 |
|
| 362 |
Some kinds of DB relationships need to have primary keys which might be more easily |
| 363 |
set in the update_model method; |
| 364 |
|
| 365 |
sub update_model { |
| 366 |
my $self = shift; |
| 367 |
my $values = $self->values; |
| 368 |
$values->{some_field}->{some_key} = 'some_value'; |
| 369 |
$self->_set_value($values); |
| 370 |
$self->next::method; |
| 371 |
} |
| 372 |
|
| 373 |
If you need to access a database field in order to create the value for a |
| 374 |
form field you can use a C< default_* > method. |
| 375 |
|
| 376 |
sub default_myformfield { |
| 377 |
my ($self, $field, $item) = @_; |
| 378 |
return unless defined $item; |
| 379 |
my $databasefield = $item->databasefield; |
| 380 |
my $value = ... # do stuff |
| 381 |
return $value; |
| 382 |
} |
| 383 |
|
| 384 |
=head2 Additional changes to the database |
| 385 |
|
| 386 |
If you want to do additional database updates besides the ones that FormHandler |
| 387 |
does for you, the best solution would generally be to add the functionality to |
| 388 |
your result source or resultset classes, but if you want to do additional updates |
| 389 |
in a form you should use an 'around' method modifier and a transaction: |
| 390 |
|
| 391 |
around 'update_model' => sub { |
| 392 |
my $orig = shift; |
| 393 |
my $self = shift; |
| 394 |
my $item = $self->item; |
| 395 |
|
| 396 |
$self->schema->txn_do( sub { |
| 397 |
$self->$orig(@_); |
| 398 |
|
| 399 |
<perform additional updates> |
| 400 |
}); |
| 401 |
}; |
| 402 |
|
| 403 |
=head2 Doing cross validation in roles |
| 404 |
|
| 405 |
In a role that handles a number of different fields, you may want to |
| 406 |
perform cross validation after the individual fields are validated. |
| 407 |
In the form you could use the 'validate' method, but that doesn't help |
| 408 |
if you want to keep the functionality packaged in a role. Instead you |
| 409 |
can use the 'after' method modifier on the 'validate' method: |
| 410 |
|
| 411 |
package MyApp::Form::Roles::DateFromTo; |
| 412 |
|
| 413 |
use HTML::FormHandler::Moose::Role; |
| 414 |
has_field 'date_from' => ( type => 'Date' ); |
| 415 |
has_field 'date_to' => ( type => 'Date' ); |
| 416 |
|
| 417 |
after 'validate' => sub { |
| 418 |
my $self = shift; |
| 419 |
$self->field('date_from')->add_error('From date must be before To date') |
| 420 |
if $self->field('date_from')->value gt $self->field('date_to')->value; |
| 421 |
}; |
| 422 |
|
| 423 |
=head2 Changing required flag |
| 424 |
|
| 425 |
Sometimes a field is required in one situation and not required in another. |
| 426 |
You can use a method modifier before 'validate_form': |
| 427 |
|
| 428 |
before 'validate_form' => sub { |
| 429 |
my $self = shift; |
| 430 |
my $required = 0; |
| 431 |
$required = 1 |
| 432 |
if( $self->params->{field_name} eq 'something' ); |
| 433 |
$self->field('some_field')->required($required); |
| 434 |
}; |
| 435 |
|
| 436 |
This happens before the fields contain input or values, so you would need to |
| 437 |
look at the param value. If you need the validated value, it might be better |
| 438 |
to do these sort of checks in the form's 'validate' routine. |
| 439 |
|
| 440 |
sub validate { |
| 441 |
my $self = shift; |
| 442 |
$self->field('dependent_field')->add_error("Field is required") |
| 443 |
if( $self->field('some_field')->value eq 'something' && |
| 444 |
!$self->field('dependent_field')->has_value); |
| 445 |
} |
| 446 |
|
| 447 |
In a Moose role you would need to use a method modifier instead. |
| 448 |
|
| 449 |
after 'validate' => sub { ... }; |
| 450 |
|
| 451 |
Don't forget the dependency list, which is used for cases where if any of one |
| 452 |
of a group of fields has a value, all of the fields are required. |
| 453 |
|
| 454 |
=head2 Supply an external coderef for validation |
| 455 |
|
| 456 |
There are situations in which you need to use a subroutine for validation |
| 457 |
which is not logically part of the form. It's possible to pass in a context |
| 458 |
or other sort of pointer and call the routine in the form's validation |
| 459 |
routine, but that makes the architecture muddy and is not a clear separation |
| 460 |
of concerns. |
| 461 |
|
| 462 |
This is an example of how to supply a coderef when constructing the form that |
| 463 |
performs validation and can be used to set an appropriate error |
| 464 |
using L<Moose::Meta::Attribute::Native::Trait::Code>. |
| 465 |
(Thanks to Florian Ragwitz for this excellent idea...) |
| 466 |
|
| 467 |
Here's the form: |
| 468 |
|
| 469 |
package SignupForm; |
| 470 |
use HTML::FormHandler::Moose; |
| 471 |
extends 'HTML::FormHandler'; |
| 472 |
|
| 473 |
has check_name_availability => ( |
| 474 |
traits => ['Code'], |
| 475 |
isa => 'CodeRef', |
| 476 |
required => 1, |
| 477 |
handles => { name_available => 'execute', }, |
| 478 |
); |
| 479 |
|
| 480 |
has_field 'name'; |
| 481 |
has_field 'email'; |
| 482 |
|
| 483 |
sub validate { |
| 484 |
my $self = shift; |
| 485 |
my $name = $self->value->{name}; |
| 486 |
if ( defined $name && length $name && !$self->name_available($name) ) { |
| 487 |
$self->field('name')->add_error('That name is taken already'); |
| 488 |
} |
| 489 |
} |
| 490 |
1; |
| 491 |
|
| 492 |
And here's where the coderef is passed in to the form. |
| 493 |
|
| 494 |
package MyApp::Signup; |
| 495 |
use Moose; |
| 496 |
|
| 497 |
has 'form' => ( is => 'ro', builder => 'build_form' ); |
| 498 |
sub build_form { |
| 499 |
my $self = shift; |
| 500 |
return SignupForm->new( |
| 501 |
{ |
| 502 |
check_name_availability => sub { |
| 503 |
my $name = shift; |
| 504 |
return $self->username_available($name); |
| 505 |
}, |
| 506 |
} |
| 507 |
); |
| 508 |
|
| 509 |
} |
| 510 |
sub username_available { |
| 511 |
my ( $self, $name ) = @_; |
| 512 |
# perform some sort of username availability checks |
| 513 |
} |
| 514 |
1; |
| 515 |
|
| 516 |
=head2 Example of a form with custom database interface |
| 517 |
|
| 518 |
The default DBIC model requires that the form structure match the database |
| 519 |
structure. If that doesn't work - you need to present the form in a different |
| 520 |
way - you may need to fudge it by creating your own 'init_object' and doing |
| 521 |
the database updates in the 'update_model' method. |
| 522 |
|
| 523 |
Here is a working example for a 'family' object (equivalent to a 'user' |
| 524 |
record') that has a relationship to permission type roles in a relationship |
| 525 |
'user_roles'. |
| 526 |
|
| 527 |
package My::Form::AdminRoles; |
| 528 |
use HTML::FormHandler::Moose; |
| 529 |
extends 'HTML::FormHandler'; |
| 530 |
|
| 531 |
has 'schema' => ( is => 'ro', required => 1 ); # Note 1 |
| 532 |
has '+widget_wrapper' => ( default => 'None' ); # Note 2 |
| 533 |
|
| 534 |
has_field 'admin_roles' => ( type => 'Repeatable' ); # Note 3 |
| 535 |
has_field 'admin_roles.family' => ( type => 'Hidden' ); # Note 4 |
| 536 |
has_field 'admin_roles.family_id' => ( type => 'PrimaryKey' ); # Note 5 |
| 537 |
has_field 'admin_roles.admin_flag' => ( type => 'Boolean', label => 'Admin' ); |
| 538 |
|
| 539 |
# Note 6 |
| 540 |
sub init_object { |
| 541 |
my $self = shift; |
| 542 |
|
| 543 |
my @is_admin; |
| 544 |
my @is_not_admin; |
| 545 |
my $active_families = $self->schema->resultset('Family')->search( { active => 1 } ); |
| 546 |
while ( my $fam = $active_families->next ) { |
| 547 |
my $admin_flag = |
| 548 |
$fam->search_related('user_roles', { role_id => 2 } )->count > 0 ? 1 : 0; |
| 549 |
my $family_name = $fam->name1 . ", " . $fam->name2; |
| 550 |
my $elem = { family => $family_name, family_id => $fam->family_id, |
| 551 |
admin_flag => $admin_flag }; |
| 552 |
if( $admin_flag ) { |
| 553 |
push @is_admin, $elem; |
| 554 |
} |
| 555 |
else { |
| 556 |
push @is_not_admin, $elem; |
| 557 |
} |
| 558 |
} |
| 559 |
# Note 7 |
| 560 |
# sort into admin flag first, then family_name |
| 561 |
@is_admin = sort { $a->{family} cmp $b->{family} } @is_admin; |
| 562 |
@is_not_admin = sort { $a->{family} cmp $b->{family} } @is_not_admin; |
| 563 |
return { admin_roles => [@is_admin, @is_not_admin] }; |
| 564 |
} |
| 565 |
|
| 566 |
# Note 8 |
| 567 |
sub update_model { |
| 568 |
my $self = shift; |
| 569 |
|
| 570 |
my $families = $self->schema->resultset('Family'); |
| 571 |
my $family_roles = $self->value->{admin_roles}; |
| 572 |
foreach my $elem ( @{$family_roles} ) { |
| 573 |
my $fam = $families->find( $elem->{family_id} ); |
| 574 |
my $has_admin_flag = $fam->search_related('user_roles', { role_id => 2 } )->count > 0; |
| 575 |
if( $elem->{admin_flag} == 1 && !$has_admin_flag ) { |
| 576 |
$fam->create_related('user_roles', { role_id => 2 } ); |
| 577 |
} |
| 578 |
elsif( $elem->{admin_flag} == 0 && $has_admin_flag ) { |
| 579 |
$fam->delete_related('user_roles', { role_id => 2 } ); |
| 580 |
} |
| 581 |
} |
| 582 |
} |
| 583 |
|
| 584 |
Note 1: This form creates its own 'schema' attribute. You could inherit from |
| 585 |
L<HTML::FormHandler::Model::DBIC>, but you won't be using its update code, so |
| 586 |
it wouldn't add much. |
| 587 |
|
| 588 |
Note 2: The form will be displayed with a template that uses 'bare' form input |
| 589 |
fields, so 'widget_wrapper' is set to 'None' to skip wrapping the form inputs with |
| 590 |
divs or table elements. |
| 591 |
|
| 592 |
Note 3: This form consists of an array of elements, so there will be a single |
| 593 |
Repeatable form field with subfields. If you wanted to use automatic rendering, you would |
| 594 |
also need to create a 'submit' field, but in this case it will just be done |
| 595 |
in the template. |
| 596 |
|
| 597 |
Note 4: This field is actually going to be used for display purposes only, but it's |
| 598 |
a hidden field because otherwise the information would be lost when displaying |
| 599 |
the form from parameters. For this case there is no real 'validation' so it |
| 600 |
might not be necessary, but it would be required if the form needed to be |
| 601 |
re-displayed with error messages. |
| 602 |
|
| 603 |
Note 5: The 'family_id' is the primary key field, necessary for updating the |
| 604 |
correct records. |
| 605 |
|
| 606 |
Note 6: 'init_object' method: This is where the initial object is created, which |
| 607 |
takes the place of a database row for form creation. |
| 608 |
|
| 609 |
Note 7: The entries with the admin flag turned on are sorted into the beginning |
| 610 |
of the list. This is entirely a user interface choice. |
| 611 |
|
| 612 |
Note 8: 'update_model' method: This is where the database updates are performed. |
| 613 |
|
| 614 |
The Template Toolkit template for this form: |
| 615 |
|
| 616 |
<h1>Update admin status for members</h1> |
| 617 |
<form name="adminroles" method="POST" action="[% c.uri_for('admin_roles') %]"> |
| 618 |
<input class="submit" name="submit" value="Save" type="submit"> |
| 619 |
<table border="1"> |
| 620 |
<th>Family</th><th>Admin</th> |
| 621 |
[% FOREACH f IN form.field('admin_roles').sorted_fields %] |
| 622 |
<tr> |
| 623 |
<td><b>[% f.field('family').fif %]</b>[% f.field('family').render %] |
| 624 |
[% f.field('family_id').render %]</td><td> [% f.field('admin_flag').render %]</td> |
| 625 |
</tr> |
| 626 |
[% END %] |
| 627 |
</table> |
| 628 |
<input class="submit" name="submit" value="Save" type="submit"> |
| 629 |
</form |
| 630 |
|
| 631 |
The form is rendered in a simple table, with each field rendered using the |
| 632 |
automatically installed rendering widgets with no wrapper (widget_wrapper => 'None'). |
| 633 |
There are two hidden fields here, so what is actually seen is two columns, one with |
| 634 |
the user (family) name, the other with a checkbox showing whether the user has |
| 635 |
admin status. Notice that the 'family' field information is rendered twice: once |
| 636 |
as a hidden field that will allow it to be preserved in params, once as a label. |
| 637 |
|
| 638 |
The Catalyst controller action to execute the form: |
| 639 |
|
| 640 |
sub admin_roles : Local { |
| 641 |
my ( $self, $c ) = @_; |
| 642 |
|
| 643 |
my $schema = $c->model('DB')->schema; |
| 644 |
my $form = My::Form::AdminRoles->new( schema => $schema ); |
| 645 |
$form->process( params => $c->req->params ); |
| 646 |
# re-process if form validated to reload from db and re-sort |
| 647 |
$form->process( params => {}) if $form->validated; |
| 648 |
$c->stash( form => $form, template => 'admin/admin_roles.tt' ); |
| 649 |
return; |
| 650 |
} |
| 651 |
|
| 652 |
Rather than redirect to some other page after saving the form, the form is redisplayed. |
| 653 |
If the form has been validated (i.e. the 'update_model' method has been run), the |
| 654 |
'process' call is run again in order to re-sort the displayed list with admin users at |
| 655 |
the top. That could have also been done in the 'update_model' method. |
| 656 |
|
| 657 |
=head2 A form that takes a resultset, with custom update_model |
| 658 |
|
| 659 |
For updating a Repeatable field that is filled from a Resultset, and not a |
| 660 |
relationship on a single row. Creates a 'resultset' attribute to pass in |
| 661 |
a resultset. Massages the data into an array that's pointed to by an |
| 662 |
'employers' hash key, and does the reverse in the 'update_model' method. |
| 663 |
Yes, it's a kludge, but it could be worse. If you want to implement a more |
| 664 |
general solution, patches welcome. |
| 665 |
|
| 666 |
package Test::Resultset; |
| 667 |
use HTML::FormHandler::Moose; |
| 668 |
extends 'HTML::FormHandler::Model::DBIC'; |
| 669 |
|
| 670 |
has '+item_class' => ( default => 'Employer' ); |
| 671 |
has 'resultset' => ( isa => 'DBIx::Class::ResultSet', is => 'rw', |
| 672 |
trigger => sub { shift->set_resultset(@_) } ); |
| 673 |
sub set_resultset { |
| 674 |
my ( $self, $resultset ) = @_; |
| 675 |
$self->schema( $resultset->result_source->schema ); |
| 676 |
} |
| 677 |
sub init_object { |
| 678 |
my $self = shift; |
| 679 |
my $rows = [$self->resultset->all]; |
| 680 |
return { employers => $rows }; |
| 681 |
} |
| 682 |
has_field 'employers' => ( type => 'Repeatable' ); |
| 683 |
has_field 'employers.employer_id' => ( type => 'PrimaryKey' ); |
| 684 |
has_field 'employers.name'; |
| 685 |
has_field 'employers.category'; |
| 686 |
has_field 'employers.country'; |
| 687 |
|
| 688 |
sub update_model { |
| 689 |
my $self = shift; |
| 690 |
my $values = $self->values->{employers}; |
| 691 |
foreach my $row (@$values) { |
| 692 |
delete $row->{employer_id} unless defined $row->{employer_id}; |
| 693 |
$self->resultset->update_or_create( $row ); |
| 694 |
} |
| 695 |
} |
| 696 |
|
| 697 |
=head2 Server-provided dynamic value for field |
| 698 |
|
| 699 |
There are many different ways to provide values for fields. Default values can be |
| 700 |
statically provided in the form with the 'default' attribute on the field, with |
| 701 |
a default_<field_name> method in the form, with an init_object/item, and with |
| 702 |
'default_over_obj' if you have both an item/init_object and want to provide a |
| 703 |
default. |
| 704 |
|
| 705 |
has_field 'foo' => ( default => 'my_default' ); |
| 706 |
has_field 'foo' => ( default_over_obj => 'my_default' ); |
| 707 |
sub default_foo { 'my_default' } |
| 708 |
.. |
| 709 |
$form->process( init_object => { foo => 'my_default } ); |
| 710 |
$form->process( item => <object with $obj->foo method to provide default> ); |
| 711 |
|
| 712 |
If you want to change the default for the field at run time, there are a number |
| 713 |
of options. |
| 714 |
|
| 715 |
You can set the value in the init_object or item before doing process: |
| 716 |
|
| 717 |
my $foo_value = 'some calculated value'; |
| 718 |
$form->process( init_object => { foo => $foo_value } ); |
| 719 |
|
| 720 |
You can use 'update_field_list' or 'defaults' on the 'process' call: |
| 721 |
|
| 722 |
$form->process( update_field_list => { foo => { default => $foo_value } } ); |
| 723 |
-- or -- |
| 724 |
$form->process( defaults => { foo => $foo_value } ); |
| 725 |
|
| 726 |
You can set a Moose attribute in the form class, and set the default in a |
| 727 |
default_<field_name> method: |
| 728 |
|
| 729 |
package My::Form; |
| 730 |
use HTML::FormHandler::Moose; |
| 731 |
extends 'HTML::Formhandler'; |
| 732 |
|
| 733 |
has 'form_id' => ( isa => 'Str', is => 'rw' ); |
| 734 |
has_field 'foo'; |
| 735 |
sub default_foo { |
| 736 |
my $self = shift; |
| 737 |
return $self->form_id; |
| 738 |
} |
| 739 |
.... |
| 740 |
$form->process( form_id => 'my_form', params => $params ); |
| 741 |
|
| 742 |
You can set a Moose attribute in the form class and set it in an update_fields |
| 743 |
method: |
| 744 |
|
| 745 |
sub update_fields { |
| 746 |
my $self = shift; |
| 747 |
$self->field('foo')->default('my_form'); |
| 748 |
} |
| 749 |
|
| 750 |
=head2 Static form, dynamic field IDs |
| 751 |
|
| 752 |
The problem: you have a form that will be used in multiple places on a page, but you |
| 753 |
want to use a static form instead of doing 'new' for each. You can pass a form name in |
| 754 |
on the process call and use 'html_prefix' in the form: |
| 755 |
|
| 756 |
$form->process( name => '...', params => {} ); |
| 757 |
|
| 758 |
But the field 'id' attribute has already been constructed and doesn't change. |
| 759 |
|
| 760 |
Solution: apply a role to the base field class to replace the 'id' getter for the 'id' |
| 761 |
attribute with a method which constructs the 'id' dynamically. Since the role is |
| 762 |
being applied to the base field class, you can't just use 'sub id', because the |
| 763 |
'id' method defined by the 'id' attribute has precedence. So create an 'around' |
| 764 |
method modifier that replaces it in the role. |
| 765 |
|
| 766 |
package My::DynamicFieldId; |
| 767 |
use Moose::Role; |
| 768 |
around 'id' => sub { |
| 769 |
my $orig = shift; |
| 770 |
my $self = shift; |
| 771 |
my $form_name = $self->form->name; |
| 772 |
return $form_name . "." . $self->full_name; |
| 773 |
}; |
| 774 |
|
| 775 |
package My::CustomIdForm; |
| 776 |
use HTML::FormHandler::Moose; |
| 777 |
extends 'HTML::FormHandler'; |
| 778 |
|
| 779 |
has '+html_prefix' => ( default => 1 ); |
| 780 |
has '+field_traits' => ( default => sub { ['My::DynamicFieldId'] } ); |
| 781 |
|
| 782 |
has_field 'foo'; |
| 783 |
has_field 'bar'; |
| 784 |
|
| 785 |
=head2 Create different field IDs |
| 786 |
|
| 787 |
Use 'build_id_method' to give your fields a different format 'id': |
| 788 |
|
| 789 |
package MyApp::CustomId; |
| 790 |
use HTML::FormHandler::Moose; |
| 791 |
extends 'HTML::FormHandler'; |
| 792 |
|
| 793 |
has '+update_field_list' => ( default => |
| 794 |
sub { { all => { build_id_method => \&custom_id } } } ); |
| 795 |
has_field 'foo' => ( type => 'Compound' ); |
| 796 |
has_field 'foo.one'; |
| 797 |
has_field 'foo.two'; |
| 798 |
has_field 'foo.three'; |
| 799 |
sub custom_id { |
| 800 |
my $self = shift; |
| 801 |
my $full_name = $self->full_name; |
| 802 |
$full_name =~ s/\./_/g; |
| 803 |
return $full_name; |
| 804 |
} |
| 805 |
|
| 806 |
The above method provides IDs of "foo_two" and "foo_three" instead of |
| 807 |
"foo.two" and "foo.three". |
| 808 |
|
| 809 |
=head1 AUTHOR |
| 810 |
|
| 811 |
FormHandler Contributors - see HTML::FormHandler |
| 812 |
|
| 813 |
=head1 COPYRIGHT AND LICENSE |
| 814 |
|
| 815 |
This software is copyright (c) 2017 by Gerda Shank. |
| 816 |
|
| 817 |
This is free software; you can redistribute it and/or modify it under |
| 818 |
the same terms as the Perl 5 programming language system itself. |
| 819 |
|
| 820 |
=cut |