Sha256: 5b31bdd3c75e01914c39ede3b68e2fa4fb21a63759ad12558f11edbf4934247a

Contents?: true

Size: 1.64 KB

Versions: 1

Compression:

Stored size: 1.64 KB

Contents

angular.module("hyperadmin")
  .controller "FormCtrl", ($scope, $state, Restangular, Flash) ->
    @resource = { }
    mode = $state.current.data.mode

    if mode == "new"
      method = "post"
      target = "admin/#{$scope.resourceClass.plural}"
      successMessage = "#{$scope.resourceClass.singular_human} created successfully."
    else
      method = "patch"
      target = "admin/#{$scope.resourceClass.plural}/#{$state.params.id}"
      successMessage = "#{$scope.resourceClass.singular_human} updated successfully."

      Restangular.one(target).get().then (resource) =>
        @resource = resource

        $scope.resourceClass.form_attributes.forEach (attr) =>
          if attr.type == "date" or attr.type == "datetime"
            if @resource[attr.key]
              @resource[attr.key] = new Date @resource[attr.key]

    [ "id", "created_at", "updated_at" ].forEach (key) ->
      _.remove $scope.resourceClass.form_attributes, (attr) ->
        attr.key == key

    prettifyErrors = (errors) ->
      result = { }
      for own attr of errors
        attrSchema = _.find $scope.resourceClass.form_attributes, (attribute) =>
          attribute.key == attr

        result[attrSchema.human] = errors[attr]

      result

    @submit = =>
      onError = (response) =>
        @errors = prettifyErrors response.data

      onSuccess = (resource) =>
        $state.go "^.show", id: resource.id
        Flash.setMessage "success", successMessage

      if method == "post"
        Restangular.all(target).post(@resource).then onSuccess, onError
      else if method == "patch"
        Restangular.one(target).patch(@resource).then onSuccess, onError

    this

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hyper_admin-0.4.0 app/assets/javascripts/hyper_admin/angularjs/controllers/form_ctrl.js.coffee