Vaidehi Patel
Vaidehi Patel

Reputation: 75

how to read extjs data store

I want to read a particular value of an extjs data store and manipulate it locally. Response xml looks like :

<user><name>abc</name><surname>def</surname><book><bname>book1</bname></book></user>

My store will have just one user entry when response is received and i want to read 'bname' value. So far i have tried two approaches and both giving error.

approach1:

Ext.define('user', {
     extend: 'Ext.data.Model',
     fields: [ 'name', 'surname'],
     hasMany: {model: 'Book', name: 'book'},
      proxy: {
        type: 'rest',
         url : request,
         reader: { type: 'json', root: 'user'}
     }
 });
 Ext.define('Book', {
     extend: 'Ext.data.Model',
     fields: [ 'name'],
     belongsTo: 'user'
 });
 var userstore = Ext.create('Ext.data.Store', {
        model: "user"
 });
 incidentstore.load({
     callback: function() {
        var inc = userstore.first();
        var bk = inc.getBook();
        console.log(dev.get('bname'));
    }
});

Running above code gives error that 'Ext.define is not a function'.

Approach2:

var proxy1 = new Jx.JxHttpProxyRest({
    url: request,
    api : {
            read : { headers : {     'Accept' : APP + '.abc.def.usermanage.user+json;version=1' } }
        }
    });

var reader = new Ext.data.XmlReader( {
    rootProperty : 'user',
    record : 'book',
    id : 'id',
}, [{ name : 'bname', mapping : 'book > bname'} ]);

var writer = new Ext.data.XmlWriter( {
    encode : false
});

var newstore = new Ext.data.Store( {
    id : 'book',
    restful : true,
    proxy : proxy1,
    remoteSort : true,
    reader : reader,
    writer : writer,
    autoload: true,
    listeners: {
        load: function() {
            console.log(newstore.data.first());
        }
    }
});
Ext.data.DataProxy.addListener('load', function(proxy, type, action, options, res) {
    console.log(res.responseText);
});
newstore.load( {
    params : { start : 0, limit : myPageSize },

});

Above code does not display anything on console.

I am new to extjs and not sure how i can access 'bname' value from response. It would be great if someone can help

Upvotes: 4

Views: 30128

Answers (5)

zloctb
zloctb

Reputation: 11194

var departmentStore = Ext.create('Ext.data.Store', {
fields : [
'name',
'active',
'dateActive',
'dateInactive',
'description',
'director',
'numEmployees',
{
name : 'id',
type : 'int'
}
],
proxy : {
type : 'ajax',
url : 'data.json',
reader : {
type : 'json',
root : 'data',
idProperty : 'id',
//successProperty : 'meta.success'  //???
}
}
});

departmentStore.load({
callback : function(records, operation, successful) {
if (successful) {
console.log('department name:',
records[0].get('name'));
}
else {
console.log('the server reported an error');
}
}
});

Upvotes: 0

Vaidehi Patel
Vaidehi Patel

Reputation: 75

Below code worked for me :

var newproxy = new Ext4.data.proxy.Rest({
    url : request,
    headers : {
        },
    reader :  {
        type : 'json',
        root : 'user.book'
    }});

 // Typical Store collecting the Proxy, Reader and Writer together.
 var newstore = Ext4.create('Ext4.data.Store', {
     id : 'book',
     fields: ['bname'],
     restful : true, // <-- This Store is RESTful
     autoLoad : true,
     proxy : newproxy
 });

var book;
newstore.load();
newstore.each(function(rec) {
    book= rec.get('bname');
});

Upvotes: 2

lontivero
lontivero

Reputation: 5275

Take a look at this:

// The user model definition
Ext.define('user', {
   extend: 'Ext.data.Model',
   fields: [ 'name', 'surname', 'book' ]
});

// The store instance
var userstore = Ext.create('Ext.data.Store', {
   model: 'user',
   proxy: {
        type: 'memory',
        reader: {
            type: 'xml',
            record: 'user',
            root: 'users'
        }
    }
});

