Jorge Ramon

  • Home
  • New Here?
  • Articles
    • All
    • Sencha Touch
    • jQuery Mobile
    • ExtJS
  • Books
  • About

Sencha Touch 2 Stores – Adding, Removing and Finding Records

October 2, 2012 20 Comments

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.

  • Sencha Touch 2 Book
  • Sencha Touch 1 Book

Stay Tuned

Don’t miss the next article. Get free updates in your inbox.



MiamiCoder will never sell your email address.

Tagged With: Sencha Touch Tutorial 20 Comments

Comments

  1. Augustine Joseph says

    November 24, 2012 at 8:19 AM

    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());

    Reply
    • Jorge says

      November 24, 2012 at 8:11 PM

      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’
      }
      }
      });

      Reply
    • jesse says

      October 24, 2013 at 6:36 PM

      Thanks!!!!
      after several hrs, I finally found your posts.
      I went back and checked my Appxxx.store.subfolder.subfolder.MyStorexxx
      setting and all is okay now.

      J

      Reply
  2. Augustine Joseph says

    November 28, 2012 at 10:45 AM

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

    ~Jo

    Reply
  3. Augustine Joseph says

    November 28, 2012 at 11:11 AM

    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();
    },

    Reply
  4. D Smith says

    November 29, 2012 at 3:31 PM

    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.

    Reply
    • Jorge says

      November 29, 2012 at 9:17 PM

      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.

      Reply
  5. abdul says

    May 23, 2013 at 8:21 AM

    Hi,
    This is really good example thanks for all your examples that help me to learn ST2.
    Can you write tutorial on Unit Testing using jasmine for ST2., i Think Lots of people goggling about that but, nobody can get nice tutorial.

    Reply
    • Jorge says

      May 24, 2013 at 8:06 AM

      Thank you Abdul. The topic of testing is very important. I have it on my list of subjects to write about.

      Reply
  6. Marius says

    July 3, 2013 at 7:27 AM

    I’m a little confused. I’m not sure when to use models and when to work directly with the store. Any suggestions ? I keep looking but nothing obvious found… I’m just guessing..

    Reply
    • Jorge says

      July 3, 2013 at 3:12 PM

      Use only models when you don’t need to keep track of more than one instance of the model. For example, a login view might use a Login model that contains the credentials for the user. You probably don’t need multiple instances of the model because the view pertains to only one user. In that case an instance of the model is enough, and you can call load, save, etc. on the model. After login you might take the user to a books page, where you might need a books store to keep track of multiple instances of a book model.

      Reply
  7. Riyaad says

    July 12, 2013 at 9:17 AM

    Hi Jorge,
    How do you find records that share the same name and remove all from your store using a single click?
    I’ve found that …
    listeners: {
    tap: function() {
    var chosenItem = Ext.getCmp(‘itemList’).getSelection();
    Ext.getStore(‘itemStore’).remove(chosenItem[0]);
    console.log(‘Button tapped’);
    }
    }
    only removes the single record. I’m looking to remove all records that shame the same ‘name’ for example?

    Reply
    • Jorge says

      July 12, 2013 at 9:42 AM

      You can use the store’s find, findBy, filter and filterBy methods to either find the records that match the criteria, or filter the store by the criteria. Once you know the position of the records, you can remove them.

      Reply
      • sortsorat says

        July 13, 2013 at 4:40 AM

        I am new to sencha..I am totally confused.. i tried to add new record..it was success..but it couldn’t update the hotels.js store data. On relaunch it always shows the records in hotels.js ..not showing the added one’s..Hope u can understand..

        Reply
        • Jorge says

          July 13, 2013 at 9:26 AM

          The definition of the store does not include a proxy. This is why upon relaunch you don’t see the record you added. Go ahead and define a local storage proxy, or an ajax or rest proxy with a backend, and you will see the new record be persisted and loaded upon relaunch.

          Reply
          • sortsorat says

            July 18, 2013 at 1:53 AM

            Thanks Jorge

  8. dharma kshetri says

    July 16, 2013 at 3:39 AM

    I have problem, during set value in select field, If anyone have idea. How set value in selectfield using data from server.
    Please go to link, I have posted my problem:
    stackoverflow.com/questions/17668080/how-to-convert-object-to-array-and-set-value-in-to-selectfield-in-sencha

    Reply
  9. Riyaad says

    July 16, 2013 at 6:35 AM

    Thank you Jorge – appreciated (“,)

    Reply
    • sortsorat says

      July 26, 2013 at 1:13 AM

      Hi Jorge,
      Please help me ..I need to retain the data in store until user delete it..I already told u On relaunch it always shows the 0 records ..not showing the added one’s..
      I will put my code:

      Savestore.js

      Ext.define(‘InMindApp.store.SaveStore’,{
      extend:’Ext.data.Store’,
      requires:[‘Ext.data.proxy.LocalStorage’],
      config:{
      model:’InMindApp.model.SaveModel’,
      proxy:{
      type :’localstorage’,
      id:’InMindStore’
      }
      }
      });

      SaveModel.js

      Ext.define(‘InMindApp.model.SaveModel’,{
      extend:’Ext.data.Model’,
      config:{
      fields:[
      {name:’name’,type:’string’}
      ]
      }
      });

      view.js
      {
      xtype:’button’,
      ui: ‘confirm’,
      text: ‘Save’,
      handler: function () {

      var temp_store = Ext.getStore(‘SaveStore’);
      console.log(‘Bfore insertion”: ‘ + temp_store.getCount());
      var anotherStore = { name: ‘North Pole View’};
      temp_store.add(anotherStore);
      console.log(‘After insertion”: ‘ + temp_store.getCount());
      }
      }

      Current output:
      On Initial launch:
      Bfore insertion”: 0
      After insertion”: 1

      On relaunch:
      Bfore insertion”: 0
      After insertion”: 1

      Expecting output:
      On Initial launch:
      Bfore insertion”: 0
      After insertion”: 1

      On relaunch or refreshing:
      Bfore insertion”: 1
      After insertion”: 2

      Not sure what i am doing is current..Please help to make it work..

      Reply
  10. Daniel says

    July 30, 2013 at 5:15 AM

    Hi Jorge,
    Thanks your artical ! that help me to learn ST2.
    In the example, getById(2) only get a NULL ??? but getAt(2) can goold work.
    I’m not sure whether ST2.2.1 can not use getById ??

    The environment: window 7, Firefox 22.0, ST version 2.2.1
    FireBug tip:
    TypeError: aRecord is null
    console.log(‘Hotel with id = 2 is ‘ + aRecord.get(‘name’));

    Reply

Leave a Comment Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Get My Books

The beginner's guide to Sencha Touch apps
The beginner's guide to jQuery Mobile apps

Book: How to Build a jQuery Mobile Application

Topics

  • » jQuery Mobile Tutorials
  • » Sencha Touch Tutorials
  • » ExtJS Tutorials
  • » Books
  • » Tools
  • » .Net Tutorials
  • » BlackBerry Tutorials
  • » iOS Tutorials
  • » Node.js Tutorials
  • » Android Training
  • » BlackBerry Training
  • » iOS Training

Search

Contact Me

  •  Email: jorge[AT]jorgeramon.me
  •  Twitter: @MiamiCoder
  •  LinkedIn: Jorge Ramon


Don’t Miss the Free Updates

Receive free updates in your inbox.
Your address is safe with me.

Copyright © 2019 Jorge Ramon · The opinions expressed herein do not represent the views of my employers in any way · Log in