[html-formfu] Validating unique names
Ton Voon
ton.voon at altinity.com
Wed May 14 17:45:34 BST 2008
On 14 May 2008, at 15:46, Andreas Marienborg wrote:
> On May 14, 2008, at 4:39 PM, Ton Voon wrote:
>
>> We've just starting playing with FormFu with new Catalyst
>> application and am impressed with how it works. However, one thing
>> which I find hard is how to define a field as unique across all the
>> existing rows.
>>
>> For instance, we have a list of hosts and we need to ensure that
>> the host name given in the form is unique. Obviously if the host is
>> being edited and the name is the same, then the validator should
>> pass.
>>
>> It looks like a validator callback is the best way to do that, but
>> I can't see how to integrate this with DBIx::Class. How do others
>> do this?
>
> We do this by setting something in the form stash before processing,
> then the validator can reach this trough the $form->stash method (I
> think). This might only work if you implement it as a constraint or
> validator class, not as a validator or constraint callback (too long
> since I worked with formfu :/)
>
> Anyway, once you have the object beeing worked on, you can check
> that the ID or whatever is the same, and return "AOK" then
>
> hope that made some sense
Andreas,
Thanks. I was thinking that the stash maybe one option. However, after
a bit of playing, I think I might have hit on something where it might
integrate better with DBIx::Class using object methods instead.
I've got a new class called HTML::FormFu::Validator::Object, which is
this:
----
package HTML::FormFu::Validator::Object;
use strict;
use base 'HTML::FormFu::Validator';
__PACKAGE__->mk_accessors(qw/ object /);
sub validate_value {
my ( $self, $value ) = @_;
$self->$object->validate_value( $self, $value );
}
1;
----
then I've added this method to DBIx::Class::HTML::FormFu:
----
sub validate_value {
my ($self, $field, $new_value) = @_;
if ($self->name ne $new_value) {
return $self->result_source->resultset-
>count( { $field->name => $new_value } ) == 0;
}
return 1;
}
----
which is a component of my DBIx::Class objects:
----
__PACKAGE__->load_components( qw/HTML::FormFu Core/ );
----
so you can now define $field with:
----
$field->validator('Object')->object( $object );
----
When validation occurs, it will call validate_value in
H::F::V::Object.pm, which in turn calls $object-
>validate_value( $field, $new_value) which now has all the
information it needs to do the validation (new value, the object and
the field information).
Is this a suitable, general solution? I can provide patches if this is
desired.
Ton
http://www.altinity.com
UK: +44 (0)870 787 9243
US: +1 866 879 9184
Fax: +44 (0)845 280 1725
Skype: tonvoon
More information about the HTML-FormFu
mailing list