Category Archives: Html::formhandler

Creating a Repeatable Address Form with HTML::FormHandler

This is a summary of how I created a repeatable Address Form Module, Mover::Form::Travel::Matrix, using HTML::FormHandler.

As part of my TravelTime Application project I needed to create a form to enter multiple location addresses. I could construct the form manually using Template Toolkit, but I would still need to write my own validation and JavaScript to implement the multiple form requirement.
I could have used HTML::FormFU I have used this previously(much to my regret) to build more complex forms. Not that HTML::FormFu isn’t useful. Once it is mastered it can be a great tool for building many types of complex forms. For me, I found that the learning curve was much too steep and the documentation was dispersed widely amongst many modules. I am sure that this has been improved in recent times, but I really don’t want to go back to pouring through reams of docs for this project.
So I continued on my quest to use another behemoth of CPAN complexity just to make my life more difficult. I had wanted an excuse to experiment with HTML::Formhandler and this seemed like a good time to do this. The documentation for this makes War And Peace seem like a side note on a shopping list. It must have taken longer to create than the Bible and hopefully will be less contentious. Seemingly it is the work of one developer by the name of Gerda Shank who must have locked herself away in a cave for a millennium to give the Pearl world this form framework.
What I like about HTML::FormHandler is that it seems much more Moose Like and intuitive to anybody who has worked with Moose. It seems very simple at first, however to get the best out of this, the learning curve is steep and requires time. So, say goodbye to family and social life while you get familiar with HTML::FormHandler.

FormHandler Forms

Mover::Form::Field::Address

Before I make my repeatable address form, I created a form element for any US address using a FormHandler Moose Role. This is one of the many useful things about HTML::Formhandler. You can create many building blocks which can be used again and again. Here is the module on github Mover::Form::Field::Address

.....

use HTML::FormHandler::Types qw/Zip Trim Collapse/;

has_field 'address_1' => (
    is      => 'rw', 
    isa     => Collapse, 
    required => 0,
    message  => {
        required => 'You must enter a street address!'
    }
);
has_field 'address_2' => (is => 'rw', isa => Collapse);
has_field 'city' => (is => 'rw', isa => Collapse);
has_field 'state' => ( type => 'Select', options_method => \&_options_state );
has_field 'country' => (is => 'rw', isa => Collapse);
#------ Create Zip Field Type
has_field 'zip' => ( is => 'rw',  isa => Zip);
#------------------------------------------------------------------------------
=head2 options_state
  Builds the Options for US states. (NY New York,  AL Alabama etc).
  Note: It does not include "DC". I may add DC later just as an alternative.
=cut

sub _options_state {

    return (
        'AL' => 'Alabama',
        'AK' => 'Alaska',
        'AZ' => 'Arizona',
         ...
        'WY' => 'Wyoming',
    );

}

no HTML::FormHandler::Moose::Role;
1;

When I initially created this Role, I had intended to manually validate the Zip Code field using Regexp::Common. I then found that FormHandler has a types Module with some useful stuff in there, including a zip code. I will try this out instead. It also has types to trim off extra white space. How convenient.

Mover::Form::Travel::Matrix

This is the actual HTML::FormHandler form, which has repeatable Address elements. I also opted to include some of the convenient FormHandler Widgets that were created to make use of the Twitter Bootstrap CSS framework. There’s lots of stuff available with HTML::FormHandler.
This module is available here on GitHub Mover::Form::Travel::Matrix


has '+field_name_space' => ( default => 'Mover::Form::Field' );
 
has '+name'        => ( default => $form_name );
 
has '+html_prefix' => ( default => 1 );
 
has '+is_html5'    => ( default => 1 );
 
has '+http_method' => ( default => $http_method );
 
has '+action'      => ( default => $form_action );

#----- Mover::Form::Field::Address that is Repeatable
 
has_field 'addresses' => (
    type         => 'Repeatable',
    setup_for_js => 1,
    do_wrapper   => 1,
    tags         => { controls_div => 1 },
    auto_id      => 1,
);

has_field 'addresses.contains' => ( type => 'Address', );
 
has_field 'submit' => (
    type         => 'Submit',
    widget       => 'ButtonTag',
    element_attr => { class => [ 'btn', $button_class, $button_size ] },
    do_wrapper   => 0,
    value        => 'Get Travel Time'
);
 
has '+info_message'    => ( default => 'Starting point.' );
 
has '+success_message' => ( default => 'Form successfully submitted' );

has '+error_message'   => ( default => 'Please fix the errors on this form!' );

Now, we have a form with a repeatable address field and some fancy Bootstrap CSS, Yippee!
Next up is to create some templates to render the form pages. So, I will use the now familiar Template Toolkit to do this.

The Address Form Template

travel_time.tt

<!-- Travel Matrix Form -->
<form name="[% tm_form.name %]" id="[% tm_form.name %]"
  action="[% tm_form.action %]" method="[% tm_form.http_method %]"
  class="form-vertical" >


<fieldset >
   <legend>
      <p class="lead">
         [%- 
             travel_time_heading 
             || 'Calculate Moving Truck Travel Time'
         -%]
      </p>
   </legend>

<!--  Start messages -->
    <div id="messages">
    <p class="text-success">[%- success_message -%]</p>
    <p class="text-error">[%- error_message -%]</p>
    <p class="text-warning">[%- warning_message -%]</p>
    <p class="text-info">[%- info_message  -%]</p>
    </div>
