text_autocomplete

text_autocomplete is input field with autocomplete function. Autocomplete options are offered after two characters are entered into input field. When autocomplete option is selected it's value is displayed in input field. Return of text_autocomplete field is by default BSON id. But can also be non id (String) value when defined by is_id: false option.

 

    10:  
      name: customer_id
      type: text_autocomplete
      search:
        table: table_name
        field: display_name
        method: return_field
or
      search: customer,customer_name
or
      search: customer,,choices_for_customer

      with_new: customer
      is_id: false
      size: 50

 

 search: Defines table name, name of the field displayed in input field and return field name. Return field name is by default id and it can be omitted.

 

When display name is omitted the last parameter defines method that will be called for obtaining autocomplete options. Method must be defined in  as class method set by table name and it will receive inputted text as parameter. Return of method represent Array of displayed value and id which will be returned by text_autocomplete field.

 

class Customer
field :name,   String
field :vat_id, String
field :name,   String
...

def self.choices_for_customer(text)
  search_by = text.to_i.to_s == text ? :vat_id : :name
  where(search_by => /#{text}/i).map { |doc| [doc.name, doc.id] }  
end

end

The code example shows how a customer can be searched either by name or VAT id.

 

with_new: option will add a button to the right side of the input field, with a link to open new customer dialog in a window. This way user doesn't have to leave form, to add a new customer when customer does not exist.

 

is_id: by default return value of text_autocomplete field is BSON id, but can also be a String value.  In the folowing example we will search for unique values of city field and offer them as choices. User may except offered choice or type a new valuecinto field.

 

    20:  
      name: city
      type: text_autocomplete
      search: customer,,choices_for_city
      is_id: false
      size: 30

and in customer.rb
 
def self.choices_for_city(text)
   distinct(:city).inject([]) do |r, city|
     r << city if city.to_s.match(/#{text}/i)
     r
   end
end

 

 

 


Last update: 29.01.2022