Extjs - How to refer the json datas in a controller? - json

I'm developing a simple login page wherein I need to compare the value that has been entered by any user in username field, with the json data store on click of 'LoginButton'. My question is, can we get the list of username from the json store in an array and compare with textfield values? If so, how?
My nSpaceIndex.html
<html>
<head>
<title>nSpace | Expense / Project Solutions</title>
<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
<script type="text/javascript" src="extjs/ext-debug.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
</body>
</html>
app.js:
Ext.application({
requires: ['Ext.container.Viewport'],
name: 'nSpace',
controllers: [
'nSpaceController'
],
appFolder: 'app',
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: {
xtype: 'loginView'
}
});
}
});
my nSpaceController.js:
Ext.define('nSpace.controller.nSpaceController', {
extend: 'Ext.app.Controller',
stores: [
'Users'
],
views: [
'login.loginView'
],
model: 'loginModel',
init: function() {
this.control({
"#loginButton": {
click: this.onLoginButtonClick
}
});
},
onLoginButtonClick: function(){
//var jsonArray = store.Users.data.items
//console.log(jsonArray);
// I NEED TO GET THE REFERENCE OF MY STORE: USERS TO COMPARE
var logUserName = Ext.getCmp('getUserName').getValue();
var logPassword = Ext.getCmp('getPassword').getValue();
if(logUserName == 'user01' && logPassword == 'password01'){
Ext.MessageBox.show({title: 'Success', msg: 'You will be redirected to the home page in few moments...', icon:Ext.MessageBox.INFO});
}
else if(logUserName == 'user02' && logPassword == 'password02'){
Ext.MessageBox.show({title: 'Success', msg: 'You will be redirected to the home page in few moments...', icon:Ext.MessageBox.INFO});
}
else{
Ext.MessageBox.show({title: 'OOPS!!!', msg: 'Please Enter Valid Details', icon:Ext.MessageBox.WARNING});
}
},
});
my loginModel.js:
Ext.define('nSpace.model.loginModel', {
extend: 'Ext.data.Model',
fields: ['loginusername', 'password']
});
Users.js:
Ext.define('nSpace.store.Users', {
extend: 'Ext.data.Store',
model: 'nSpace.model.loginModel',
autoLoad : true,
proxy: {
type: 'ajax',
url: 'data/users.json',
reader: {
type: 'json',
root: 'users',
successProperty: 'success'
}
}
});
loginView.js:
Ext.define('nSpace.view.login.loginView' ,{
extend: 'Ext.form.Panel',
alias: 'widget.loginView',
store: 'Users',
title: 'nSpace | Login',
frame:true,
bodyPadding: 5,
width: 350,
layout: 'anchor',
defaults: {
anchor: '100%'
},
defaultType: 'textfield',
items: [{
fieldLabel: 'User Name',
name: 'loginusername',
id: 'getUserName',
allowBlank: false
},{
fieldLabel: 'Password',
inputType: 'password',
id: 'getPassword',
name: 'password',
allowBlank: false
}],
// Reset and Submit buttons
buttons: [{
text: 'Sign Up',
handler: function() {
// location.href = 'signUp.html';
}
},{
text: 'Reset',
handler: function() {
this.up('form').getForm().reset();
}
}, {
text: 'Login',
id:'loginButton',
formBind: true, //only enabled once the form is valid
disabled: true,
}],
renderTo: Ext.getBody()
});
users.json:
{
"success": true,
"users": [
{"loginusername": 'user01', "password": 'password01'},
{"loginusername": 'user02', "password": 'password02'}
]
}

inside init function above this.control
try using this..
var store = this.getUsersStore();
store.load({
callback:function(){
var l = store.first();
console.log(l.get("password"));
}
});
this is how you can check
store.each(function(rec){
if (rec.get('password') === value) {
display = rec.get('username');
return false;
}
});

