Ember Js nested forms

2019-09-20 12:29发布

问题:

Currently I have a form called a "form A", I've created a number of views for this form, an edit, create and list. I want to be able to create a form called "form B", that will pull through "form A's ID" as a parent ID. To enable me to have a list of all form B under a "form A" (essential a one to many relationship). So at the moment under my list for "form A" I have this link for each item:

{{#link-to 'form-a.form-b.listing' form-a.id}} <!--Link to a controller -->
      <span class="btn btn-primary"> form b </span> 
{{/link-to}}

Here is also my router

 this.route('form-a', function() {
    this.route('new');
    this.route('listing');
    this.route('edit', {path: '/edit/:form-a_id' });
    this.route('form-b', function() {
      this.route('listing', {path: '/listing/:form-a_id'});
      this.route('new');
    });
  });

So I'm trying to pull through the Id of form-a for the listing. However I'm kind of stuck here as I'm unsure how what to do next and how to correctly pull through "form a" Id in the listing controller and the use it as a parent ID for each "form B". Is there a better way to have nested forms with one too many relationships or am I going about it in the best way?

I hope someone can help as this issue as I have hit the coding wall. If you need any clarifications please ask as I know I'm usually terrible at describing my issues.

回答1:

This post applies to Ember 2.x.x and was written as of 2.15.

I think what will help you out a lot is paramsFor().

It's hard to say what the "right" routing structure because your UI will dictate things somewhat, and I'm not sure how much exact URLs matter.

Here's how I would set up the routes, assuming there will be multiple form a's in time.

  this.route('form-as', function() {
    this.route('form-a', {path: '/:form-a_id'}, function() {
      this.route('new');
      this.route('listing');
      this.route('edit');
      this.route('form-b', function() {
        this.route('listing', {path: '/listing'});
        this.route('new');
      });
    });
  });

In the code above, new, listing, and edit under form a will have access to the form a id via the params in the model hook of the routes:

model(params) {
  console.log(params['form-a_id'])
  // using the [] accessor since dashes don't work for normal dictionary nav
}

In the form b segment, listing and new can get access to the form-a parameters like this:

model() {
  console.log(this.paramsFor('form-as.form-a'))
}

Watch out for those dasherized ids and model names. They are a likely source of bugs and I'm not 100% sure I got them right here. I avoid them.

For more about paramsFor(), see Reusing Route Context in the Guides and Dynamic Segments