Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FormBuilder to pass id of object on update

Tags:

angular

I am trying to update a row in database by passed ID.

I am having a form component, as you can see I am using reactive 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>

How do I retrieve ID from this.form.value as you can see I am trying to get id, but console.log says it's undefined. Do I have to initialize it inside of form builder or inside of html?

like image 719
sensei Avatar asked Nov 28 '25 22:11

sensei


1 Answers

You should actually utilize the reactive form you have created, now you have not done that in your html. When you build a form, you use the form controls in your html, and any possible form arrays and nested form groups. Here is a very simplified version of your code, where we can integrate the id very easily, we just decide not to even include it in the template! :)

You can use a boolean flag that doesn't show the form, until we have built it with the data you are receiving from db. Also we create a function, we call it to build the form. Let's call it buildForm() So your getProgram would call that in the callback (subscribe):

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

Then let's build the form!

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!
}

And now to the form, where we actually utilize the form controls we have created. Here we can just exclude the form control id, it will still have the value, we just don't show it. Notice the use of formControlName:

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

That's it! When you now console log the form value, it will also include the id.

Read more about reactive form, formControl:s, FormArray:s and FormGroups from the official docs.

Finally a DEMO with the code I have described above :)

PS. In case you need to have an empty form, you can build it just like you have upon initialization of the component. Then when you have received data you can call a function and patch the values like so:

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

Then of course do not use the boolean flag.

like image 82
AT82 Avatar answered Nov 30 '25 22:11

AT82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!