ActiveAdmin Forms and date select inputs with Custom Pages
2 min readOct 5, 2020
This was a pain in the butt to figure out, so I wanted to share what worked for me.
The code below shows how to register/add a custom page to ActiveAdmin that’s not tied to a specific model or resource, and allows you to change a date input that, when submitted, reloads the page with the date appended to the URL as a parameter (ex: ?d=YYYY-MM-DD
). Using a get request was the simplest solution, but you can use a post request too, if needed.
With a get request
ActiveAdmin.register_page 'Marketing' do
menu label: 'Mktg' controller do
def index
@date = params[:d]&.to_date || Date.current
end
end content title: 'Marketing' do
h2 "Date: #{controller.instance_variable_get(:@date).strftime('%_m/%-d/%y')}" form action: "marketing", method: :get do |f|
label 'Date'
input :date, type: 'date', name: 'd', value: controller.instance_variable_get(:@date)
input :submit, type: :submit, value: 'Update'
end
end
end
With a post request
ActiveAdmin.register_page 'Marketing' do
menu priority: 2, label: 'Mktg'controller do
def index
@date = params[:d]&.to_date || Date.current
end
end # page_action used by post request
page_action :set_date, method: :post do
redirect_to "/admin/marketing?d=#{params[:d]}"
end content title: 'Marketing' do
h2 "Date: #{controller.instance_variable_get(:@date).strftime('%_m/%-d/%y')}" # action and method changed here
form action: "marketing/set_date", method: :post do |f|
label 'Date'
input :date, type: 'date', name: 'd', value: controller.instance_variable_get(:@date) # this is needed when using a post request
input :authenticity_token, type: :hidden, name: :authenticity_token, value: form_authenticity_token
input :submit, type: :submit, value: 'Update'
end
end
end
Reference links:
ActiveAdmin’s docs are all unfortunately sparse:
I hope this was helpful!