Form-Processor-Model-CDBI

 view release on metacpan or  search on metacpan

lib/Form/Processor/Model/CDBI.pm  view on Meta::CPAN


=item model_validate

Validates profile items that are dependent on the model.
Currently, "unique" fields are checked  to make sure they are unique.

This validation happens after other form validation.  The form already has any
field values entered in $field->value at this point.

=cut

sub model_validate {
    my ( $self ) = @_;

    return unless $self->validate_unique;

    return 1;
}

=item validate_unique

Checks that the value for the field is not currently in the database.

=cut

sub validate_unique {
    my ( $self ) = @_;

    my $unique = $self->profile->{unique} || return 1;

    my $item = $self->item;

    my $class = ref( $item ) || $self->object_class;

    my $found_error = 0;

    for my $field ( map { $self->field( $_ ) } @$unique ) {

        next if $field->errors;

        my $value = $field->value;
        next unless defined $value;

        my $name = $field->name;

        # unique means there can only be on in the database like it.
        my $match = $class->search( { $name => $value } )->first || next;

        next if $self->items_same( $item, $match );

        $field->add_error( 'Value must be unique in the database' );
        $found_error++;
    }

    return $found_error;
}




sub update_model {
    my ( $self ) = @_;


    # Grab either the item or the object class.
    my $item = $self->item;
    my $class = ref( $item ) || $self->object_class;



    # get a hash of all fields
    my %fields = map { $_->name, $_ } grep { !$_->noupdate } $self->fields;


    # First process the normal and has_a columns
    # as that data is directly stored in the object

    my %data;


    # Loads columns (including has_a)
    foreach my $col ( $class->columns('All') ) {
        next unless exists $fields{ $col };

        my $field = delete $fields{$col};

        # If the field is flagged "clear" then set to NULL.
        my $value = $field->clear ? undef : $field->value;


        if ( $item ) {
            my $cur = $item->$col;
            next unless $value || $cur;
            next if $value && $cur && $value eq $cur;
            $item->$col( $value )
        } else {
            $data{$col} = $value;
        }
    }


    if ( $item ) {
        $item->update;
        $self->updated_or_created( 'updated' );
    } else {
        $item = $class->create( \%data );
        $self->item( $item );
        $self->updated_or_created( 'created' );
    }



    # Now check for mapping/has_many in any left over fields


    for my $field_name ( keys %fields ) {
        next unless $class->meta_info('has_many');
        next unless my $meta = $class->meta_info('has_many')->{$field_name};

        my $field = delete $fields{$field_name};
        my $value = $field->value;



( run in 0.533 second using v1.01-cache-2.11-cpan-e93a5daba3e )