Skip to content

Commit

Permalink
Merge pull request #702 from naymspace/feature/improve-custom-fields-…
Browse files Browse the repository at this point in the history
…docs

Improve custom fields docs
  • Loading branch information
Flo0807 authored Dec 14, 2024
2 parents 7553cef + 3580a58 commit 2df6653
Showing 1 changed file with 37 additions and 2 deletions.
39 changes: 37 additions & 2 deletions guides/fields/custom-fields.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ Backpex ships with a set of default fields that can be used to create content ty

When creating your own custom field, you can use the `field` macro from the `BackpexWeb` module. It automatically implements the `Backpex.Field` behavior and defines some aliases and imports.

> #### Information {: .info}
Note that a field has to be a [LiveComponent](https://hexdocs.pm/phoenix_live_view/Phoenix.LiveComponent.html).

> #### Warning {: .warning}
>
> A field has to be a [LiveComponent](https://hexdocs.pm/phoenix_live_view/Phoenix.LiveComponent.html).
> As Backpex is still under active development in a 0.X version, it can be assumed that there will be breaking changes to the
> fields API in future releases, which will require you to update your custom fields.
## Creating a Custom Field

Expand Down Expand Up @@ -49,3 +52,35 @@ The `render_value/1` function returns markup that is used to display a value on
The `render_form/1` function returns markup that is used to render a form on `edit` and `new` views.

See `Backpex.Field` for more information on the available callback functions. For example, you can implement `render_index_form/1` to make the field editable in the index view.

## Add field option validation

With Backpex v0.9 we are validating field options. This ensures that only field options that are actually used by the field can be defined in the field options map. So if your custom field requires certain field options, make sure you define them.

Note that we use [NimbleOptions](https://hexdocs.pm/nimble_options) to validate field options.

To add field option validation pass a config schema to `use Backpex.Field`.

```elixir
@config_schema [
custom_option: [
doc: "A custom field option.",
type: :string
],
# see https://hexdocs.pm/nimble_options/NimbleOptions.html
# or any other core backpex field for examples...
]

use Backpex.Field, config_schema: @config_schema
```

You can then access your custom option safely in your field.

```elixir
@impl Backpex.Field
def render_value(assigns) do
custom_option = assigns.field_options[:custom_option]

# ...
end
```

0 comments on commit 2df6653

Please sign in to comment.