Skip to content

How to use the sortable_table_for feature

Steve Pallen edited this page May 11, 2016 · 1 revision

Create a sorted sorted table allowing drag and drop for the rows, with ajax updates.

With a many-to-many join table:

defmodule MyApp.ExAdmin.Category do
  use ExAdmin.Register
  alias MyApp.{Category,CategoryProperty}

  @position_column "priority" # "position" by default

  register_resource Category do
    show category do
      attributes_table

      panel "Properties" do
        sortable_table_for(category, :category_properties) do
          # call of `sort_handle_column` could be omitted
          sort_handle_column "arrows" # "bars" by default
          column :property
          column :required, toggle: ~w(Yes No) # ~w(YES NO) in case `toggle: true`
          column :displayable, toggle: true
        end
      end
    end

    query do
      %{
        show: [preload: [
          # :any,
          # :other,
          # :associations,
          category_properties: from(CategoryProperty, order_by: [:priority], preload: [:property]) 
            # nested preload in from clause could be omitted if you don't use nested associations inside sortable tables
        ]],
        # all: [preload: [:all, :associations, :used, :in_views, :and, :in_forms]]
      }
    end
  end
end

With a has_many relationship:

defmodule Survey.ExAdmin.Question do
  use ExAdmin.Register
  @position_column "key"

  register_resource Survey.Question do
    menu priority: 3

    show question do
      attributes_table
      panel "Choices" do
        sortable_table_for(question, :choices) do
          #sort_handle_column
          column :name
        end
      end
    end

    query do
      %{
        show: [preload: [
          :survey,
          choices: from(Survey.Choice, order_by: [:key])
        ]],
        all: [preload: [:survey]]
      }
    end
  end
end