[Catalyst-commits] r12139 - trunk/examples/CatalystAdvent/root/2009/pen

alexn_org at dev.catalyst.perl.org alexn_org at dev.catalyst.perl.org
Tue Dec 1 22:03:48 GMT 2009


Author: alexn_org
Date: 2009-12-01 22:03:48 +0000 (Tue, 01 Dec 2009)
New Revision: 12139

Modified:
   trunk/examples/CatalystAdvent/root/2009/pen/formhandler.pod
Log:
added custom type

Modified: trunk/examples/CatalystAdvent/root/2009/pen/formhandler.pod
===================================================================
--- trunk/examples/CatalystAdvent/root/2009/pen/formhandler.pod	2009-12-01 21:42:58 UTC (rev 12138)
+++ trunk/examples/CatalystAdvent/root/2009/pen/formhandler.pod	2009-12-01 22:03:48 UTC (rev 12139)
@@ -132,6 +132,11 @@
           data_type   => 'text',
           is_nullable => 1,
       },
+      rank => {
+          data_type => 'decimal',
+          size        => [3, 2],
+  	  is_nullable => 1,	  
+      },
       
   );  
   __PACKAGE__->set_primary_key('article_id');  
@@ -264,7 +269,9 @@
   has_field 'title'    => ( type => 'Text',     required => 1 );
   has_field 'ts'       => ( type => 'Date', label => 'Published Date' );
   has_field 'content'  => ( type => 'TextArea', required => 0 );
+
   has_field 'tags_str' => ( type => 'TextArea', required => 0 );
+  has_field 'rank'     => ( type => 'Text',     default => '0.00' );
 
   1;
 
@@ -299,7 +306,7 @@
 
 =back
 
-There's only one problem ... the "tags_str" field is a
+The first problem ... the "tags_str" field is a
 textarea. HTML::FormHandler can work directly with many-to-many
 relationships, but in this case we want the editing to be as
 "free-form" as possible. So we want to specify those tags in a simple
@@ -338,6 +345,41 @@
       $self->field('tags_str')->value($value);
   };
 
+=head3 A custom type
+
+Another problem is with the "rank". We want this to be a decimal
+number between 0 and 5. One way of doing this is to define a custom
+type ...
+
+  package Blog::Form::Field::Rank;
+  
+  use HTML::FormHandler::Moose;
+  extends 'HTML::FormHandler::Field::Text';
+
+  apply(
+      [
+       { 
+  	 transform => sub {
+  	     my $value = shift;
+  	     $value =~ s/^\$//;
+  	     return $value;
+  	 }},
+       {
+  	 transform => sub { $_[0] =~ /^[\d+.]+$/ ? sprintf '%.2f', $_[0] : $_[0] },
+  	 message   => 'Value cannot be converted to a decimal',
+       },
+       {
+  	 check => sub { $_[0] =~ /^-?\d+\.?\d*$/ && $_[0] >= 0 && $_[0] <= 5 },
+  	 message => 'Rank must be a decimal number between 0 and 5'
+       }
+      ]
+      );  
+  1;
+
+And then the field declaration in the form class becomes ...
+
+  has_field 'rank' => ( type => '+Blog::Form::Field::Rank', default => '0.00' );
+
 =head2 Testing
 
 And we are done. Start your development server with ...




More information about the Catalyst-commits mailing list