As other users have pointed out, it is trivial to perform authorization on the client side of the application. However you have stated that this is not a concern, therefore I will answer your question without addressing the obvious security flaws of this approach.
I see that you're making use of Ext.getCmp() therefore your components have been assigned an id. This is generally considered to be bad practice as the id property is global, and therefore if there are two components instantiated with the same id, the application will crash. You may find it useful to instead assign the component an itemId and create a reference to easily retrieve the component in the Controller's refs[] definition.
For example:
Ext.define('nSpace.controller.nSpaceController', {
... other store/model/view here ...
refs: [{
name: 'userNameField', // makes magic method 'getUserNameField()'
selector: 'textfield[name=loginusername]',
xtype: 'textfield'
},{
name: 'passwordField', // makes magic method 'getPasswordField()'
selector: 'textfield[name=password]',
xtype: 'textfield'
}],
this.control({ .. observe events here .. });
});
Retrieve a reference to your store, and search for the provided user...
var me = this, // controller
store = Ext.getStore('Users'),
user = me.getUserNameField.getValue(),
pass = me.getPasswordField().getValue(),
success;
// Attempt to find a record matching the provided user/pass
success = store.findBy(function(rec){
return (rec.get('loginusername') === user && rec.get('password') === pass);
});
// Store findBy returns the index, or -1 if no matching record is found
if(success >= 0){
// user/password matched
}else{
// no user/password match found
}

Related

Get value from other element in Polymer 1

I have a "login-imp.html" file (polymer 1 element) that checks the login and gets username and someID.
I need to retrieve that "someID" in other polymer element that is in another html file (modal-imp.html).
login-imp.html
<dom-module id="login-imp">
<style>...</style>
<template>
<iron-ajax id="limp" url="SOMEURL" method="POST" handle-as="json"
content-type="application/json" with-credentials="true" on-response="_handleResponse" on-error="_handleError">
</iron-ajax>
<iron-a11y-keys keys="enter" on-keys-pressed="_logIn"></iron-a11y-keys>
<div class="login">
<paper-input value={{username}} label="[[lang.login_imp.user]]" name="username"></paper-input>
<paper-input value="{{password}}" label="[[lang.login_imp.password]]" name="password" type="password"></paper-input>
<span class="error-message">[[errorMessage]]</span>
<paper-button id="login-button" on-tap="_logIn" raised>[[lang.login_imp.signin]]</paper-button>
</div>
<paper-dialog id="modalSignUp" entry-animation="scale-up-animation" exit-animation="fade-out-animation" with-backdrop>
<modal-signup-imp id="modal-signup-view" lang="[[lang]]" config="[[config]]"></modal-signup-imp>
</paper-dialog>
</template>
<script>
Polymer({
is: 'login-imp',
properties: {
loggedIn: {
type: Boolean,
notify: true
},
profile: {
type: Object,
notify: true,
value: function () {
return {}
}
},
username: {
type: String,
notify: true,
value: ''
},
password: {
type: String,
notify: true,
value: ''
},
retailerId: {
type: String,
notify: true,
value: ''
},
config: {
type: String
},
default: {
type: Array,
notify: true
},
lang: {
type: String
},
errorMessage: String,
observers: ['_removeMessage(username, password)']
},
ready: function () {
this.addEventListener('eventFromChild', this.closeModal);
},
_logIn: function () {
Polymer.dom(this.root).querySelector("#login-button").disabled = true;
this.$.limp.body = JSON.stringify({
"username": this.username,
"password": this.password
});
this.$.limp.generateRequest();
},
_handleResponse: function (xhrResponse) {
Polymer.dom(this.root).querySelector("#login-button").disabled = false;
var message = xhrResponse.detail.response.message;
if (message == "Access granted (" + this.username + ")") {
// save profile
this.profile = xhrResponse.detail.response.user
// change status to logged in
this.loggedIn = true;
this.username = '';
this.password = '';
//THIS IS THE ID I NEED
this.retailerId = xhrResponse.detail.response.user.id_retailer;
this._removeMessage();
}
},
_handleError: function (event) {
Polymer.dom(this.root).querySelector("#login-button").disabled = false;
this.errorMessage = [
[this.lang.errors.signin]
];
this.loggedIn = false;
},
_removeMessage: function () {
this.set('errorMessage', '');
},
signup_modal: function () {
Polymer.dom(this.root).querySelector("#modal-signup-view").xhrRetailers();
var modal = Polymer.dom(this.root).querySelector("#modalSignUp");
modal.open();
},
closeModal: function () {
var modal = Polymer.dom(this.root).querySelector("#modalSignUp");
modal.close();
}
});
</script>
</dom-module>
I've tried every way to access that object from modal-imp.html as indicated in the Polymer 1 API and docs.
-The html hierarchy:
login-imp.html -> main-imp.html -> index.html
modal-imp.html -> header-imp.html -> main-imp.html -> index.html
The code inside your login-imp.html file looks fine. You defined the retailerId as a property and have set notify to true. I presume without seeing the other files that you most likely used a wrong binding.
To clarify in your example:
What you will have to do is send the retailerId up to main-imp.html
From there you bind it down to header-imp.html and further to modal-imp.html
Example:
Inside your main-imp.html
<login-imp retailer-id="{{retailerId}}"></login-imp>
Important:
You have to use {{mustaches}} brackets when binding in two ways (in your case up)
The attribute had to be written in lower case so your property name changes to retailer-id
Define retailerId inside your main-imp.html property section
Similar Problems
Maybe a similar question I have answered explaining one & two way data-binding

