Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get query string value on html.exx file?

I am new on phoenix, elixir. I am trying to get params[:task_id] on text_field on new.html.exx , something like below rails code.

<%= f.text_field :task_id, value: params[:task_id] %>

I found below info on iex shell

[info] GET /tasks/1/comments/new
[debug] Processing by HelloWorld.CommentController.new/2
Parameters: %{"task_id" => "1"}

I tried with IEX.pry and got following result, but i am not able to apply it on text_input value.

pry(3)> conn.params["task_id"]
"1" 

Also tried below code but no luck.

<%= text_input f, :task_id, value: @conn.params["task_id"] %>
Got Error: assign @conn not available in eex template.

Any help would be appreciated. Thanks.

like image 573
siv rj Avatar asked Dec 01 '25 09:12

siv rj


2 Answers

You can use the copy of params available in @conn (which is available in all templates rendered directly using Phoenix.Controller.render).

# new.html.eex
<%= @conn.params["task_id"] %>

If you want to use @conn in a template rendered using Phoenix.View.render inside the main template, you need to explicitly pass it to the new template:

# new.html.eex
<%= render "form.html", ..., conn: @conn %>

You can also just pass in params:

# new.html.eex
<%= render "form.html", ..., params: @conn.params %>

and use @params:

# form.html.eex
<%= @params["task_id"] %>
like image 106
Dogbert Avatar answered Dec 04 '25 13:12

Dogbert


Based on comments, you appear to be using Ecto and Changesets.

Given some schema

schema "foo" do
  field :name, :string
  field :age, :integer
end

You can have something like this in your controller

def new(conn, _params) do
  changeset = Foo.changeset(%Foo{})
  render conn, "new.html", changeset: changeset
end

Which will allow you to have something like this in your html view file.

= form_for @changeset, foo_path(@conn, :create), [as: :foo], fn f ->
  = text_input f, :name
  = number_input f, :age
  = submit "Submit"
- end

Then back to your controller for the create method

def create(conn, %{"foo" => foo_params}) do
  foo = Foo.changeset(%Foo{}, foo_params)

  case Repo.insert(foo) do
    {:ok, foo} -> redirect conn, to: foo_path(:show, foo)
    {:error, changeset} -> render conn, "new.html", changeset: changeset
  end
end

Depending on your needs, the logic may be different, but you can take advantage of the changeset to fill the form in for you.

like image 28
Justin Wood Avatar answered Dec 04 '25 12:12

Justin Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!