// data sample to test the approach
mydata =
    [
        ['Juan', 'Alonso', [ { bname: 'El loco' }, { bname: 'El cuerdo' } ]],
        ['Susana', 'Cabrera', [ { bname: 'Adios a las palomas' }]]
    ];

// load the store with the sample data 
userstore.loadData(mydata, false);  

// display the first book for the first record
var firstRecord = userstore.getAt(0);
var firstBook = firstRecord.get('book')[0]; 
alert(firstBook.bname )

​Or see the working code here: http://jsfiddle.net/lontivero/HTj5Q/

As you can see, it works fine. However, if your store will have 'always' just one record, then you shouldn´t use a store, you should use a model and load the model.

UPDATE:

Ok, if you are using extjs 3.1.1 (it would be good to gave such important information before) you can do it as follow:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
      <title>For extjs 3.1.1</title>

        <script src="http://extjs-public.googlecode.com/svn/tags/extjs-3.1.1/release/adapter/ext/ext-base.js" type="text/javascript" ></script>
        <script src="http://extjs-public.googlecode.com/svn/tags/extjs-3.1.1/release/ext-all.js" type="text/javascript" ></script>
    </head>
    <body>
        <script type="text/javascript">
        Ext.onReady(function(){
            // The store instance
            var userstore = new Ext.data.ArrayStore({
                 fields: ['name', 'surname', 'book'],
                 reader: new Ext.data.ArrayReader({
                     idIndex: 0  // id for each record will be the first element
                 })
            });

            // data sample to test the approach
            mydata =
                 [
                      ['Juan', 'Alonso', [ { bname: 'El loco' }, { bname: 'El cuerdo' } ]],
                      ['Susana', 'Cabrera', [ { bname: 'Adios a las palomas' }]]
                 ];

            // load the store with the sample data 
            userstore.loadData(mydata, false);  

            // display the first book for the first record
            var firstRecord = userstore.getAt(0);
            var firstBook = firstRecord.get('book')[0]; 
            alert(firstBook.bname );
        });

        </script>
    </body>
</html>

Upvotes: 5

Izhaki
Izhaki

Reputation: 23586

You are using Ext version 4 code, but your library is 3.1.1

It simply wouldn't work unless you upgrade your library to version 4.

Upvotes: 1

Johan Van de Merwe
Johan Van de Merwe

Reputation: 312

To make the sample of Lontivero complete, it is also useful to find a record on a specific key with the findRecord method. As the sample shows below (based on the sample of lontivero), it will only get the first found record. So this is very useful if you work with a store with a unique key.

You can see this sample live at: http://jsfiddle.net/jvandemerwe/dGUGb/25/

// The user model definition
Ext.define('user', {
   extend: 'Ext.data.Model',
   fields: [ 'name', 'surname', 'book' ]
});

// The store instance
var userstore = Ext.create('Ext.data.Store', {
   model: 'user',
   proxy: {
        type: 'memory',
        reader: {
            type: 'xml',
            record: 'user',
            root: 'users'
        }
    }
}); 

// data sample to test the approach
mydata =
    [
        ['Juan', 'Alonso', [ { bname: 'El loco' }, { bname: 'El cuerdo' } ]], 
        ['Juan', 'Lopez', [ { bname: 'Superdooper' }, { bname: 'Swinglist' } ]],  
        ['Susana', 'Cabrera', [ { bname: 'Adios a las palomas' }]]
    ];

// load the store with the sample data 
userstore.loadData(mydata, false);  

// Finds the first!!! matching Record in this store by a specific field value.
// API info: findRecord( fieldName, value, [startIndex], [anyMatch], [caseSensitive], [exactMatch] )

var keyToFind = 'Juan';
var found = userstore.findRecord('name', keyToFind, 0, false, false, true);

if (found != null) {

    var list = '';
    var author = found.get('name')+' '+ found.get('surname');
    var books = found.get('book');

    Ext.each(books, function(book, idx) {
        if (list != '') list = list + ', ';
        list = list+book.bname;
    });

    alert('Books of '+author+'\n'+list);
} else {
    alert('no books with key \''+keyToFind+'\'');
}

Upvotes: 0

Related Questions