Sencha Touch 2 Stores – Adding, Removing and Finding Records

In this Sencha Touch tutorial you will learn how to add, remove and find records in a Sencha Touch store. The store methods you will learn about in this post are the following:

  • add
  • insert
  • getAt
  • getById
  • removeAt
  • removeAll
  • getCount

Let’s create a simple Sencha Touch application with the following files:

The index.html file will look like this:

In the model/Hotel.js file, you will define a Hotels store like so:

Ext.define('App.store.Hotels', {
    extend: 'Ext.data.Store',
    config:{
        fields: [
            { name: 'id', type: 'int' },
            { name: 'name', type: 'string' },
            { name: 'address', type: 'string' },
            { name: 'status', type: 'int' }
        ],
        data: [
            [1, 'Siesta by the Ocean', '1 Ocean Front, Happy Island', 1],
            [2, 'Gulfwind', '25 Ocean Front, Happy Island', 1],
            [3, 'South Pole View', '1 Southernmost Point, Antarctica', 1]
        ]
    }
});

Remember that you should name stores following the AppName.store.StoreName convention. Which is why our store is named App.store.Hotels. Hotels is a simple store with a fields config and a few records hard-coded through the data config.

In the app.js file we are going to define a Sencha Touch application, acquire a reference to the Hotels store, and perform some operations on it:

Ext.application({
    name: 'App',
    stores:['Hotels'],
    launch: function () {

        var hotelsStore = Ext.getStore('Hotels'); // Shortcut  Ext.data.StoreManager.lookup. You can get a reference to any store using the Store Manager class.

        console.log('Number of hotels: ' + hotelsStore.getCount()); // Using getCount method.

        var anotherHotel = { id: 4, name: 'North Pole View', address: '1 Northernmost Point, Arctic Ocean', status: 1 };

        hotelsStore.add(anotherHotel);  // Use the add function to add records or model instances.

        var oneMoreHotel = { id: 5, name: 'View From Up High', address: 'The Moon', status: 1 };

        hotelsStore.insert(2, oneMoreHotel);    // Use insert to add records or model instances at a given index.

        console.log('Number of hotels after adding "anotherHotel": ' + hotelsStore.getCount());

        var firstRecord = hotelsStore.getAt(2);     // Use getAt function to retrieve a record at a given index.

        console.log('Third hotel\'s name is ' + firstRecord.get('name'));

        var aRecord = hotelsStore.getById(2);  // You can get a record with a given id.

        console.log('Hotel with id = 2 is ' + aRecord.get('name'));

        hotelsStore.removeAt(0);    // Use removeAt to remove a record at a given index.

        console.log('Number of hotels in the store after removing first hotel: ' + hotelsStore.getCount());

        hotelsStore.removeAll();    // Use removeAll to remove all records.

        console.log('Number of hotels in the store after removing all: ' + hotelsStore.getCount());

    }
});

If you open the index.html file in Google Chrome and activate the Javascript console, you will see a series of messages similar to this:

How It Works

The first step you need to take in the application is to add the stores config, which declares the Hotels store.

The stores config defines the list of stores to load for the application. The application assumes the files for its stores exist in the app/store directory. When adding stores to the stores config, you can type either the full class name of the store, or just the last part of the class name. In our example, you can type stores:['Hotels'] or stores:['App.store.Hotels'].

In the application’s launch function, you acquire a reference to the Hotels store using the Ext.getStore method. Then, you are ready to perform operations on the store.

You can add records or model instances to the store using the add method:

var anotherHotel = { id: 4, name: 'North Pole View', address: '1 Northernmost Point, Arctic Ocean', status: 1 };

hotelsStore.add(anotherHotel);

If you need to insert records at a particular position, you can use the insert method:

var oneMoreHotel = { id: 5, name: 'View From Up High', address: 'The Moon', status: 1 };

hotelsStore.insert(2, oneMoreHotel);

The getAt method allows you to find a record or model instance at a given position:

var firstRecord = hotelsStore.getAt(2);

You can also find records by id using the getById method

var aRecord = hotelsStore.getById(2);

Removing by position is easy with the removeAt method:

hotelsStore.removeAt(0);

Finally, you can remove all the records using removeAll:

hotelsStore.removeAll();

Want To Learn More?

My Sencha Touch books will teach you how to create a Sencha Touch application, step by step, from mockups to production build.

About Jorge

Jorge is the author of Building a Sencha Touch Application, How to Build a jQuery Mobile Application, and the Ext JS 3.0 Cookbook. He runs a software development and developer education shop that focuses on mobile, web and desktop technologies.
If you'd like to work with Jorge, contact him at ramonj[AT]miamicoder.com.

