wlminimal
Drab: how to get a conn value?
Is there anyway to get conn value inside defhandler in drab?
I want to get a user from conn.assigns like this
defhandler shorten_url(socket, sender) do
long_url = sender.params["long_url_textarea"]
user = conn.assigns.current_user
case Analytics.create_short_link(long_url) do
{:ok, results} ->
# Create bitly struct
%{id: bitlink_id, link: bitlink_url, long_url: long_url} = results
Bitly.create_bitly(%{bitlink_id: bitlink_id, bitlink_url: bitlink_url, long_url: long_url, total_clicks: 0, user_id: user.id})
poke socket, long_url: bitlink_url
{:error, errors} ->
set_prop socket, "#long-url-error", innerHTML: "Something wrong found in your url. Make sure including http://, for example http://www.example.com"
end
end
Most Liked
grych
You can’t. Conn does not exists anymore - it is available only when rendering page with controller. While the page is already rendered and connected, the similar role for conn plays socket
To get the userid, you may use:
- session: there is a Drab.Core.get_session/2 for this
-
socket.assigns- you may add the assign to thesocketstruct when rendering Drab JS inapp.html.eex, eg:
# app.html.eex:
<%= Drab.Client.run(@conn, current_user: @conn.assigns.current_user) %>
# your_commander.ex
defhandler shorten_url(socket, sender) do
user = socket.assigns.current_user
end
grych
Actually, I can’t reproduce this issue. In my environment all works as expected: the other form values (name, description) are kept.
The only reason why this value may be cleared, is when Drab decides to refresh them. This may be because the form may be under some other expression. Imagine something like:
<%= if @short_url do %>
<input id=other>
<input value=<%= @long_url%> id=long_url>
<input value=<%= @short_url%> id=short_url>
<% end %>
Now, when you poke socket, long_url: ..., everything will work as expected: the only <input id=long_url> is going to be updated. So the other input value will be untouched.
But what when you poke socket, short_url: ...? Drab will update everything under if, so all three inputs will be refreshed! This will re-set their values.







