[フレーム]
Last Updated: April 15, 2016
·
306
· tmartin314

Custom Re-Usable Filepicker field Rails

Add the custom filepicker field to a form

Pass the current form object and the column name:
= custom_filepicker_field(form, :profile_image)

Create an application helper:

Optionally toggle multiple

# app/helpers/application_helper.rb
 def custom_filepicker_field(form, field_name, multiple=false)
 @multiple = multiple
 @form = form
 @field_name = field_name
 render 'shared/custom_filepicker_field'
 end

Then add the custom shared view file:

Customize if necessary, but most importantly notice the custom onchange method.

# app/views/shared/_custom_filepicker_field.html.slim
= @form.filepicker_field @field_name, services: 'COMPUTER, GOOGLE_DRIVE, WEBCAM',
 mimetype: 'image/*', button_class: 'btn btn-primary btn-sm',
 button_text: 'Select file',
 onchange: 'filepickerOnChange(event, $(this))',
 multiple: @multiple

Add a global js method to process the file selection

# app/assets/javascripts/filepicker.js.coffee
window.filepickerOnChange = (event, elem) ->
 content = '<span class="filepicker-filename">' + event.fpfile.filename + '</span>'
 elem.parent().append(content)

AltStyle によって変換されたページ (->オリジナル) /