amirOrbe

amirOrbe

Save data from a form in a live view

Hi everybody :slight_smile:

I am creating a web application for a friend who has a beauty aesthetic, the application has a couple of sections and I am just programming the appointment creation part, I am struggling to save the form data in the database since I have a live view for the form which is the following:

this is my html form:

def render(assigns) do
    ~H"""
    <div>
      <.header>
        <%= @title %>
        <:subtitle>
          Utilice este formulario para administrar registros de citas en su base de datos.
        </:subtitle>
      </.header>

      <.simple_form
        for={@form}
        id="appointment-form"
        phx-target={@myself}
        phx-change="validate"
        phx-submit="save"
      >
        <.input
          field={@form[:date]}
          type="date"
          label="Fecha"
          class="border-red-300 rounded-md shadow-sm"
        />

        <.input field={@form[:start_time]} type="time" label="Hora de Inicio" />
        <.input field={@form[:end_time]} type="time" label="Hora de Fin" />
        <.input
          field={@form[:service_ids]}
          type="select"
          label="Servicios"
          multiple={true}
          options={list_services_with_id()}
          class="scroll-smooth md:scroll-auto"
        />
        <p class="mt-2 text-xs text-neutral-500">
          Mantenga presionada la tecla <kbd>Ctrl</kbd>
          (o <kbd>Command</kbd>
          en Mac) para seleccionar o anular varios grupos.
        </p>
        <:actions>
          <.button phx-disable-with="Guardando...">Guardar Cita</.button>
        </:actions>
      </.simple_form>
    </div>

    """
  end

this is my function for get all the services:

  defp list_services_with_id(),
    do: Enum.map(Services.list_services(), fn %{id: id, name: name} -> {name, id} end)

this is my function for save appointments:

 def handle_event("save", %{"appointment" => appointment_params}, socket) do
    save_appointment(socket, socket.assigns.action, appointment_params)
  end
  
    defp save_appointment(socket, :new, appointment_params) do
    case Appointments.create_appointment(add_user_id_to_appointment(socket, appointment_params)) do
      {:ok, appointment} ->
        updated_appointment =
          appointment
          |> Ecto.Changeset.change()
          |> Repo.update()

        case updated_appointment do
          {:ok, appointment} ->
            notify_parent({:saved, appointment})

            {:noreply,
             socket
             |> put_flash(:info, "Cita creada exitosamente")
             |> push_patch(to: socket.assigns.patch)}

          {:error, %Ecto.Changeset{} = changeset} ->
            {:noreply, assign_form(socket, changeset)}
        end

      {:error, %Ecto.Changeset{} = changeset} ->
        {:noreply, assign_form(socket, changeset)}
    end
  end
  
    def create_appointment(attrs \\ %{}) do
    %Appointment{}
    |> Appointment.changeset(attrs)
    |> Repo.insert()
  end
  
    def changeset(appointment, attrs) do
    appointment
    |> cast(attrs, [:date, :start_time, :end_time, :user_id])
    |> validate_required([:date, :start_time, :end_time])
  end

and I want the services that are selected to be saved with the many_to_many association for each appointment, since an appointment can have many services and a service can have many appointments

this is my appointment schema:

  schema "appointments" do
    field :date, :date
    field :start_time, :time
    field :end_time, :time
    belongs_to :user, Accounts.User
    has_many :appointments_services, MedussaStudio.AppointmentsServices.AppointmentService
    has_many :services, through: [:appointments_services, :service]

    timestamps(type: :utc_datetime)
  end

this is my services schema:

  schema "services" do
    field :name, :string
    field :price, :decimal

    has_many :appointments_services, MedussaStudio.AppointmentsServices.AppointmentService
    has_many :appointments, through: [:appointments_services, :appointment]
    timestamps(type: :utc_datetime)
  end

and this is my schema of the table that i created for save the association:

  schema "appointments_services" do
    belongs_to :service, MedussaStudio.Services.Service
    belongs_to :appointment, MedussaStudio.Appointments.Appointment

    timestamps()
  end

How can i save the appointment with the association of the schema ? :frowning: help me please, I even accept new ideas or comments :slight_smile:

Where Next?

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement