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?

Popular in Questions Top

qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29703 241
New
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement