Saving form data to local storage but unable to reterive it/


#1

Hi there, I’m trying to save my form data to the local storage of the app as the app has a couple of forms. SO basically what I want is the form is to be filled in two sections sec 1 and sec 2, user can fill sec 1 save it and edit it also I want the data to be there once filled and then proceed to sec 2 at the same time or may be weeks later and do the same. After the final submission(no editing can be done on forms and the data would clear out) form data of both the section would be exported on a PDF file.(Here I used the PDF code just to check if data is being printed or not.)
I tried doing that but I didn’t get the desired result _**

whenever I fill the form and serve the app the data gets lost

can anyone help me with my code…

export class SecOnePage {
  schoolName: any;
  addRess: any;
  direcTion: any;
  mapLoc: any;
  schoolType: any;
  typeSchool: any;
  headOrg: any;
  contSchool: any;

  sec1={

SchoolName: '',
Address: '',
Direction:'',
MapLoc:'',
SchoolType:'',
TypeSchool:'',
HeadOrg:'',
ContSchool:'',
  }
  pdfObj = null;

  constructor(public navCtrl: NavController, public navParams: NavParams, public loadingCtrl: LoadingController, private platform: Platform, private file: File, private fileOpener: FileOpener) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad SecOnePage');

    if (localStorage.getItem('stat') == '0') {
      var sec1 = JSON.parse(localStorage.getItem("sec1"));
      this.schoolName = sec1.SchoolName;
      this.addRess = sec1.Address;
      this.direcTion = sec1.Direction;
      this.mapLoc = sec1.MapLoc;
      this.schoolType = sec1.SchoolType;
      this.typeSchool = sec1.TypeSchool;
      this.headOrg = sec1.HeadOrg;
      this.contSchool = sec1.ContSchool;

    }
  }


  saveSecI() {
    localStorage.setItem('stat', '0');
    var sec1 = [
      {
        "SchoolName": this.schoolName
      },
      {
        "Address": this.addRess
      },
      {
        "Direction": this.direcTion
      },
      {
        "MapLoc": this.mapLoc
      },
      {
        "SchoolType": this.schoolType
      },
      {
        "TypeSchool": this.typeSchool
      },
      {
        "HeadOrg": this.headOrg
      },
      {
        "ContSchool": this.contSchool
      }

    ];


    // Or to get a key/value pair
    localStorage.setItem("sec1", JSON.stringify(sec1));
    // sec1 = JSON.parse(localStorage.getItem("sec1"));
  }
  gotoSecII(){
    //  console.log(sec1);
      var docDefinition = {
        content: [
          
          { text: this.schoolName, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.addRess, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.direcTion, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.mapLoc, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.schoolType, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.typeSchool, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.headOrg, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.contSchool, style: 'story', margin: [0, 20, 0, 20] },
     
        ],
        styles: {
          story: {
            italic: true,
            alignment: 'center',
            width: '50%',
          }
        }
      }
      this.pdfObj = pdfMake.createPdf(docDefinition);
      if (this.platform.is('cordova')) {
        this.pdfObj.getBuffer((buffer) => {
          var blob = new Blob([buffer], { type: 'application/pdf' });
   
          // Save the PDF to the data Directory of our App
          this.file.writeFile(this.file.dataDirectory, 'myletter.pdf', blob, { replace: true }).then(fileEntry => {
            // Open the PDf with the correct OS tools
            this.fileOpener.open(this.file.dataDirectory + 'myletter.pdf', 'application/pdf');
          })
        });
      } else {
        // On a browser simply use download!
        this.pdfObj.download();
    //   }
    let loading = this.loadingCtrl.create({
        content: 'Please wait...'
   });
  
    loading.present();


     loading.dismiss();




     this.navCtrl.push(SecTwoPage);
  
  }

  }
}

#2

plse use

And with this, you don’t need to stringify objects.

Plse be aware that the methods of this are async, so you need to use promise pattern.


#3

ok so that needs to create a database in your app for storing the data.
But I don’t want to create one inside my app but I’ll like to use the local storage instead.
Can you help me out with that.
Thanks!!


