HTML-Widget

 view release on metacpan or  search on metacpan

lib/HTML/Widget.pm  view on Meta::CPAN

package HTML::Widget;

use warnings;
use strict;
use base 'HTML::Widget::Accessor';
use HTML::Widget::Result;
use Scalar::Util 'blessed';
use Carp qw/croak/;

# For PAR
use Module::Pluggable::Fast
    search =>
    [qw/HTML::Widget::Element HTML::Widget::Constraint HTML::Widget::Filter/],
    require => 1;

__PACKAGE__->plugins;

__PACKAGE__->mk_accessors(
    qw/container indicator query subcontainer uploads strict empty_errors
        element_container_class xhtml_strict unwrapped explicit_ids/
);
__PACKAGE__->mk_ro_accessors(qw/implicit_subcontainer/);

# Custom attr_accessor for id provided later
__PACKAGE__->mk_attr_accessors(qw/action enctype method/);

use overload '""' => sub { return shift->attributes->{id} }, fallback => 1;

*const         = \&constraint;
*elem          = \&element;
*name          = \&id;
*tag           = \&container;
*subtag        = \&subcontainer;
*result        = \&process;
*indi          = \&indicator;
*constrain_all = \*constraint_all;

our $VERSION = '1.11';

=head1 NAME

HTML::Widget - HTML Widget And Validation Framework

=head1 NOTE

L<HTML::Widget> is no longer under active development and the current 
maintainers are instead pursuing an intended replacement (see the 
L<mailing-list|/SUPPORT> for details).

Volunteer maintainers / developers for L<HTML::Widget>, please contact 
the L<mailing-list|/SUPPORT>.

=head1 SYNOPSIS

    use HTML::Widget;

    # Create a widget
    my $w = HTML::Widget->new('widget')->method('get')->action('/');

    # Add a fieldset to contain the elements
    my $fs = $w->element( 'Fieldset', 'user' )->legend('User Details');

    # Add some elements
    $fs->element( 'Textfield', 'age' )->label('Age')->size(3);
    $fs->element( 'Textfield', 'name' )->label('Name')->size(60);
    $fs->element( 'Submit', 'ok' )->value('OK');

    # Add some constraints
    $w->constraint( 'Integer', 'age' )->message('No integer.');
    $w->constraint( 'Not_Integer', 'name' )->message('Integer.');
    $w->constraint( 'All', 'age', 'name' )->message('Missing value.');

    # Add some filters
    $w->filter('Whitespace');

    # Process
    my $result = $w->process;
    my $result = $w->process($query);


    # Check validation results
    my @valid_fields   = $result->valid;
    my $is_valid       = $result->valid('foo');
    my @invalid_fields = $result->have_errors;
    my $is_invalid     = $result->has_errors('foo');;

    # CGI.pm-compatible! (read-only)
    my $value  = $result->param('foo');
    my @params = $result->param;

    # Catalyst::Request-compatible
    my $value = $result->params->{foo};
    my @params = keys %{ $result->params };


    # Merge widgets (constraints and elements will be appended)
    $widget->merge($other_widget);


    # Embed widgets (as fieldset)
    $widget->embed($other_widget);


    # Get list of elements
    my @elements = $widget->get_elements;

    # Get list of constraints
    my @constraints = $widget->get_constraints;

    # Get list of filters
    my @filters = $widget->get_filters;


    # Complete xml result
    [% result %]
    [% result.as_xml %]


    # Iterate over elements
    <form action="/foo" method="get">
    [% FOREACH element = result.elements %]

lib/HTML/Widget.pm  view on Meta::CPAN

Arguments: $type, $name, \%attributes

Return Value: $element

Add a new element to the Widget. Each element must be given at least a type. 
The name is used to generate an id attribute on the tag created for the 
element, and for form-specific elements is used as the name attribute. The 
returned element object can be used to set further attributes, please see 
the individual element classes for the methods specific to each one.

The C<attributes> argument is equivalent to using the 
L<attributes|HTML::Widget::Element/attributes> method.

If the element starts with a name other than C<HTML::Widget::Element::>, 
you can fully qualify the name by using a unary plus:

    $self->element( "+Fully::Qualified::Name", $name );

The type can be one of the following:

=over 4

=item L<HTML::Widget::Element::Block>

    my $e = $widget->element('Block');

Add a Block element, which by default will be rendered as a C<DIV>.

    my $e = $widget->element('Block');
    $e->type('img');