Comments

  1. Augustine Joseph says:

    Hi,
    This is really good example thanks for all your examples that help me to learn ST2.

    I tried to store to local storage using the below code and the record is added to the store but not to the local storage. I coded based on your MVC tutorials so that model and the store is same as that example except the name. Any clue. Please advice. Trying for last 2 days. But no clue. Thanks in advance for your help.

    var now = new Date();
    var noteId = (now.getTime()).toString() + (this.getRandomInt(0, 100)).toString();
    console.log(“New ID:” + noteId);
    var newNote1 = Ext.create(“NotesApp.model.TestParam”, {
    id: noteId,
    dateCreated: now,
    title: “By Joseph”,
    narrative: “By Joseph 1″
    });
    testParamsStore.add(newNote1);
    testParamsStore.sync();
    console.log(“testParamsStore size: ” + testParamsStore.getCount());

    • Thank you Augustine. Please post the testParamsStore definition.

      Make sure your store has a localstorage proxy defined. For example, look at the following store:

      Ext.define(‘App.store.MyStore’, {
      extend: ‘Ext.data.Store’,
      requires: ['Ext.data.proxy.LocalStorage'],
      config: {
      model: ‘App.model.MyModel’,
      proxy: {
      type: ‘localstorage’,
      id: ‘app-store’
      }
      }
      });

  2. Augustine Joseph says:

    hi,
    Thanks for your reply.
    I got the code from your MyNotes Sencha touch application and its working now.

    ~Jo

  3. Augustine Joseph says:

    Hi,
    I AM TRYING TO SOLVE THIS PROBLEM BASED ON YOUR MYNOTES APP.
    I can solve this issue using the same way that you are doing in your MyNotes app as mentioned below.
    Your logic
    ————–
    1) When new button is clicked you create the newNote record and then pass it to the view.
    2) When the save button is clicked you get the record and check for note id already available.
    If available then update and then add.

    MY PROBLEM
    ——————-
    What I am trying to do is just create the model on the fly and store it to the store and sync it to local storage. You can see my code between the comments //Joseph Code Starts and //Joseph Code Ends.

    The problem I am facing is that the new note is added in the store and I can see it the note list page. But when I refresh the page its not getting loaded because its not sync to the local storage. Any idea. Am I doing anything wrong here. Please advice. Thanks for your help

    CODE FROM YOUR APP
    ———————————
    onNewNoteCommand: function () {
    console.log(“onNewNoteCommand”);
    var now = new Date();
    var noteId = (now.getTime()).toString() + (this.getRandomInt(0, 100)).toString();
    var newNote = Ext.create(“NotesApp.model.Note”, {
    id: noteId,
    dateCreated: now,
    title: “”,
    narrative: “”
    });
    this.activateNoteEditor(newNote);
    },

    onSaveNoteCommand: function () {
    console.log(“onSaveNoteCommand”);

    var noteEditorView = this.getNoteEditorView();

    var currentNote = noteEditorView.getRecord();
    var newValues = noteEditorView.getValues();

    // Update the current note’s fields with form values.
    currentNote.set(“title”, newValues.title);
    currentNote.set(“narrative”, newValues.narrative);

    var errors = currentNote.validate();

    if (!errors.isValid()) {
    Ext.Msg.alert(‘Wait!’, errors.getByField(“title”)[0].getMessage(), Ext.emptyFn);
    currentNote.reject();
    return;
    }

    var notesStore = Ext.getStore(“Notes”);

    if (null == notesStore.findRecord(‘id’, currentNote.data.id)) {
    console.log(“Inside if:::” + currentNote.data.id);

    notesStore.add(currentNote);
    }

    //Joseph Code Starts
    var now = new Date();
    var noteId = (now.getTime()).toString() + (this.getRandomInt(0, 100)).toString();

    var newNote = Ext.create(“NotesApp.model.Note”, {
    id: noteId,
    dateCreated: now,
    title: “Joseph”,
    narrative: “Joseph Desc”
    });
    notesStore.add(newNote);

    //Joseph Code Ends
    notesStore.sync();

    notesStore.sort([{ property: 'dateCreated', direction: 'DESC'}]);

    this.activateNotesList();
    },

  4. I have a store with fields: id, username, address. id is my primary key or my idProperty in sencha terms.

    How would you add records to the localstorage and have the ‘id’ value auto increment? The app may not know the next ‘id’ value to insert.

    • One approach would be to create an extension of the model class that will handle the creation of the id the way you require. Maybe adding a static nextId() function.

Speak Your Mind

*