How to access other tables with nil value

Hey
I create a liveview with the generator. But from the index.html.heex file I want to connect other tables. Because of that I create the function “list_owner_1”

<.input field={@form[:owner_id]} type="select" label="Owner" options={Persons.list_owner_1() |> Enum.map(&{&1.owner_d, &1.id})} />

def list_owner_1 do
(from s in Owner, select: %Owner{id: s.id, owner_d: fragment(“concat( ?, ’ ', ?)”, s.firstname, s.surname)})
|> Repo.all
end

That is working. But it fails if there is no value. In this case I get a error because nil is not allowed. Are there other possibilitys?

Hello and welcome,

I fixed the post format. Please use ``` to wrap your code…

You should add this to your view, in order to clean up the template.

defp list_options
  Persons.list_owner_1() |> Enum.map(&{&1.owner_d, &1.id})
end

# and use it like this

<.input field={@form[:owner_id]} type="select" label="Owner" options={list_options()} />

Enum.map expect a list, but You have nil | list

=> Transform nil to an empty list

defp list_options
  Persons.list_owner_1() 
  |> Kernel.||([])
  |> Enum.map(&{&1.owner_d, &1.id})
end

It is not the only way… You could also use an assign and use new Liveview syntax

# somewhere in the view
socket
|> assign(:options, list_options())

defp list_options
  Persons.list_owner_1() 
  |> Enum.map(&{&1.owner_d, &1.id})
end

# in the template
<.input :if={@options} field={@form[:owner_id]} type="select" label="Owner" options={@options} />

Not tested

1 Like