=item L<HTML::Widget::Element::Button>

    my $e = $widget->element( 'Button', 'foo' );
    $e->value('bar');

Add a button element.

    my $e = $widget->element( 'Button', 'foo' );
    $e->value('bar');
    $e->content('<b>arbitrary markup</b>');
    $e->type('submit');

Add a button element which uses a C<button> html tag rather than an 
C<input> tag. The value of C<content> is not html-escaped, so may contain 
html markup.

=item L<HTML::Widget::Element::Checkbox>

    my $e = $widget->element( 'Checkbox', 'foo' );
    $e->comment('(Required)');
    $e->label('Foo');
    $e->checked('checked');
    $e->value('bar');

Add a standard checkbox element.

=item L<HTML::Widget::Element::Fieldset>

    my $e = $widget->element( 'Fieldset', 'foo' );
    $e->legend('Personal details');
    $e->element('Textfield', 'name');
    $e->element('Textarea', 'address');

Adds a nested fieldset element, which can contain further elements.

=item L<HTML::Widget::Element::Hidden>

    my $e = $widget->element( 'Hidden', 'foo' );
    $e->value('bar');

Add a hidden field. This field is mainly used for passing previously gathered
data between multiple page forms.

=item L<HTML::Widget::Element::Password>

    my $e = $widget->element( 'Password', 'foo' );
    $e->comment('(Required)');
    $e->fill(1);
    $e->label('Foo');
    $e->size(23);
    $e->value('bar');

Add a password field. This is a text field that will not show the user what
they are typing, but show asterisks instead.

=item L<HTML::Widget::Element::Radio>

    my $e = $widget->element( 'Radio', 'foo' );
    $e->comment('(Required)');
    $e->label('Foo');
    $e->checked('checked');
    $e->value('bar');

Add a radio button to a group. Radio buttons with the same name will work as
a group. That is, only one item in the group will be "on" at a time.

=item L<HTML::Widget::Element::RadioGroup>

    my $e = $widget->element( 'RadioGroup', 'name' );
    $e->comment('(Required)');
    $e->label('Foo'); # Label for whole radio group
    $e->value('bar'); # Currently selected value
    $e->labels([qw/Fu Bur Garch/]); # default to ucfirst of values

This is a shortcut to add multiple radio buttons with the same name at the
same time. See above.

=item L<HTML::Widget::Element::Reset>

    $e = $widget->element( 'Reset', 'foo' );
    $e->value('bar');

Create a reset button. The text on the button will default to "Reset", unless
you call the value() method. This button resets the form to its original
values.

=item L<HTML::Widget::Element::Select>

    my $e = $widget->element( 'Select', 'foo' );
    $e->comment('(Required)');

lib/HTML/Widget.pm  view on Meta::CPAN

        my $type = "HTML::Widget::Filter::$opt{type}";

        return grep { $_->isa($type) } @{ $self->{_filters} };
    }

    return @{ $self->{_filters} };
}

=head2 get_filters_ref

Arguments: %options

Return Value: \@filters

Accepts the same arguments as L</get_filters>, but returns an arrayref 
of results instead of a list.

=cut

sub get_filters_ref {
    my $self = shift;

    return [ $self->get_filters(@_) ];
}

=head2 get_filter

Arguments: %options

Return Value: $filter

    my @filters = $self->get_filter;
    
    my @filters = $self->get_filter( type => 'Integer' );

Similar to L</get_filters>, but only returns the first filter in the 
list.

Accepts the same arguments as L</get_filters>.

=cut

sub get_filter {
    my ( $self, %opt ) = @_;

    return ( $self->get_filters(%opt) )[0];
}

=head2 indi

=head2 indicator

Arguments: $field_name

Return Value: $field_name

Set/Get a boolean field. This is a convenience method for the user, so they 
can keep track of which of many Widget objects were submitted. It is also
used by L<Catalyst::Plugin::HTML::Widget>

=head2 legend

Arguments: $legend

Return Value: $legend

Set/Get a legend for this widget. This tag is used to label the fieldset. 

=cut

sub legend {
    my ( $self, $legend ) = @_;

    croak "'legend' not permitted at top level in xhtml_strict mode"
        if $self->xhtml_strict;

    my $top_level = $self->_get_implicit_subcontainer;
    unless ( $top_level->can('legend') ) {
        croak "implicit subcontainer does not support 'legend'";
    }

    $top_level->legend($legend);
    return $self;
}

=head2 merge

Arguments: @widgets

Arguments: $element, @widgets

