Handling server side validation with Ember Data

风格不统一 提交于 2019-12-10 17:14:14

问题


I'm having trouble handling server side validations with Ember and Ember Data.

When a validation error occurs, the API returns the code 422. Ember data then triggers the becameInvalid callback on the model.

From here, I'm not sure what's the best way to handle the errors I'm getting, and how to make them bubble up to the view.

App.Challenge = DS.Model.extend Ember.Validations,
    title: attr('string')
    summary: attr('string')
    # other attributes

    becameInvalid: (errors) ->
        # is it the place where I should handle the errors?
        # how would I make the errors bubble up to the view here?

I have 2 issues.

  • I'm not sure if becameInvalid is the place to handle the errors, and if it is, how to make the errors display in the view
  • In becameInvalid, @get('isValid') returns true, which doesn't make sense to me.

回答1:


is it the place where I should handle the errors?

Yes. But you might not need to do anything at all. Ember-data expects your api to have included any validation errors in it's json response. That errors object is passed to the becameInvalid hook and also saved as a property errors on the model. So if all you want to do is display the errors in your view, it might be enough to do something like:

{{input value=firstName}}<p class="inline-help">{{errors.firstName}}</p>

See: https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/rest_serializer.js#L50-L61

In becameInvalid, @get('isValid') returns true, which doesn't make sense to me

Agreed that's weird. I think it's a bindings thing, like the becameInvalid hook is running before bindings have updated.



来源:https://stackoverflow.com/questions/17434350/handling-server-side-validation-with-ember-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!