<!-- End  messages -->

    [% started_new_row  = 0  %]  [%# To specify how many Addresses per line %]
    <!--- four to a line -->
    [% FOREACH address_element IN tm_form.field('addresses').fields -%]
        [%  IF ((loop.count == 1) || ((loop.count % 5) == 0))   %]

          [% IF ( started_new_row == 1) %]
              <!-- Close previous row before opening a new one. -->
               </div> <!-- /row-fluid -->
          [%  END %]
          <div class="row-fluid">
          [% started_new_row  = 1 %]
        [% END %]

        <div class="span3 well">
        
          [% IF loop.first %]
              <span class="text-info">
                <abbr title='Calculations are based from a starting point in central New York City.'>
                First Address
                </abbr>
              </span>
          [% ELSIF loop.last  %] 
              <span class="text-info">
                  <abbr title='The next version will have an option for more destination points.'>
                  Last Address</abbr>
              </span>

          [% ELSE %]
              <span class='text-info'>Address [% loop.count %]</span>
          [% END %]
          
          [% address_element.render %]

        </div> <!-- /span3 -->
    [% END %]

    [% IF ( started_new_row == 1) %] [%# Close div tag at end of each row %]
        </div> <!-- /row-fluid -->
        [% started_new_row  = 0 %]
    [%  END %]



<div class="row-fluid">
    [% tm_form.field('submit').render %]
</div> <!-- /row-fluid -->
</fieldset>
</form>

</div> <!-- /row-fluid -->

[% IF ( tm_form.is_valid) %]

    [% IF (my_errors) %]
        <div class="alert alert-error">
        <span><b>[% error_message  || 'What a mess!' %]</b></span>
        [%# One way to loop through a hash %]
        [% FOREACH error IN my_errors.values %]
         <span> [% error %]</span>
         [% END %]
        </div>
    [%  END %]
    
[% ELSIF ( tm_form.errors) %]
    <div class="alert alert-error row-fluid">
        [% FOREACH error IN tm_form.errors -%]
        <span class="span2">[% error %]</span>
        [% END %]
    </div>
[%  END %]

The source code for this template is available here.
There are many other ways to render a HTML::Formhandler form, which you can explore in the CPAN documentation.

There is much to explore in HTML::FormHandler and I am sure I will be using it again in future projects.

Perl Google Distance Matrix API Interface

This is my Perl Module Google::Travel::Matrix, which will be an interface to the Google Distance Matrix API. I will use this for calculating distance and travel times between multiple locations.

Google Distance Matrix API Interface

Google::Travel::Matrix

This module provides an interface with the Google Distance Matrix API. It will return the distance between given locations in JSON format.
It will accept one or many “Origin” addresses in String, Array or Hash format.It will also accept many Destination addresses. The Google Matrix configuration attributes can be set here, but it may be easier just to accept the defaults that I built in unless you have other specific requirements.
I used the Perl Moose Object framework as it does a really great job of helping set up the configuration attributes using Moose Types and coercion. It will also make it easier for me to build my sub classes.
The module is available here on GitHub, Google::Travel::Matrix


=head2 get_all_elements
 Given the Google Distance Matrix output as a scalar reference to a Perl data
 structure, returns an ArrayRef of Matrix elements or undef.
 If no Google Output data passed, then it will create one using the Origin and
 destination addresses;
 It would be a good idea to check that the Google Matrix Return is 'OK' before calling
 this method.
=cut

sub get_all_elements {
    my $self = shift;
    my $matrix = shift || $self->get_google_matrix_data_as_scalar_ref();

    my $google_status = $self->get_matrix_status_message($matrix);

    if ( ( not $google_status ) || ( $google_status ne $VALID_REQ ) ) {

        $log->debug( 'Google return status message is: '
              . ( $google_status // 'No Google Status' ) );
        return $FAIL;
    }

    #------ Preserve the Original address sent to Google
    #       as it may be needed later.
    #       Yet again,  this is something I would prefer 
    #       to put into a Child Class
    my $original_origins      = $self->_get_array_of_origins();
    my $original_destinations = $self->_get_array_of_destinations();

    #------ Get each combination for the origin destination addresses
    my $origin_ct = 0;
    my @elements_array;
    foreach my $origin_addr ( @{ $self->get_matrix_origin_addresses($matrix) } )
    {
        my $original_origin_addr = $original_origins->[ $origin_ct++ ];
        $log->debug( 'Original origin address is : ' . $original_origin_addr );

        #---Get results for current origination address
        my $row = shift @{ $matrix->{rows} };

        #------ Match origination address with all destination addresses
        my $dest_ct = 0;
        foreach my $destination_addr (
            @{ $self->get_matrix_destination_addresses($matrix) } )
        {

            my $original_destination_addr =
              $original_destinations->[ $dest_ct++ ];

            $log->debug( 'Original destination address is : '
                  . $original_destination_addr );

           #----- get the result for the current Origination -> Destination pair
            my $element = shift @{ $row->{elements} };

            push @elements_array,
              {
                origin_address               => $origin_addr,
                destination_address          => $destination_addr,
                original_origin_address      => $original_origin_addr,
                original_destination_address => $original_destination_addr,
                element_status               => $element->{status},
                element_duration_text        => $element->{duration}{text},
                element_duration_value       => $element->{duration}{value},
                element_distance_text        => $element->{distance}{text},
                element_distance_value       => $element->{distance}{value},
              };
        }
    }
    $log->debug(
        'Array of all elements returned by Google:  ' . dump @elements_array );
    return \@elements_array;
}

This is far from being a completed masterpiece, but for now it will get me what I need. I intentionally didn’t allow for receiving the data in XML format, as Google recommends JSON format.I may add XML processing at a later date.I may even consider refactoring it from Moose to Moo, to make it lighter and nimbler.
I also plan to create a subclass class to Google::Travel::Time that will do the actual conversion from distance to a travel time acceptable to the NYC moving and storage industry. Until then, I don’t consider this module to be CPAN worthy.