The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

HTML::FormHandlerX::Field::JSON - a script tag which sets a var using JSON data, encoded from perl data supplied via field for HTML::FormHandler.

VERSION

version 0.001

SYNOPSIS

This class can be used for fields that need to supply JSON data for use by scripts in the form. It will JSONify and render the value returned by a form's data_[field_name] method, or the field's data attribute.

  has_field 'user_addresses' => ( type => 'JSON',
     data => { john => 'john@example.com', sarah => 'sarah@example.com' } );

or using a method:

  has_field 'user_addresses' => ( type => 'JSON' );
  sub data_user_addresses {
     my ( $self, $field ) = @_;
     if( $field->value == 'foo' ) {
        return { john => 'john@example.com', sarah => 'sarah@example.com' };
     } else {
        return [ 'john@example.com', 'sarah@example.com' ];
     }
  }
  #----
  has_field 'usernames' => ( type => 'JSON' );
  sub data_usernames {
      my ( $self, $field ) = @_;
      return [ qw'john sarah' ];
  }

or set the name of the rendering method:

   has_field 'user_addresses' => ( type => 'JSON', set_data => 'my_user_addresses' );
   sub my_user_addresses {
     ....
   }

or provide a 'render_method':

   has_field 'user_addresses' => ( type => 'JSON', render_method => \&render_user_addresses );
   sub render_user_addresses {
       my $self = shift;
       ....
       return '...';
   }

variable names

By default, the name of the variable being assigned is same as the field name. The variable name can be changed with the data_key attribute. If the data_key value is simple string (no dot separator) then the variable will be created with var varName;, otherwise it is assumed the variable is already defined.

The data_key can begin or end with a dot, in which case the field name is either appended or prepended to the data_key.

  has_field 'user_addresses' => ( type => 'JSON',
                data_key => '.email',
                data_ => [ qw'john@acme.org sarah@acme.org' ],
   );

Will render as:

  <script type="text/javascript">
        user_addresses.email = [ "john@acme.org", "sarah@acme.org" ];
  </script>);

FIELD OPTIONS

We support the following additional field options, over what is inherited from HTML::FormHandler::Field

do_minify

Boolean to indicate whether code should be minified using JavaScript::Minifier::XS

json_opts

Hashref with 3 possible keys; pretty, relaxed, canonical. The values are passed to JSON when encoding the data.

AUTHOR

Charlie Garrison <garrison@zeta.org.au>

COPYRIGHT AND LICENSE

This software is copyright (c) 2014 by Charlie Garrison.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.