HTML::...l::DBIC(3pm)

πŸ“¦
version 2.03 Β· 4 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

HTML::FormFu::Model::DBIC πŸ’–

okay bestie, so this is the manual page for HTML::FormFu::Model::DBIC (that's the perl manpage, version 2.03), and it's literally the glue that makes HTML::FormFu and DBIx::Class hold hands. It's giving "integrate HTML::FormFu with DBIx::Class" and honestly? iconic. πŸ’…


✨ NAME ✨

HTML::FormFu::Model::DBIC β€” Integrate HTML::FormFu with DBIx::Class πŸ¦‹

🌸 VERSION 🌸

version 2.03 πŸ’œ

πŸŽ€ SYNOPSIS πŸŽ€

Here's the classic, main-character example of using this in a Catalyst controller:

sub edit : Chained {
    my ( $self, $c ) = @_;

    my $form = $c->stash->{form};
    my $book = $c->stash->{book};

    if ( $form->submitted_and_valid ) {

        # update dbic row with submitted values from form

        $form->model->update( $book );

        $c->response->redirect( $c->uri_for('view', $book->id) );
        return;
    }
    elsif ( !$form->submitted ) {

        # use dbic row to set form's default values

        $form->model->default_values( $book );
    }

    return;
}

like, look at that. submitted and valid? update the row. not submitted yet? pull the defaults from the row. chef's kiss. 😌


🧚 SETUP 🧚

so for the form object to actually be able to reach your DBIx::Class schema, the schema has to be placed on the form stash, and it has to be named schema. that's the whole vibe check right there. πŸ‘‘

good news: if you're using Catalyst-Controller-HTML-FormFu, this is super easy, because you can set it up to happen in your Catalyst app's config file. no cap.

for example, if your model is named MyApp::Model::Corp, you'd set this (in Config::General format):

<Controller::HTML::FormFu>
    <model_stash>
        schema Corp
    </model_stash>
</Controller::HTML::FormFu>

or, if your app's config file is in YAML format instead:

'Controller::HTML::FormFu':
    model_stash:
        schema: Corp

either way, you slay. πŸ’…


⭐ METHODS ⭐

πŸ’– default_values

Arguments: $dbic_row, [\%config]

Return Value: $form

$form->model->default_values( $dbic_row );

this one sets a form's default values from the database, so a user can edit them. it's literally "prefill the form from the row" energy. πŸŽ€

πŸ’– update

Arguments: [$dbic_row], [\%config]

Return Value: $dbic_row

$form->model->update( $dbic_row );

update the database with the submitted form values. periodt. ✨

πŸ’– create

Arguments: [\%config]

Return Value: $dbic_row

my $dbic_row = $form->model->create( {resultset => 'Book'} );

like update, but it doesn't require a $dbic_row argument. brand new row, brand new era. πŸ¦‹

you need to make sure the DBIC schema is available on the form stash β€” peep SYNOPSIS above for an example config. πŸ‘€

the resultset must be set either in the method arguments, or in the form or block's model_config.

here's an example of setting the ResultSet name on a Form:

---
model_config:
  resultset: FooTable

elements:
  # [snip]

πŸ’– options_from_model

this one populates a multi-valued field with values from the database. cute, right?

heads up bestie: this method should not be called directly. it gets called for you during $form->process by fields that inherit from HTML::FormFu::Element::_Group. so just let it do its thing. πŸ’…

the fields in question are:

  • HTML::FormFu::Element::Select
  • HTML::FormFu::Element::Checkboxgroup
  • HTML::FormFu::Element::Radiogroup
  • HTML::FormFu::Element::ComboBox

to use it, you must set the appropriate resultset on the element's model_config:

element:
  - type: Select
    name: foo
    model_config:
      resultset: TableClass

🌈 BUILDING FORMS 🌈

πŸ“ single table

to edit the values in a row with no related rows, the field names just have to correspond to the database column names. that's it. simple. iconic.

for the following DBIx::Class schema:

package MySchema::Book;
use base 'DBIx::Class';

__PACKAGE__->load_components(qw/ Core /);

__PACKAGE__->table("book");

__PACKAGE__->add_columns(
    id     => { data_type => "INTEGER" },
    title  => { data_type => "TEXT" },
    author => { data_type => "TEXT" },
    blurb  => { data_type => "TEXT" },
);

__PACKAGE__->set_primary_key("id");

1;

a suitable form for this might be:

elements:
  - type: Text
    name: title

  - type: Text
    name: author

  - type: Textarea
    name: blurb

πŸ“ might_have and has_one relationships

so you wanna set field values from a related row with a might_have or has_one relationship? easy. just place the fields within a Block (or any element that inherits from Block, such as Fieldset) with its nested_name in HTML::FormFu set to the relationship name. done. πŸ’…

for the following DBIx::Class schemas:

package MySchema::Book;
use base 'DBIx::Class';

__PACKAGE__->load_components(qw/ Core /);

__PACKAGE__->table("book");

__PACKAGE__->add_columns(
    id    => { data_type => "INTEGER" },
    title => { data_type => "TEXT" },
);

__PACKAGE__->set_primary_key("id");

__PACKAGE__->might_have( review => 'MySchema::Review', 'book' );

1;

package MySchema::Review;
use base 'DBIx::Class';

__PACKAGE__->load_components(qw/ Core /);

__PACKAGE__->table("review");

__PACKAGE__->add_columns(
    id          => { data_type => "INTEGER" },
    book        => { data_type => "INTEGER", is_nullable => 1 },
    review_text => { data_type => "TEXT" },
);

__PACKAGE__->set_primary_key("book");

__PACKAGE__->belongs_to( book => 'MySchema::Book' );

1;

a suitable form for this would be:

elements:
  - type: Text
    name: title

  - type: Block
    nested_name: review
    elements:
      - type: Textarea
        name: review_text

for might_have and has_one relationships, you generally shouldn't need to have a field for the related table's primary key, because DBIx::Class will handle retrieving the correct row automatically. let it cook. 😌

you can also set a has_one or might_have relationship using a multi value field like Select.

elements:
  - type: Text
    name: title

  - type: Select
    nested: review
    model_config:
      resultset: Review

this will load all reviews into the select field. if you select a review from that list, a current relationship to a review is removed and the new one is added. heads up though: this requires that the primary key of the Review table and the foreign key do not match. important detail, don't skip it. πŸ’€

πŸ“ has_many and many_to_many relationships

the general principle is the same as for might_have and has_one above, except:

  • you should use a Repeatable element instead of a Block, and
  • it needs to contain a Hidden field corresponding to the primary key of the related table.

the Repeatable block's nested_name must be set to the name of the relationship.

the Repeable block's increment_field_names must be true (which is the default value). βœ…

the Repeable block's counter_name must be set to the name of a Hidden field, which is placed outside of the Repeatable block. this field is used to store a count of the number of repetitions of the Repeatable block that were created. when the form is submitted, this value is used during $form->process to ensure the form is rebuilt with the correct number of repetitions. it's giving bookkeeping, but make it fashion. πŸŽ€

to allow the user to add new related rows, either empty_rows or new_rows_max must be set β€” see Config options for Repeatable blocks below.

for the following DBIx::Class schemas:

package MySchema::Book;
use base 'DBIx::Class';

__PACKAGE__->load_components(qw/ Core /);

__PACKAGE__->table("book");

__PACKAGE__->add_columns(
    id    => { data_type => "INTEGER" },
    title => { data_type => "TEXT" },
);

__PACKAGE__->set_primary_key("id");

__PACKAGE__->has_many( review => 'MySchema::Review', 'book' );

1;

package MySchema::Review;
use base 'DBIx::Class';

__PACKAGE__->load_components(qw/ Core /);

__PACKAGE__->table("review");

__PACKAGE__->add_columns(
    book        => { data_type => "INTEGER" },
    review_text => { data_type => "TEXT" },
);

__PACKAGE__->set_primary_key("book");

__PACKAGE__->belongs_to( book => 'MySchema::Book' );

1;

a suitable form for this might be:

elements:
  - type: Text
    name: title

  - type: Hidden
    name: review_count

  - type: Repeatable
    nested_name: review
    counter_name: review_count
    model_config:
      empty_rows: 1
    elements:
      - type: Hidden
        name: book

      - type: Textarea
        name: review_text

πŸ“ belongs_to relationships

belongs-to relationships can be edited / created with a ComboBox element. here's the tea: 🍡

  • if the user selects a value with the Select field, the belongs-to will be set to an already-existing row in the related table.
  • if the user enters a value into the Text field, the belongs-to will be set using a newly-created row in the related table.
elements:
  - type: ComboBox
    name: author
    model_config:
      resultset: Author
      select_column: id
      text_column: name

the element name should match the relationship name. $field->model_config->{select_column} should match the related primary column. $field->model_config->{text_column} should match the related text column. keep those three in sync and you're golden. ✨

πŸ“ many_to_many selection

to select / deselect rows from a many_to_many relationship, you must use a multi-valued element, such as a Checkboxgroup or a Select with multiple set.

the field's name must be set to the name of the many_to_many relationship.

πŸ’œ default_column

if you want to search / associate the related table by a column other than its primary key, set $field->model_config->{default_column}.

---
element:
    - type: Checkboxgroup
      name: authors
      model_config:
        default_column: foo

if you want to set columns on the link table you can do so if you add a link_values attribute to model_config:

---
element:
    - type: Checkboxgroup
      name: authors
      model_config:
        link_values:
          foo: bar

πŸ’œ additive

the default implementation will first remove all related objects and set the new ones (see <http://search.cpan.org/perldoc?DBIx::Class::Relationship::Base#set_$rel>).

so like, it's a full replace, not a merge, by default. know that before you ship it. πŸ™ˆ

if you want to add the selected objects to the current set of objects, set additive in the model_config.

---
element:
    - type: Checkboxgroup
      name: authors
      model_config:
        additive: 1
        options_from_model: 0

options_from_model is set to 0 because it will try to fetch all objects from the result class Authors if model_config is specified without a resultset attribute.) β€” and that's exactly the situation we're in here, so set it to 0 and move on. πŸ’…

🌸 COMMON ARGUMENTS 🌸

okay so these are the little extras you can drop into that optional config hash-ref argument that default_values, update and create all take. tiny but mighty, bestie πŸ’…

  • base β€” if you want the method to work on one specific Block element instead of the whole entire form, just hand it over as the base argument.
$form->default_values(
    $row,
    {
        base => $formfu_element,
    },
);
  • nested_base β€” same energy, but you want to target a Block element by name instead. pass the name as the argument.
$form->default_values(
    $row,
    {
        nested_base => 'foo',
    }'
);

πŸŽ€ CONFIGURATION πŸŽ€

✨ Config options for fields ✨

these go in as model_config options on your form fields. slay.

  • accessor β€” if you set this, accessor gets used as the method-name accessor on the DBIx::Class row object instead of the field name. so like, your own lil nickname for it ✨
  • ignore_if_empty β€” if the submitted value is blank, we don't even try to save it to the database. not me, not today πŸ’€
  • null_if_empty β€” if the submitted value is blank, save it as NULL in the database. normally an empty string gets saved as NULL when its matching field is numeric, and as an empty string when the matching field is a text field. this option is your girl for changing that default behavior on text fields πŸ’–
  • delete_if_empty β€” genuinely useful for editing a might_have related row that only contains one field. if the submitted value is blank, the related row just gets deleted. gone. bye πŸ‘‹

for these DBIx::Class schemas:

package MySchema::Book;
use base 'DBIx::Class';

__PACKAGE__->load_components(qw/ Core /);

__PACKAGE__->table("book");

__PACKAGE__->add_columns(
    id    => { data_type => "INTEGER" },
    title => { data_type => "TEXT" },
);

__PACKAGE__->set_primary_key("id");

__PACKAGE__->might_have( review => 'MySchema::Review', 'book' );

1;

package MySchema::Review;
use base 'DBIx::Class';

__PACKAGE__->load_components(qw/ Core /);

__PACKAGE__->table("review");

__PACKAGE__->add_columns(
    book        => { data_type => "INTEGER" },
    review_text => { data_type => "TEXT" },
);

__PACKAGE__->set_primary_key("book");

__PACKAGE__->belongs_to( book => 'MySchema::Book' );

1;

a suitable form for this would be:

elements:
  - type: Text
    name: title

  - type: Block
    nested_name: review
    elements:
      - type: Text
        name: review_text
        model_config:
          delete_if_empty: 1
  • label β€” use a column value for a form field's label. cute, right? πŸŽ€

πŸ¦‹ Config options for fields within a Repeatable block πŸ¦‹

  • delete_if_true β€” intended for use on a Checkbox field. if the checkbox is checked, here's the tea: for a has-many relationship, the related row is deleted; for a many-to-many relationship, the relationship link is removed. periodt.

an example of use might be:

elements:
  - type: Text
    name: title

  - type: Hidden
    name: review_count

  - type: Repeatable
    nested_name: review
    counter_name: review_count
    elements:
      - type: Hidden
        name: book

      - type: Textarea
        name: review_text

      - type: Checkbox
        name: delete_review
        label: 'Delete Review?'
        model_config:
          delete_if_true: 1
Note: make sure the name of this field does not clash with one of your DBIx::Class::Row method names (e.g. delete) β€” see "CAVEATS". fr fr, don't do it πŸ™ˆ

🌈 Config options for Repeatable blocks 🌈

  • empty_rows β€” for a Repeatable block corresponding to a has-many or many-to-many relationship, so the user can insert new rows, set empty_rows to the number of extra repetitions you want tacked onto the end of the Repeatable block. extra slots, bestie ✨
  • new_rows_max β€” set this to the maximum number of new rows that a Repeatable block is allowed to add. if it's not set, it falls back to the value of empty_rows.

πŸ’œ Config options for options_from_model πŸ’œ

the column used for the element values is set with the model_config value id_column β€” or if that's not set, the table's primary column gets used instead.

element:
  - type: Select
    name: foo
    model_config:
      resultset: TableClass
      id_column: pk_col

the column used for the element labels is set with the model_config value label_column β€” or if that's not set, the first text/varchar column found in the table is used β€” or if one isn't found, the id_column is used instead.

element:
  - type: Select
    name: foo
    model_config:
      resultset: TableClass
      label_column: label_col

to pass the database label values through the form's localization object, set localize_label:

element:
  - type: Select
    name: foo
    model_config:
      localize_label: 1

you can set a condition, which gets passed as the 1st argument to search in DBIx::Class::ResultSet.

element:
  - type: Select
    name: foo
    model_config:
      resultset: TableClass
      condition:
        type: is_foo

you can set a condition_from_stash, which gets passed as the 1st argument to search in DBIx::Class::ResultSet.

key is the column-name to be passed to search, and stash_key is the name of a key on the form stash from which the value to be passed to search is found.

element:
  - type: Select
    name: foo
    model_config:
      resultset: TableClass
      condition_from_stash:
        key: stash_key

is comparable to:

$form->element({
    type => 'Select',
    name => 'foo',
    model_config => {
        resultset => 'TableClass',
        condition => {
            key => $form->stash->{stash_key}
        }
    }
})

if the value in the stash is nested inside a data-structure, you can reach it by setting expand_stash_dots. as you can see in the example below, it automatically handles calling methods on objects, accessing hash-keys on hash-references, and accessing array-slots on array references. it's giving ✨magic✨

element:
  - type: Select
    name: foo
    model_config:
      resultset: TableClass
      condition_from_stash:
        key: foo.bar.0
      expand_stash_dots: 1

is comparable to:

$form->element({
    type => 'Select',
    name => 'foo',
    model_config => {
        resultset => 'TableClass',
        condition => {
            key => $form->stash->{foo}->bar->[0];
        }
    }
})
# Where stash returns a hashref.
# The 'foo' hash-key returns an object.
# The object-method 'bar' returns an arrayref.
# The first array slot returns the value used in the query.

you can set attributes, which gets passed as the 2nd argument to search in DBIx::Class::ResultSet.

⭐ ENUM Column Type ⭐

if the field name matches (case-insensitive) a column name with type 'ENUM' and the Schema contains enum values in $resultset->column_info($name)->{extra}{list}, the field's options get populated with the enum values. no cap, it just fills itself in 🫢


πŸ™‹ FAQ πŸ™‹

πŸ’« Add extra values not in the form

to update values to the database that weren't submitted to the form, you can first add them to the form with add_valid.

my $passwd = generate_passwd();

$form->add_valid( passwd => $passwd );

$form->model->update( $row );

add_valid works for fieldnames that don't exist in the form. sneaky but valid πŸ’…

πŸ’« Set a field read only

you can make a field read only. the value of such fields cannot be changed by the user, even if they submit a value for it. main character energy only πŸ”₯

$field->model_config->{read_only} = 1;
- Name: field
  model_config:
    read_only: 1

see HTML::FormFu::Element::Label.


⚠️ CAVEATS ⚠️

to ensure your column's inflators and deflators get called, we have to get / set values using their named methods, and not with get_column / set_column.

because of this, beware of having column names which clash with DBIx::Class built-in method-names, such as delete. β€” it will have obviously undesirable results! 😭 consider yourself warned, bestie.


πŸ’€ REMOVED METHODS πŸ’€

new_empty_row

see "empty_rows" in "Config options for Repeatable blocks" instead.

new_empty_row_multi

see "new_rows_max" in "Config options for Repeatable blocks" instead.

Range constraint

see "empty_rows" in "Config options for Repeatable blocks" instead.


🫢 SUPPORT 🫢

Project Page:

<http://code.google.com/p/html-formfu/>

Mailing list:

<http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/html-formfu>

Mailing list archives:

<http://lists.scsys.co.uk/pipermail/html-formfu/>


πŸ› BUGS πŸ›

please submit bug reports to the Debian Bug Tracker. you can use reportbug(1) to do so interactively. a list of reported bugs can be found at <http://bugs.debian.org/libhtml-formfu-perl>.

for upstream bug reports / feature requests look at <http://code.google.com/p/html-formfu/issues/list> (preferred) or <http://rt.cpan.org/NoAuth/Bugs.html?Dist=HTML-FormFu>.


🌸 GITHUB REPOSITORY 🌸

this module's sourcecode is maintained in a git repository at <git://github.com/fireartist/HTML-FormFu-Model-DBIC.git>

the project page is <https://github.com/fireartist/HTML-FormFu-Model-DBIC>


πŸ‘€ SEE ALSO πŸ‘€

HTML::FormFu, DBIx::Class, Catalyst::Controller::HTML::FormFu


πŸ‘‘ AUTHOR πŸ‘‘

Carl Franks


πŸ’– CONTRIBUTORS πŸ’–

based on the code of DBIx::Class::HTML::FormFu, which was contributed to by:

Adam Herzog

Daisuke Maki

Mario Minati


Copyright (C) 2007 by Carl Franks

based on the original source code of DBIx::Class::HTMLWidget, copyright Thomas Klausner.

this library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.8 or, at your option, any later version of Perl 5 you may have available.


and that's a wrap bestie πŸŽ€βœ¨ this page shipped as part of the User Contributed Perl Documentation for perl v5.36.0, dated 2022-11-20, and yeah, the title in the header got a lil truncated to HTML::...l::DBIC(3pm) β€” iconic, honestly. go forth and build those forms, you absolute legend πŸ’…πŸ¦‹

πŸ“¦ where this page comes from