PDA

View Full Version : Setting model string field to null



dedoz
28 Jan 2012, 6:20 PM
Im trying to set to null a string field in a model, so when i do record.save() it sends a null on that field and the server knows that field hasnt been set. (it allow nulls btw)

if we dont do anything, the server will send a empty string "", like with numbers, if we dont set anything the default value is 0 wich is weird, should be like "undefined" or null.

So i came with this code and a weird solution.


Ext.onReady(function() {
Ext.define('Person', {
extend: 'Ext.data.Model',
fields: [
{name:'id' ,type:'int'},
{name:'int1' ,type:'int'},
{name:'int2' ,type:'int', useNull:true},
{name:'string1' ,type:'string' },
{name:'string2' ,type:'string', useNull:true},
{name:'string3' ,type:'string', defaultValue:null},
{name:'string4' ,type:'string', defaultValue:'null'},

],
});

var myPerson = Ext.create('Person');
console.log(myPerson.get('int1')); // 0
console.log(myPerson.get('int2')); // null (javascript null)
console.log(myPerson.get('string1')); // "" (empty string)
console.log(myPerson.get('string2')); // "" (empty string)
console.log(myPerson.get('string3')); // "" (empty string)
console.log(myPerson.get('string4')); // "null" (a string)


var myPerson = Ext.create('Person',{
string1 : null,
string2 : null,
string3: null,
string4: null,
});

console.log("second person");
console.log(myPerson.get('string1')); // "" (empty string)
console.log(myPerson.get('string2')); // null (javascript null)
console.log(myPerson.get('string3')); // "" (empty string)
console.log(myPerson.get('string4')); // "null" (a string)
});


so i guess the solution is to set every string that allows nulls like this


Ext.define('Person', {
extend: 'Ext.data.Model',
fields: [
{name:'id' ,type:'int'},
{name:'string1' ,type:'string' useNull:true},
{name:'string2' ,type:'string', useNull:true},
{name:'string3' ,type:'string', useNull:true},
{name:'string4' ,type:'string', useNull:true},

],
});

var myPerson = Ext.create('Person',{
string1 : null,
string2 : null,
string3: null,
string4: null,
});

this will generate json (to send to server) with string field that arent set, with a real null value. note that useNull is not to use with strings, but it works at least, is way to do it

useNull docs :
"Use when converting received data into a Number type (either int or float). If the value cannot be parsed, null will be used if useNull is true, otherwise the value will be 0. Defaults to false."

is this the right way to initiliaze a string field with a null value ? think if a model has 10 strings, shouldnt be a default option of this so wouldnt be necesary to set all string to null when creating a instance of that model ? or im missing something from docs

(sorry for my bad english)

rupamkhaitan
11 Apr 2013, 4:19 AM
I dont know if its the right way of doing, but it helped me set a defaultValue to one of my property which will always go same to backend