Variable Assigning from Api to field - ReactJS , Javascript

For examplpe I am fetching the record through Json and in success function am storing the return data in localstorage to use
Output Json like
[{"1":"Core"},{"2":"Moderate"},{"3":"Remote"}]
It's returning as expected
but I can't populate the data in drop down, if i hard coded the same json it's working. Thanks in advance please help me to resolve.
$.ajax({
url: 'http://test.com',
//type: 'POST',
//data :Editorcontent,
success: function (data) {
let fieldes = JSON.parse(data)
localStorage.setItem('one',fieldes)
},
error: function () {
alert(url);
}
});
var selected = localStorage.getItem('one');
//selected = [{"1":"Core"},{"2":"Moderate"},{"3":"Remote"}]
//selected = selected.replace('\'',"'");
console.log(selected);
var editor = {
ajax: '',
ajaxFiles: '',
struct: {
buttons: ['top', 'bottom'] // buttons
},
fields: [
{
label: "Branch Name",
name: "DefaultBranchID",
values: selected,
type: 'select'
},
{
label: "Country:",
name: "CountryID",
type: 'multiselect',
attrs: [
{'pattern': '^[A-Za-z0-9_]+$'}
]
},
"selected" is the variable am assigning
OutPut for Branch Nam Drop down :-O/p

Pass a config-node parameter within HTML-File to another node

I created following input-node:
<script type="text/javascript">
RED.nodes.registerType('Sensor',{
category: 'input',
defaults: {
name: {type:"InputDevice", required:true},
count: {value:"", required:true, validate:RED.validators.number()},
topic: {value:"",validate: RED.validators.regex(/^(#$|(\+|[^+#]*)(\/(\+|[^+#]*))*(\/(\+|#|[^+#]*))?$)/)},
qos: {value: "1"},
broker: {type:"mqtt-broker", required:true},
},
color:"#3FADB5",
inputs:0,
outputs:1,
icon: "feed.png",
label: function() {
//var testu = RED.nodes.getNode(config.name).inputDeviceName;
//return this.name.inputDeviceName;
return this.name||this.topic||"ClientName";
},
labelStyle: function() {
return this.name?"node_label_italic":"";
},
});
And following config node:
<script type="text/javascript">
RED.nodes.registerType('InputDevice',{
category: 'config',
defaults: {
inputDeviceName: {value:"",required:true},
},
label: function() {
return this.inputDeviceName;
}
});
I can not figure out, how to pass over the parameter
inputDeviceName
to my Sensor node within the HTML File. Within the JS File, i am able to get the value of inputDeviceName with:
this.name = RED.nodes.getNode(config.name).inputDeviceName;
How can I name the sensor-node, like in the example above, to appear as 'LDR' in my flow?
You can access the properties of any node for which you know the id in a HTML file with RED.nodes.node(node_id). This will return this nodes default properties.
If you, for example, need some property from a config node, you can get its id from the value of the select HTML-element associated with the config node.

Overriding default parameter names in ExtJS 4 Store

I'm trying to override the default parameter name for limitParam in proxy for the Store. I want to make a JSONP call to http://search.twitter.com/search.json?q=kathmandu&rpp=2 but instead of setting rpp directly I want to map it to limitParam and set it's value. But it's not setting through limitParam. The reason I'm doing is the parameter keys store sends (sort, dir, etc) do not match the parameters on the server side (which I've no control over). Thanks in advance.
Ext.require('Ext.grid.View');
Ext.require('Ext.util.Point');
Ext.application({
name: 'HelloExt',
launch: function() {
/*Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [
{
title: 'Hello Ext',
html : 'Hello! Welcome to Ext JS.'
}
]
});*/
console.log('ok1');
Ext.define('Video', {
extend: 'Ext.data.Model',
fields: ['from_user', 'from_user_id']
});
var myStore2 = Ext.create('Ext.data.Store', {
model: 'Video',
storeId : 'restfulStore',
proxy: {
type: 'jsonp',
url : 'http://search.twitter.com/search.json?q=kathmandu',
reader: {
type: 'json',
//root: 'data.items'
root: 'results'
},
limitParam: 'rpp',
pageParam: 'page'
},
listeners: {
load: function(store, records) {
Ext.each(records, function(rec) {
console.log(rec.get('from_user'));
});
}
},
sorters: [{
property: 'from_user',
direction: 'DESC'
}, {
property: 'from_user_id',
direction: 'ASC'
}],
//autoLoad: true,
remoteSort: true
});
var p = myStore2.getProxy();
p.limitParam = 2;
myStore2.load();
console.log('loads anyway??? loaded the store ...');
Ext.create('Ext.grid.Panel', {
title: 'Restful Grid',
store: Ext.data.StoreManager.lookup('restfulStore'),
columns: [
{header: "From User", width: 200, sortable: true, dataIndex: 'from_user'},
{header: "From User ID", width: 200, sortable: true, dataIndex: 'from_user_id'}
],
height: 400,
width: 400,
renderTo: Ext.getBody()
});
console.log('store loaded!!');
}
});
Your proxy configuration is fine for what you want to do. The problem is in the way you load the store. You should not change limitParam which is really the config option for the name of the param. To affect the number of results, use the limit option of the load method, that you can also configure in the store with the pageSize option.
So, remove this:
var p = myStore2.getProxy();
p.limitParam = 2;
And instead, use the limit option when loading the store:
myStore2.load({
limit: 2
});
Alternatively, you can set this in the store config with the pageSize option:
Ext.create('Ext.data.Store', {
// ...
pageSize: 2
,autoLoad: true
});
You can mix both by setting a default with pageSize, and changing it at loading time with limit.
As a side note, the tweeter API doesn't seem to support sorting, so your sorters configuration won't have any effect on the returned results. You should switch remoteSort to false to have the returned results sorted on the client side according to your configuration.

sencha-touch application not working

i am not able to figure out the problem in the following sencha-touch code i have written.
it shows no errors but still when i run it, it doesn't work. are there any more files or classes that the application requires? i am running it on chrome using a linux machine.
var App = new Ext.application({
requires: [
'Ext.tab.Panel' ,'Ext.List', 'Ext.data.Store', 'Ext.data.Model'
],
name : 'notesapp',
useLoadMask : true,
launch : function () {
Ext.regModel('note',{
idProperty:'id',
fields:[{name :'id', type:'int'},
{name : 'date', type: 'date', dateFormat:'c'},
{name : 'title', type: 'string'},
{name : 'narrative' , type:'string'}],
validations:[{type: 'presence', field: 'id'},
{type: 'presence', field: 'title'} ]
});
Ext.regStore('notestore', {
model:'note',
sorters:[{
property:'date',
direction:'DESC'
}],
proxy:[{
type:'localstorage',
id:'notes-app-local-store'
}],
data: [
{ id: 1, date: new Date(), title: 'Test Note', narrative: 'This is simply a test note' }
]
}
);
var notelist= new Ext.List({
id:'notelist',
store:'notestore',
itemTpl:
'<div class= "list-item-title">{title}</div>'
+ '<div class="list-item-narrative">{narrative}</div>'
});
var noteslisttoolbar = new Ext.Toolbar({
id:'noteslisttoolbar',
title:'MyNotes'
});
var noteslistcontainer= new Ext.Panel({
id:'noteslistcontainer',
layout:'fit',
dockedItems:[noteslisttoolbar],
items:[notelist]
});
this.viewport = new Ext.Panel({
fullscreen: true,
layout:'card',
cardAnimation:'slide',
items:[noteslistcontainer]
});
}
})
your getting an error at
proxy:[{
type:'localstorage',
id:'notes-app-local-store'
}],
please check there..
with out that code sencha app running fine
see http://www.senchafiddle.com/#j2f0i