Merge elements, constraints and filters from other widgets, into this one. The
elements will be added to the end of the list of elements that have been set
already.

Without an element argument, and with standard widgets, the contents of the
first top-level element of each widget will be merged into the first
top-level element of this widget.
This emulates the previous behaviour.

With an element argument, the widgets are merged into the named element.
No checks are made on whether the provided element belongs to $self.

=cut

sub merge {
    my ( $self, @widgets ) = @_;

    my $dest;
    if ( $widgets[0]->isa('HTML::Widget::Element') ) {
        croak "destination element is not a container"
            unless $widgets[0]->isa('HTML::Widget::Element::NullContainer');
        $dest = shift @widgets;
    }
    else {
        $dest = $self->_first_element;
        croak "merge only supported if destination first element is container"
            if $dest
            and not $dest->isa('HTML::Widget::Element::NullContainer');

        $dest = $self->_get_implicit_subcontainer unless $dest;
    }

    for my $widget (@widgets) {

        my $source = $widget->_first_element;
        croak "merge only supported if source first element is container"
            unless $source
            and $source->isa('HTML::Widget::Element::NullContainer');

        $dest->push_content( @{ $source->content } );

        push @{ $self->{_constraints} }, @{ $widget->{_constraints} }
            if $widget->{_constraints};
        push @{ $self->{_filters} }, @{ $widget->{_filters} }
            if $widget->{_filters};
    }
    return $self;
}

=head2 method

lib/HTML/Widget.pm  view on Meta::CPAN

            _constraints            => $self->{_constraints},
            _elements               => $self->{_elements},
            _errors                 => $errors,
            _js_callbacks           => \@js_callbacks,
            _params                 => \%params,
            subcontainer            => $self->subcontainer,
            strict                  => $self->strict,
            empty_errors            => $self->empty_errors,
            submitted               => ( $query ? 1 : 0 ),
            element_container_class => $self->element_container_class,
            implicit_subcontainer   => $self->implicit_subcontainer,
            explicit_ids            => $self->explicit_ids,
        } );
}

=head2 query

Arguments: $query

Return Value: $query

Set/Get the query object to use for validation input. The query object can also
be passed to the process method directly.

=head2 strict

Arguments: $bool

Return Value: $bool

Only consider parameters that pass at least one constraint valid.

=head2 subcontainer

Arguments: $tag

Return Value: $tag

Set/Get the subcontainer tag to use.
Defaults to C<fieldset>.

=head2 uploads

Arguments: \@uploads

Return Value: \@uploads

Contains an arrayref of L<Apache2::Upload> compatible objects.

=head2 xhtml_strict

Arguments: $bool

Return Value: $bool

When C<true>, it is an error to have any element at the top-level of the 
widget which is not derived from L<HTML::Widget::Element::Block>. 
Currently, the only valid element supplied is the  
L<HTML::Widget::Element::Fieldset>.

When C<true>, the top-level widget may not have a L/legend>.

=head1 Frequently Asked Questions (FAQ)

=head2 How do I add an onSubmit handler to my form?

    $widget->attributes( onsubmit => $javascript );

See L<HTML::Widget/attributes>.

=head2 How do I add an onChange handler to my form field?

    $element->attributes( onchange => $javascript );

See L<HTML::Widget::Element/attributes>.

=head2 Element X does not have an accessor for Y!

You can add any arbitrary attributes with 
L<HTML::Widget::Element/attributes>.

=head2 How can I add a tag which isn't included?

You can either create your own element module files, and use them as you 
would a standard element, or alternatively...

You can call L<type|HTML::Widget::Element::Block/type> on a 
L<HTML::Widget::Element::Block> element to change the rendered tag.

    $w->element('Block')->type('br');
    # will render as
    <br />

=head2 How can I render some elements in a HTML list?

    my $ul = $w->element('Block')->type('ul');
    $ul->element('Block')->type('li')
        ->element( Textfield => foo' );
    $ul->element('Block')->type('li')
        ->element( Textfield => 'bar' );
    
    # will render as
    <ul>
    <li>
    <input class="textfield" id="widget_foo" name="foo" type="text" />
    </li>
    <li>
    <input class="textfield" id="widget_bar" name="bar" type="text" />
    </li>
    </ul>

=head1 SUPPORT

Mailing list:

L<http://lists.rawmode.org/cgi-bin/mailman/listinfo/html-widget>

=head1 SUBVERSION REPOSITORY

The publicly viewable subversion code repository is at 
L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/HTML-Widget/>.



( run in 2.801 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )