Home > Net >  How to use variable in phoenix framework in a handle_event function?
How to use variable in phoenix framework in a handle_event function?

Time:12-22

I would like to have two input fields in two different forms (see below). The first one submits the user's name and saves it in variable client_name. This seems to work fine.

When the second one is submitted, I would like to grab hold of the client_name variable and use it in the string I create. But I don't know how.

defmodule ChatWeb.ChatLive do 
use ChatWeb, :live_view

@topic "message_received"

    def mount(params, session, socket) do
        ChatWeb.Endpoint.subscribe(@topic)
        {:ok, assign(socket, :text_value, "") |>assign(:client_name, "")}
    end
    
    def render(assigns) do
    ~H"""
        <h1>Chat</h1>
        <form phx-submit="submit_name">
            <label>Your name: <%= @client_name %><input id="client" type="text" name="client" /></label>
            <input type="submit" />
        </form>
        <form phx-submit="submit">
            <label>Your Text:<input id="msg" type="text" name="input_value" /></label>
            <input type="submit" />
        </form>
        <div id="chat">
            Chat history: <%= @text_value %>
        </div>
        
    """
    end
    
    def handle_event("submit_name", %{"client" => client}, socket) do
        {:noreply, assign(socket, :client_name, client)}
    end
    
    def handle_event("submit", %{"input_value" => msg}, socket) do
        ChatWeb.Endpoint.broadcast_from(self(), @topic, "message_received_received", "| Message by #{client_name}: '" <> msg <> "' ")
        {:noreply, assign(socket, :text_value, "| Message by #{client_name}: '" <> msg <> "' " <> socket.assigns.text_value)}
    end
    
    def handle_info(%{topic: @topic, payload: new_message}, socket ) do
        {:noreply, assign(socket, :text_value, new_message <> socket.assigns.text_value)}
    end
    

end

The Problem is with the #{client_name} What would be the correct notation?

My error says: undefined function client_name/0

CodePudding user response:

Your call to client_name should be changed to socket.assigns.client_name as this is where you put the value in the handle_event("submit_name", ...).

Alternatively you can bind the client_name assign in the function clause:

def handle_event("submit", %{"input_value" => msg}, %{assigns: %{client_name: client_name}} = socket) do

In this case you don't need to fix client_name in the function body.

  • Related