Quantcast
Channel: Zammad - Community - Latest posts
Viewing all articles
Browse latest Browse all 6728

Attachments in form

$
0
0

Hi I am creating my own package, I need to create App.ControllForm in a modal window that will have options to add attachments, what api should I use and form tags.
currently I have it done like this

class AssetModal extends App.ControllerModal
  head: __('Model')
  shown: true
  buttonSubmit: true
  buttonCancel: true
  large: true

  content: ->
    false

  render: ->
    super
    @form_id = App.ControllerForm.formId()

    content = $(App.view('asset/form')())

    @form = new App.ControllerForm(
      el: content.find('.js-form')
      model:
        configure_attributes: [
          { name: 'name', display: __('Nazwa'), tag: 'input', null: false, },
          { name: 'serial_number', display: __('Numer seryjny'), tag: 'input',null: false },
          { name: 'organization_id', display: __('Organization'), tag: 'autocompletion_ajax_customer_organization', multiple: false, null: false, relation: 'Organization', },
          { name: 'user_ids', display: __('User'), tag: 'autocompletion_ajax', relation: 'User', null: true, },
          { name: 'invoice', display: __('Faktura'), tag: 'file_upload',form_id: @form_id, class: 'input', null: true,  },
          { name: 'attachments', display: __('Załączniki'), tag: 'file_upload', form_id: @form_id, class: 'input', null: true,  },
          { name: 'asset_model_id', display: __('Aktywo'), tag: 'autocompletion_ajax', relation: 'AssetModel', null: true, },
          { name: 'seller_model_id', display: __('Sprzedawca'), tag: 'autocompletion_ajax', relation: 'SellerModel', null: true,},
          { name: 'purchase_date', display: __('Data kupna'), tag: 'date', class: 'input', null: true },
          { name: 'purchase_cost', display: __('Koszt kupna'), tag: 'decimal', null: true},
          { name: 'description', display: __('Opis'), tag: 'textarea',upload:true, class: 'input', null: true},
        ]
      params: @data
    )

    callback = (data) =>
      @objects = data.items
      return if data.items.length >= data.total_count

    @el.find('.modal-body').html(content)
      
  onSubmit: (e) =>
    params = @formParam(e.target)
    error = @form.validate(params)

    if error
      @formValidate(form: e.target, errors: error)
      return false

    isEditing = Boolean(@data)
  
    if isEditing
      @ajax({
      id: 'assets_edit',
      type: 'PUT',
      url: "#{@apiPath}/assets/#{@data.id}",
      data: JSON.stringify(params),
      processData: true,
      success: (data) =>
        @close()
        @successCallback()
      })
      return
    @ajax({
      id: 'assets_add',
      type: 'POST',
      url: "#{@apiPath}/assets/",
      data: JSON.stringify(params),
      processData: true,
      success: (data) =>
        @close()
        @successCallback()
    })

# coffeelint: disable=camel_case_classes
class App.UiElement.file_upload
  @render: (attributeConfig, params, form) ->
    console.log form
    attribute = $.extend(true, {}, attributeConfig)
    attachments = []
    item = $( App.view('generic/file_upload')(attribute: attribute) )
    @form_id = attribute.form_id

    renderFile = (file) ->
      item.find('.attachments').append(App.view('generic/attachment_item')(file))
      attachments.push file

    item.find('.attachments').on('click', '.js-delete', (e) ->
      id = $(e.currentTarget).data('id')
      attachments = _.filter(
        attachments,
        (item) ->
          return if item.id.toString() is id.toString()
          item
      )


      # delete attachment from storage
      App.Ajax.request(
        type:        'DELETE'
        url:         "#{App.Config.get('api_path')}/asset_attachments/#{@form_id}"
        processData: false
      )

      element = $(e.currentTarget).closest('.attachments')
      $(e.currentTarget).closest('.attachment').remove()
      if element.find('.attachment').length == 0
        element.empty()
    )

    new App.Html5Upload(
      uploadUrl:              "#{App.Config.get('api_path')}/asset_attachments/"
      dropContainer:          item.find("[name=#{attribute.name}]")
      cancelContainer:        item.find('.js-cancel')
      inputField:             item.find('input')
      data:
        form_id: @form_id
      onFileCompletedCallback: (response) ->
        renderFile(response.data)
      attachmentPlaceholder: item.find('.attachmentPlaceholder')
      attachmentUpload:      item.find('.attachmentUpload')
      progressBar:           item.find('.attachmentUpload-progressBar')
      progressText:          item.find('.js-percentage')
    ).render()
    item
class AssetAttachmentsController < ApplicationController
  prepend_before_action :authentication_check, except: %i[show destroy]
  prepend_before_action :authentication_check_only, only: %i[show destroy]

  def show

    view_type = params[:preview] ? 'preview' : nil
    send_data(
      download_file.content(view_type),
      filename:    download_file.filename,
      type:        download_file.content_type,
      disposition: download_file.disposition
    )
  end

  def create
    file = params[:File]
    content_type = file.content_type

    if !content_type || content_type == 'application/octet-stream'
      content_type = if MIME::Types.type_for(file.original_filename).first
                       MIME::Types.type_for(file.original_filename).first.content_type
                     else
                       'application/octet-stream'
                     end
    end

    headers_store = {
      'Content-Type' => content_type
    }

    store = Store.create!(
      object:      'Asset::Attachemnt',
      o_id:        params[:form_id],
      data:        file.read,
      filename:    file.original_filename,
      preferences: headers_store
    )

    render json: {
      success: true,
      data:    {
        id:          store.id,
        filename:    file.original_filename,
        size:        store.size,
        contentType: store.preferences['Content-Type']
      }
    }
  end

  def destroy
    Store.remove_item(download_file.id)

    render json: {
      success: true,
    }
  end

  def destroy_form
    Store.remove(
      object: 'Asset::Attachemnt',
      o_id:   params[:form_id],
    )

    render json: {
      success: true,
    }
  end

  private

  def user_not_authorized(e)
    not_found(e)
  end
end


Viewing all articles
Browse latest Browse all 6728

Trending Articles