开发者

Autocomplete for Formtastic

开发者 https://www.devze.com 2023-04-05 11:29 出处:网络
I have been looking at a way to add autocomplete functionality to a formtastic form and came across the crowdint / rails3-jquery-autocomplete but I haven\'t be able to get the latest version(0.9.1) to

I have been looking at a way to add autocomplete functionality to a formtastic form and came across the crowdint / rails3-jquery-autocomplete but I haven't be able to get the latest version(0.9.1) to work with formtastic (which is a known issue) and in the previous version id-element helper doesn't work so it's not possible to set the option value in a hidden field when submit the form. And another gem, formtastic_autocomplete by elandesign is outdated. So I am wondering if there any alternat开发者_高级运维ive methods I could use to get an (jquery-ui?) autocomplete field in a formtastic form. My models are such that product belongs to a brand and a brand has many products(there is a brand_id column ib the product table), so currently I have which means that automatically creates an option select for the association

Thanks, Alex


If you don't use a gem that tries to be smart and does everything for you, the fact that you are using formtastic is kind of irrelevant. The HTML generated by formastic is not different from the HTML generated using the regular form helpers.

You can easily use the jquery ui autocomplete plugin.


Just fixed the Formtastic issue on rails3-jquery-autocomplete. Use version 1.0.2

When you say id-element is not working, do you mean in combination with Formtastic?

When I use it with the regular input it seems to work just fine.


I have written an unobtrusive, pure jQuery solution to this problem (autocomplete for belongs_to associations). You don't have to do anything special with regard to Formtastic. Simply generate a normal input field for your foreign key and add an attribute specifying the autocomplete URL and another attribute specifying the current display value of the referenced model (the brand name of an existing product in your case). Using HAML template notation (ERB is pretty much the same):

= semantic_form_for @product do |f|
  = f.inputs do
    -# Other input fields ...
    = f.input :brand_id,
        :input_html => {:'data-autocomplete-url' => auto_complete_brands_path,
                        :'data-autocomplete-value' => @product.brand.try(:name)}
:javascript
  $(function() {
    $('#product_brand_id').autocompleteAssociation();
  });

This uses a jQuery autocomplete widget I wrote specifically for such model association cases. It can be found here, together with more documentation: https://gist.github.com/3842296

0

精彩评论

暂无评论...
验证码 换一张
取 消