| 1 |
use strict; |
| 2 |
use warnings; |
| 3 |
use Test::More; |
| 4 |
|
| 5 |
use HTML::FormHandler::Field; |
| 6 |
|
| 7 |
# This is an example of the different ways to change an attribute of a field. |
| 8 |
# It uses the 'id' field for demonstration purposes - most of these methods |
| 9 |
# can also be used against other attributes. |
| 10 |
|
| 11 |
{ |
| 12 |
package Test::IDRole; |
| 13 |
use Moose::Role; |
| 14 |
|
| 15 |
sub build_id { |
| 16 |
my $self = shift; |
| 17 |
return "meth_role." . $self->html_name; |
| 18 |
}; |
| 19 |
} |
| 20 |
|
| 21 |
# can't use a simple method role in field_traits because |
| 22 |
# it's applied against the base field class which contains |
| 23 |
# the 'build_id' method. a method in a role won't override |
| 24 |
# a method in a class itself. It *will* override a method in |
| 25 |
# a superclass, so this kind of role can be applied against |
| 26 |
# the field subclasses |
| 27 |
# a method modifier can be used to override a field class |
| 28 |
# method |
| 29 |
{ |
| 30 |
package Test::IDRoleMM; |
| 31 |
use Moose::Role; |
| 32 |
|
| 33 |
around 'build_id' => sub { |
| 34 |
my $orig = shift; |
| 35 |
my $self = shift; |
| 36 |
return "mm_role." . $self->html_name; |
| 37 |
}; |
| 38 |
} |
| 39 |
|
| 40 |
{ |
| 41 |
package Test::Form; |
| 42 |
use HTML::FormHandler::Moose; |
| 43 |
extends 'HTML::FormHandler'; |
| 44 |
|
| 45 |
|
| 46 |
# function with lexical variable |
| 47 |
my $name = 'test_form'; |
| 48 |
my $create_id = sub { |
| 49 |
my $field_name = shift; |
| 50 |
return "$name.$field_name"; |
| 51 |
}; |
| 52 |
|
| 53 |
sub BUILD { |
| 54 |
my $self = shift; |
| 55 |
$self->field('tue')->id('my_build.tue'); |
| 56 |
} |
| 57 |
|
| 58 |
has "+name" => ( default => $name ); |
| 59 |
has_field 'foo' => ( id => 'form.foo' ); |
| 60 |
has_field 'bar' => ( id => &my_id ); |
| 61 |
has_field 'dux' => ( traits => ['Test::IDRole'] ); |
| 62 |
has_field 'pax'; |
| 63 |
has_field 'mon' => ( id => &$create_id('mon') ); |
| 64 |
has_field 'tue'; |
| 65 |
|
| 66 |
sub my_id { 'my_form.bar' } |
| 67 |
|
| 68 |
} |
| 69 |
|
| 70 |
HTML::FormHandler::Field->apply_traits('Test::IDRoleMM'); |
| 71 |
|
| 72 |
#my $form = Test::Form->new( field_traits => ['Test::IDRole'] ); |
| 73 |
my $form = Test::Form->new; |
| 74 |
ok( $form, 'form built' ); |
| 75 |
is( $form->field('foo')->id, 'form.foo', 'id attribute works' ); |
| 76 |
is( $form->field('bar')->id, 'my_form.bar', 'id function works' ); |
| 77 |
is( $form->field('dux')->id, 'meth_role.dux', 'build_id role works' ); |
| 78 |
is( $form->field('pax')->id, 'mm_role.pax', 'role with meth modifier around build_id works' ); |
| 79 |
is( $form->field('mon')->id, 'test_form.mon', 'build_id function with var' ); |
| 80 |
is( $form->field('tue')->id, 'my_build.tue', 'set id in BUILD' ); |
| 81 |
|
| 82 |
done_testing; |