2017-05-31 40 views
0

我想通过传递的ID更新数据库中的一行。如何使用FormBuilder传递对象的id更新

我有一个表单组件,你可以看到我用的反应formBuilder:

@Component({ 
    selector: 'program-form', 
    templateUrl: './program.form.component.html', 
    styleUrls: ['./program.form.component.css'] 
}) 
export class ProgramFormComponent implements OnInit { 

    form: FormGroup; 
    title: string; 
    program: ProgramModel = new ProgramModel(); 

    constructor(
    formBuilder: FormBuilder, 
    private router: Router, 
    private route: ActivatedRoute, 
    private dataService: DataService 
) { 
    this.form = formBuilder.group({ 
     name: ['', [ 
     Validators.required, 
     Validators.minLength(3) 
     ]], 
    // email: ['', [ 
    //  Validators.required, 
    //  BasicValidators.email 
    // ]], 
    // phone: [], 
    // address: formBuilder.group({ 
    //  street: ['', Validators.minLength(3)], 
    //  suite: [], 
    //  city: ['', Validators.maxLength(30)], 
    //  zipcode: ['', Validators.pattern('^([0-9]){5}([-])([0-9]){4}$')] 
    // }) 
    }); 
    } 

    ngOnInit() { 
    var id = this.route.params.subscribe(params => { 
     var id = params['id']; 

     this.title = id ? 'Edit' : 'New'; 

     if (!id) 
     return; 

     this.getProgram(id); 
    }); 
    } 

    private getProgram(id: number) { 
     this.dataService.setEndpoint('/api/program/getsingle'); 
     this.dataService 
      .GetSingle(id) 
      .subscribe(data => { 
       this.program = data 
      }, (error) => { 
       console.log(error); 
      }); 
    } 

    create() { 
    var result, 
     userValue = this.form.value; 

     console.log(userValue.Id + ", userValueId"); 

    if (userValue.id){ 
     this.dataService.setEndpoint('/api/program/update'); 
     result = this.dataService.Update(userValue.Id, userValue); 
    } 
    else 
    { 
     this.dataService.setEndpoint('/api/program/create'); 
     this.dataService.Create(userValue).subscribe(data => { 
       (data => this.router.navigate(['users'])); 
      }, (error) => { 
       console.log(error); 
      });; 
    } 

    //result.subscribe(data => this.router.navigate(['users'])); 
    } 
} 

HTML:

<div class="row"> 
    <form materialize class="col s12" [formGroup]="form" (ngSubmit)="create()"> 
    <div class="row"> 
     <div class="input-field col s12"> 
     <i class="material-icons prefix">account_circle</i> 
     <label for="name" 
       [class.active]="program.name" 
       data-error="Name is required and needs to contain at least 3 chars"> 
      Name 
     </label> 
     <input id="name" type="text" class="validate" 
       [(ngModel)]="program.name" formControlName="name" 
       [class.invalid]="form.controls['name'].touched && !form.controls['name'].valid"> 
     </div> 
    </div> 

    <button class="btn waves-effect waves-light" type="submit"> 
     Submit<i class="material-icons right">send</i> 
    </button> 
    </form> 
</div> 

如何从this.form.value为您检索ID可以看到我试图获得id,但console.log说它是未定义的。我是否需要在表单构建器或html内部初始化它?

+0

哪里有id?我看不到任何你想传递它的地方?'我瞎了吗:D – Alex

+0

你甚至没有在你的html中使用formbuilder? – Alex

+0

你能解释一下吗?我不确定你的意思。 –

回答

0

看来你没有在窗体本身上的Id应该用户输入这个ID或从哪里得到它?

如果你想成为在表格上,你将不得不添加到窗体团,如:

id: [id ||''], 
name: ['', [... 
+0

我有一个项目列表,然后点击Edit(so我为每个项目获得Id)。这个ID应该以编辑的形式传递。 –

+0

如果您在创建代码应该工作的表单时拥有该ID。 –

+0

所以我真的不明白你为什么要添加id到表单中,如果你不做任何修改的话。但是如果你想这样做,记得在创建表单之前拥有这个id,并像我向你展示的那样构建它。 –

0

你其实应该利用你所创建的反应形式,现在你还没有这样做,在你的HTML 。当你创建一个表单时,你可以在你的html中使用表单控件,以及任何可能的表单数组和嵌套表单组。这里是你的代码的一个非常简化的版本,我们可以很容易地集成这个id,我们只是决定不将它包含在模板中! :)

您可以使用不显示表单的布尔标志,直到我们用您从db接收的数据构建它。此外,我们创建一个函数,我们称之为构建表单。让我们把它buildForm()所以你getProgram将调用回调(订阅):

.subscribe(data => { 
    this.program = data; 
    this.buildForm(); // here! 
}, ... 

然后让我们构建的形式!

buildForm() { 
    this.form = this.formBuilder.group({ 
    id: [this.program.id] 
    name: [this.program.name] 
    }); 
    this.isDone=true; // set boolean flag true so that the form will be shown! 
} 

现在转到表单,我们实际使用了我们创建的表单控件。在这里,我们可以排除表单控件id,它仍然有价值,我们只是不显示它。注意使用formControlName

<form [formGroup]="form" *ngIf="isDone" (ngSubmit)="create(form.value)"> 
    <input formControlName="name" /> 
    <button type="submit">Submit</button> 
</form> 

这就是它!当您现在控制台记录表单值时,它也会包含该ID。

了解更多关于反应形式,formControl:S,FormArray:S和来自本official docsFormGroup秒。

最后一个DEMO与我上述:)

PS所描述的代码。如果你需要一个空的表单,你可以像组件初始化时那样构建它。然后当你收到数据时,你可以调用一个函数并修改数值,如下所示:

this.form.patchValue({ 
    id: this.program.id, 
    name: this.program.name 
}) 

然后当然不要使用布尔标志。