Form-Tiny-Plugin-Diva

 view release on metacpan or  search on metacpan

lib/Form/Tiny/Plugin/Diva.pm  view on Meta::CPAN

package Form::Tiny::Plugin::Diva;
$Form::Tiny::Plugin::Diva::VERSION = '1.03';
use v5.10;
use strict;
use warnings;

use Form::Tiny::Plugin::Diva::Adapter;
use Form::Tiny::Plugin::Diva::MetaRole;

use parent 'Form::Tiny::Plugin';

sub plugin
{
	my ($self, $caller, $context) = @_;

	return {
		subs => {
			diva_config => sub {
				$$context = undef;
				$caller->form_meta->add_diva_config(@_);
			},
		},

		roles => [__PACKAGE__],
		meta_roles => ['Form::Tiny::Plugin::Diva::MetaRole'],
	};
}

use Scalar::Util qw(weaken);
use Moo::Role;

has 'diva' => (
	is => 'ro',
	builder => '_build_diva',
	lazy => 1,
	init_arg => undef,
);

sub _build_diva
{
	my ($self) = @_;
	my %config = %{$self->form_meta->diva_config};

	my @fields;
	my @hidden;

	for my $field (@{$self->field_defs}) {
		my %field_data = (
			%{$field->data // {type => 'hidden'}},
			name => $field->name,
		);

		if ($field->has_default && !exists $field_data{d} && !exists $field_data{default}) {
			$field_data{default} = $field->default->($self);
		}

		my $type = $field_data{type} // $field_data{t};
		my $push_to = lc $type eq 'hidden' ? \@hidden : \@fields;
		push @$push_to, {%field_data, comment => \%field_data};
	}

	my $obj = Form::Tiny::Plugin::Diva::Adapter->new(
		%config,
		form => \@fields,
		hidden => \@hidden,

		form_instance => $self,
	);

	weaken $obj->{form_instance};
	return $obj;
}

1;

__END__

=head1 NAME

Form::Tiny::Plugin::Diva - Form::Diva integration for Form::Tiny

=head1 SYNOPSIS

	### Form configuration

	use Form::Tiny plugins => ['Diva'];

	# Form::Diva configuration can be passed using diva_config
	diva_config label_class => 'my-label-class';

	# data of fields is used as an input to Form::Diva
	# note: name is added automatically from field name
	form_field 'normal_edit' => (
		data => {type => 'text'},
	);

	# passing type => 'hidden' will make the field hidden in diva
	form_field 'hidden' => (
		data => {type => 'hidden'},
	);

	# if there is no data section at all, the field is also treated as hidden
	# default value in form is used
	form_field 'also_hidden' => (
		default => sub { 55 },
	);


	### Using Form::Diva

	my $form = MyFormPackage->new;
	$form->set_input({normal_edit => 'edited!'});

	# Form::Diva adapter - see Form::Diva docs
	my $diva = $form->diva;

	# no need to pass the data in first argument to functions that need it
	print Dumper($form->generated);

=head1 DESCRIPTION

This plugin adds some HTML outputting capabilities to L<Form::Tiny> forms using L<Form::Diva>.

=head1 CONFIGURATION

This plugin can be added to Form::Tiny with the following line:

	use Form::Tiny plugins => ['Diva'];

=head2 Form::Diva form scope configuration



( run in 2.570 seconds using v1.01-cache-2.11-cpan-99c4e6809bf )