#4

Hi
this uses local storage. Using sqlite is optional.
The examples in the doc should guide
Tom


#5

Actually data is being saved but it is not reflecting on the input field when I open the page after killing and serving the app again.

 ionViewDidLoad() {
    console.log('ionViewDidLoad SecOnePage');

    if (localStorage.getItem('stat') == '0') {
      var sec1 = JSON.parse(localStorage.getItem("sec1"));
      this.schoolName = sec1.SchoolName;
      this.addRess = sec1.Address;
      this.direcTion = sec1.Direction;
      this.mapLoc = sec1.MapLoc;
      this.schoolType = sec1.SchoolType;
      this.typeSchool = sec1.TypeSchool;
      this.headOrg = sec1.HeadOrg;
      this.contSchool = sec1.ContSchool;

    }
  }

#6

Do a console log of sec1 after the load from localStorage. Does it show data? If yes, then your binding to form data is not correct, which is not shown in the code


#7

console.log shows the data correctly.


#8

then your problem is not in the code you show

it is in the code that binds the variables to the form


#9

My html

<ion-content padding text-wrap>
  <div>
    <ion-card class="bgcol">
      <ion-card-header text-center>
        Section I - Customer Details
      </ion-card-header>
      <ion-card-content>
        <ion-list class="bGcol">
          <ion-item class="itembg">
            <ion-label stacked style="color:black">Full Name of School:</ion-label>
            <ion-textarea [(ngModel)]="schoolName" style="background-color: whitesmoke"></ion-textarea>
          </ion-item>
          <ion-item class="itembg">
            <ion-label stacked style="color:black">Postal Address With Pin Code for Mailing:</ion-label>
            <ion-textarea [(ngModel)]="addRess" style="background-color: whitesmoke"></ion-textarea>
          </ion-item>
          <ion-item class="itembg">
            <ion-label stacked style="color:black">Direction To Reach The School (Name Of The Nearest Station/Town) And Distance:</ion-label>
            <ion-textarea [(ngModel)]="direcTion" style="background-color: whitesmoke"></ion-textarea>
          </ion-item>
          <ion-item class="itembg">
            <ion-label stacked style="color:black">Google Map Location (If Available):</ion-label>
            <ion-textarea [(ngModel)]="mapLoc" style="background-color: whitesmoke"></ion-textarea>
          </ion-item>
          <ion-item class="itembg">
            <ion-label stacked style="color:black">Type of School:</ion-label>
            <ion-select [(ngModel)]="schoolType" style="background-color: whitesmoke">
              <ion-option value="gov">Govt</ion-option>
              <ion-option value="govAid">Govt Aided</ion-option>
              <ion-option value="govSpon">Govt Sponsored</ion-option>
              <ion-option value="pvt">Private</ion-option>
            </ion-select>
            </ion-item>
            <ion-item class="itembg">
              <ion-label stacked style="color:black">Type of School:</ion-label>
              <ion-select [(ngModel)]="typeSchool" style="background-color: whitesmoke">
                  <ion-option value="gov">Secondary</ion-option>
                  <ion-option value="govAid">Higher Secondary</ion-option>
                  </ion-select>
            </ion-item>
        </ion-list>
      </ion-card-content>
    </ion-card>
    <div style="text-align:center">
        <button ion-button small (click)="saveSecI();">Save</button>
        <button ion-button small (click)="gotoSecII();">Next</button>
    </div>
  </div>

</ion-content>

my ts

export class SecOnePage {
  schoolName: any;
  addRess: any;
  direcTion: any;
  mapLoc: any;
  schoolType: any;
  typeSchool: any;


  sec1={

SchoolName: '',
Address: '',
Direction:'',
MapLoc:'',
SchoolType:'',
TypeSchool:'',

  }
  pdfObj = null;

  constructor(public navCtrl: NavController, public navParams: NavParams, public loadingCtrl: LoadingController, private platform: Platform, private file: File, private fileOpener: FileOpener) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad SecOnePage');

