LiveView modal doesn't recognize field validation correctly

Hi, I’m new to Phoenix 1.7 and I’m developing a book cataloguing app that can perform CRUD operations against a database in order to teach myself. I used mix phx.gen.live after setting up a schema.

When trying to add a new Book via modal, one of the fields I wanted explicitly to not be required, the :pages field, seems to be required (“can’t be blank” when the field is empty and trying to submit).

Here’s the Book model:

defmodule Bookphx.Book do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @derive {Phoenix.Param, key: :id}
  schema "books" do
    field :title, :string
    field :author, :string
    field :pages, :integer, default: nil

    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(books, attrs) do
    books
    |> cast(attrs, [:id, :title, :author, :pages])
    |> validate_required([:id, :title, :author]) # note that :pages is absent
  end
end

I also added a required={false} attribute to the render function in BookphxWeb.BookLive.FormComponent:

@impl true
  def render(assigns) do
    ~H"""
    <div>
      <.header>
        <%= @title %>
        <:subtitle>Use this form to manage book records in your database.</:subtitle>
      </.header>

      <.simple_form
        for={@form}
        id="book-form"
        phx-target={@myself}
        phx-change="validate"
        phx-submit="save"
      >
        <.input field={@form[:title]} type="text" label="Title" />
        <.input field={@form[:author]} type="text" label="Author" />
        <.input field={@form[:pages]} type="number" label="Pages" required={false} />
        <:actions>
          <.button phx-disable-with="Saving...">Save Book</.button>
        </:actions>
      </.simple_form>
    </div>
    """
  end

Nonetheless, the modal still shows me a “can’t be blank” in red text if I leave the Pages input field blank. Any ideas?

Just updating this to say… whoops! I found the issue :sweat_smile:

Running mix phx.gen.live generated a new model altogether for me. There was a second model at lib/bookphx/books/book.ex. My original model is located at lib/bookphx/book.ex

Needless to say the changes I made within my original book.ex weren’t being reflected.

2 Likes