amirOrbe

amirOrbe

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? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
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
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
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
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews