繁体   English   中英

活动管理员:如何自定义选择过滤器的标签?

[英]Active Admin: How to customize labels for select filter?

这似乎应该相当简单,买到我还没有找到关于这个主题的任何文件。

我有以下过滤器:

filter :archived, as: :select

...它给了我一个选择框形式的工作过滤器,选项“Any”,“Yes”和“No”。

我的问题是:如何自定义这些标签,使功能保持不变,但标签是“全部”,“实时”和“已存档”?

快速简便:

filter :archived, as: :select, collection: [['Live', 'true'], ['Archived', 'false']]

但是,这不会让您在不更改I18n的情况下自定义“全部”选项。

更新:这是另一种选择:

# Somewhere, in an initializer or just straight in your activeadmin file:
class ActiveAdmin::Inputs::FilterIsArchivedInput < ActiveAdmin::Inputs::FilterSelectInput
  def input_options
    super.merge include_blank: 'All'
  end

  def collection
    [ ['Live', 'true'], ['Archived', 'false'] ]
  end
end

# In activeadmin
filter :archived, as: :is_archived

我有同样的问题,但我需要自定义选择索引过滤器和表单输入,所以我找到了类似的解决方案:在app / inputs(如建议formtastic)我创建两个clases:

在app / inputs / country_select_input.rb中:

class CountrySelectInput < Formtastic::Inputs::SelectInput

  def collection
    I18nCountrySelect::Countries::COUNTRY_CODES.map { |country_code|
      translation = I18n.t(country_code, scope: :countries, default: 'missing')
      translation == 'missing' ? nil : [translation, country_code]
    }.compact.sort
  end

end

在app / inputs / filter_country_select_input.rb中:

class FilterCountrySelectInput < ActiveAdmin::Inputs::FilterSelectInput

  def collection
    I18nCountrySelect::Countries::COUNTRY_CODES.map { |country_code|
      translation = I18n.t(country_code, scope: :countries, default: 'missing')
      translation == 'missing' ? nil : [translation, country_code]
    }.compact.sort
  end

end

在我的app / admin / city.rb中:

ActiveAdmin.register City do

  index do
    column :name
    column :country_code, sortable: :country_code do |city|
      I18n.t(city.country_code, scope: :countries)
    end
    column :created_at
    column :updated_at
    default_actions
  end

  filter :name
  filter :country_code, as: :country_select
  filter :created_at

  form do |f|
    f.inputs do
      f.input :name
      f.input :country_code, as: :country_select
    end
    f.actions
  end

end

如您所见,ActiveAdmin在不同的上下文,索引过滤器或表单输入中查找Filter [:your_custom_name:] Input和[:your_custom_name:]输入。 因此,您可以创建ActiveAdmin :: Inputs :: FilterSelectInput或Formtastic :: Inputs :: SelectInput的扩展,并自定义您的逻辑。

它对我有用,我希望你能发现它很有用

这是一个有效的黑客......无需你编写新的输入控件!

filter :archived, as: :select, collection: -> { [['Yes', 'true'], ['No', 'false']] }

index do
  script do
    """
      $(function () {
        $('select[name=\"q[archived]\"] option[value=\"\"]').text('All');
      });
    """.html_safe
  end
  column :id
  column :something
end

它不是“干净”也不是“优雅”,但效果还不错:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM