Update Name through Ash resources.

talha-azeem
2023-01-30

talha-azeem:

Trying to update the name through ash resources.

talha-azeem:

name_form_params = %{"name" => user.name}
user = socket.assigns.current_user
name_form =
    AshPhoenix.Form.for_update(user, :update_name,
          as: "update_name",
          api: Accounts,
          actor: user
        )
        |> AshPhoenix.Form.validate(name_form_params, errors: false)

name form that i am assigning in mount of liveview

talha-azeem:

<.header>Change Name</.header>

    <.simple_form
      :let={f}
      id="name_form"
      for={@name_form}
      method="post"
      phx-change="validate_name"
      phx-submit="save_name"
    >
      <.input
        field={{f, :name}}
        name="name"
        type="text"
        label="Name"
        id="name_for_user"
        required
      />
      <:actions>
        <.button phx-disable-with="Changing...">Change Name</.button>
      </:actions>
    </.simple_form>

form on the frontend

talha-azeem:

@impl true
  def handle_event("save_name", params, socket) do
    case AshPhoenix.Form.submit(socket.assigns.name_form, params: params) do
      {:ok, _result} ->
        {:noreply,
         socket
         |> put_flash(:info, "Name updated")
         |> push_redirect(to: "/users/settings")}

      {:error, name_form} ->
        {:noreply, assign(socket, name_form: name_form)}
    end
  end

  def handle_event("validate_name", params, socket) do
    {:noreply,
     assign(socket,
       name_form:
         AshPhoenix.Form.validate(socket.assigns.name_form, params,
           errors: socket.assigns.name_form.submitted_once?
         )
     )}
  end

validate and save name handle events.

talha-azeem:

In my user.ex:

policies do
   policy action(:update_name) do
      description "A logged in user can update their name"
      authorize_if expr(id == ^actor(:id))
    end
end

update :update_name do
      argument :name, :ci_string, allow_nil?: false
    end

these are defined

ZachDaniel:

update :update_name do
  argument :name, :ci_string, allow_nil?: false
end

ZachDaniel:

That isn’t enough to do it

ZachDaniel:

That just adds an argument

ZachDaniel:

But it doesn’t actually do anything with the argument

ZachDaniel:

update :update_name do
  accept [:name]
end

ZachDaniel:

By default, an action will accept all public attributes to be changed

ZachDaniel:

You don’t need to add arguments for them unless they are private? true or writable? false

talha-azeem:

I was about to try this 😅 just saw this in docs 😅

ZachDaniel:

👍

talha-azeem:

update :update_name do
      accept [:name]
    end

worked after updating it like this, Thank you 🙌🏻