Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveAdmin: form input without corresponding table attribute

How can I set a textfield in an ActiveAdmin form, who do not correspond to a table attribute ?

I need it to build an autocomplete behavior, to populate a list of checkboxes.

like image 803
Ruff9 Avatar asked Oct 29 '22 21:10

Ruff9


1 Answers

In case you want the value submitted back to your model, you can create a virtual attribute by adding attr_accessible, or explicitly define them in the model, as suggested in this answer:

def my_virtual_attr= (attributes)
  #this will be evaluated when you save the form
end

def my_virtual_attr
  # the return of this method will be the default value of the field
end 

and you will need to add it to permit_params in the ActiveModel resource file.

In case you don't need the value submitted to the backend (needed for front-end processing for example), you can actually add any custom HTML to ActiveAdmin form, and this is an example code it:

ActiveAdmin.register MyModel do
  form do |f|
    f.semantic_errors # shows errors on :base
    f.inputs "My Custom HTML" do      
      f.li "<label class='label'>Label Name</label><a class='js-anchor' href='#{link}'>Link Text</a><span></span>".html_safe
      f.li "<label class='label'>Label 2 Name</label><input id='auto_complete_input'/>".html_safe
    end
    f.inputs "Default Form Attributes" do
      f.inputs          # builds an input field for every attribute
    end
    f.actions         # adds the 'Submit' and 'Cancel' buttons
  end
end
like image 104
Brary Avatar answered Nov 11 '22 07:11

Brary