    if (localStorage.getItem('stat') == '0') {
      var sec1 = JSON.parse(localStorage.getItem("sec1"));
      this.schoolName = sec1.SchoolName;
      this.addRess = sec1.Address;
      this.direcTion = sec1.Direction;
      this.mapLoc = sec1.MapLoc;
      this.schoolType = sec1.SchoolType;
      this.typeSchool = sec1.TypeSchool;

    }
  }


  saveSecI() {
    localStorage.setItem('stat', '0');
    var sec1 = [
      {
        "SchoolName": this.schoolName
      },
      {
        "Address": this.addRess
      },
      {
        "Direction": this.direcTion
      },
      {
        "MapLoc": this.mapLoc
      },
      {
        "SchoolType": this.schoolType
      },
      {
        "TypeSchool": this.typeSchool
      },


    ];


    // Or to get a key/value pair
    localStorage.setItem("sec1", JSON.stringify(sec1));
    // sec1 = JSON.parse(localStorage.getItem("sec1"));
  }
  gotoSecII(){
    //  console.log(sec1);
      var docDefinition = {
        content: [
          
          { text: this.schoolName, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.addRess, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.direcTion, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.mapLoc, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.schoolType, style: 'story', margin: [0, 20, 0, 20] },
          { text: this.typeSchool, style: 'story', margin: [0, 20, 0, 20] },
     
     
        ],
        styles: {
          story: {
            italic: true,
            alignment: 'center',
            width: '50%',
          }
        }
      }
      this.pdfObj = pdfMake.createPdf(docDefinition);
      if (this.platform.is('cordova')) {
        this.pdfObj.getBuffer((buffer) => {
          var blob = new Blob([buffer], { type: 'application/pdf' });
   
          // Save the PDF to the data Directory of our App
          this.file.writeFile(this.file.dataDirectory, 'myletter.pdf', blob, { replace: true }).then(fileEntry => {
            // Open the PDf with the correct OS tools
            this.fileOpener.open(this.file.dataDirectory + 'myletter.pdf', 'application/pdf');
          })
        });
      } else {
        // On a browser simply use download!
        this.pdfObj.download();
    //   }
    let loading = this.loadingCtrl.create({
        content: 'Please wait...'
   });
  
    loading.present();


     loading.dismiss();




     this.navCtrl.push(SecTwoPage);
  
  }

  }
}

#10

localStorage considered harmful. Also, you are lazily abusing any. You know what the types of all of those things are; declare them.


#11

It is just for testing purpose. So yes I’m abusing it :joy:
And I’m getting the value but unable to display it on the form after killing and serving it again.


#12

What does it exactly show?

There is quite some horror going on in terms of typing and object definition, besides using localStorage. Not sure if that solves your issue, except that a different coding discipline/rigor would not have brought you in this position.

I would try to put {{typeSchool}} in the html to see if the value is actually bound. The [(ngModel)] bindings seem according to specification.

Just a matter of removing code until you have something that works and then slowly build it up again.


#13

Ok let me show you an example.


#14

Ugh. This attitude disgusts me so much. I think it is time for another extended break.

I understand some people at some times might not care about code quality so much. I think they’re wrong, but I acknowledge why they do it. When it comes to asking advice of volunteers, if you can’t bothered to do the best that you absolutely can as a questioner, why would you expect anybody to want to help you? More importantly, the prevalence and tolerance of garbage “do my homework/write my app” threads here crowds out legitimate community support discussions.


#15

input:

Output:


#16

True, but that is why I choose not to answer in many cases and set my expectations to the lowest possible… If apparently people feel no obstacle to investigate then I don’t feel an obstacle not to respond.

But that is off topic…


#17

The data seems to be stored in an array (with 14 elements). So you need to reference to the relevant array item.

Lots of learnings for you, my friend. But once you are there, it is going to be even more fun to code

Signing off. Got to do some work


#18

Bro you are taking it in a wrong way. previously also you did and now also.
I already told you I like your solutions but try be cool and relax.


#19

Thanks for your help and replies.
Have a nice day ahead.


#20

Congratulations. You could not possibly have written a more effective comment in terms of demotivating me to participate here.

See you whenever, everybody who I respect. This isn’t working for me.