CCK Fields Data in Titanium javascript

We encourage users to post events happening in the community to the community events group on https://www.drupal.org.
sumitk's picture

This is from Gregg's email .... I am moving here so it could be helpful for everyone

When I want to post info from a CCK text field called "field_origin" the services output looks like this

[field_origin] => Array
                 (
                     [0] => Array
                         (
                             [value] => Edmonton, Alberta, Canada
                         )

                 )

And when I use this Titanium code I get the full output of the array including brackets and the [value] text

var label2 = Ti.UI.createLabel({
text: data[c]['field_origin'],
color: '#420404',
});

How would I scope this javascript call to just a specific value of "value" within the array?

Similarly when I try and access this taxonomy field through services

[taxonomy] => Array (
                           [19] => stdClass Object (
                                            [tid] => 19
                                            [vid] => 2 
                                            [name] => Comedy 
                                            [description] => 
                                            [weight] => 0 )
                       )

using this code

var label2 = Ti.UI.createLabel({
text: data[c]['taxonomy'],
color: '#420404',
});

The output I receive is the contents of the array and not just the "name" field which is what I am looking for.

How would I scope this javascript call to just a specific value "name" within the array?

Comments

Gregg, Here to get name out

sumitk's picture

Gregg,

Here to get name out of taxonomy you can do-

var taxonomy_arr = data[c]['taxonomy'];
var taxonomy_name = taxonomy_arr[19].name;

Hope it will help!

Thanks

iaminawe's picture

Hi Sumit

Thank you very much, makes sense that it is here rather than hidden in an e-mail.

I appreciate the assistance and see on the Titanium forums that a few other people were struggling with this same issue.

I found the easiest way to extract the correct value from the first array (the cck origin_field) one was to use the following code

text: data[c]['field_origin'][0]['value'],

As most of my cck fields are simple text fields with only one value, using the [0] always references the correct value.

Thanks for the info about the taxonomy arrays but I don't understand how you would do it for a table view of values without hardcoding the [19] part
So for example lets say Label 1 is the node title (show name) and Label 2 is the taxonomy name assigned to that node (comedy)

In each row I want the title and taxonomy term, when the row is tapped it loads in the full show details.
How would I use the above code so that it displays the correct taxonomy name for each row rather than showing "comedy" for them all?

Thanks for any help with this

Gregg, I am not very sure as

sumitk's picture

Gregg,

I am not very sure as I never played with taxonomies in titanium apps .. but if it is an incremented field like 0,1,2,3 .... 19 for all taxonomy fields .. you can use a loop and refer values as data[c]['field_origin'][c+1]['value']

This will look as

for (var c=0; c<data[c]['field_origin'].lenght; c++) {
  var data = [];
  data = [ blah operations .... useing data[c]['field_origin'][c+1]['value'] as value ]
}

I think you can make the rest from above reference.

Or use fields :)

iaminawe's picture

I just made an awesome discovery for displaying both taxonomy term names and cck fields that are easy to access with Titanium

If the view being called by services is using "Row Style:Node" to display the records it puts the cck fields and taxonomy items into arrays.
If the view being called by services is using "Row Style: Fields" to display the records then it outputs [node_data_field_companyname_field_origin_value] => Edmonton, Alberta, Canada for the CCK text field and [term_data_name] => Comedy for the taxonomy.

Problem solved
Thanks Sumit

:) awesome!

sumitk's picture

:) awesome!

node.save sample code in Titanium

newnewuser's picture

I'm a novice here. I am able to do views.get service call (following Sumit's code sample). But, I unsuccessfully do "node.save" service call. Can you help provide some sample codes on how to go about creating a node content.

As I don't understand how each function really works, my attempt was purely change from views.get to node.save as follow:

// Test drupal node.save

var nodesave = new Object;
nodesave.method = 'node.save';
nodesave.node = '{"type":"song","title":"song name","field_artist_reference":"john"}'; // field_artist_reference is a node reference

var xhr = Titanium.Network.createHTTPClient();
xhr.open("POST",url);
Ti.API.info(nodesave);
xhr.send({data: JSON.stringify(nodesave)});
Ti.API.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
Ti.API.info(data);

This doesn't work and the console debug doesn't say anything that I can understand:

W/TiAnalyticsSvc( 324): (Thread-11) [52,52] Analytics Service Started
W/TiTabActivity( 324): (main) [112,164] Notifying TiTabGroup, activity is created
D/TiFastDev( 324): (main) [85,249] sent tokens successfully
D/skia ( 324): --- decoder->decode returned false
I/global ( 324): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
D/dalvikvm( 324): GC_FOR_MALLOC freed 3257 objects / 255456 bytes in 129ms
D/TiFastDev( 324): (kroll$2: app://demo.js) [369,618] sent tokens successfully
D/KrollContext( 324): (kroll$2: app://demo.js) [1,619] Running evaluated script: app://demo.js
D/TiHttpClient( 324): (kroll$2: app://demo.js) [140,759] Setting ready state to 1
I/TiAPI ( 324): (kroll$2: app://demo.js) [3,762] {"method":"node.save","node":"{\"type\":\"song\",\"title\":\"song name\",\"field_artist_reference\":\"john\"}"}
I/TiAPI ( 324): (kroll$2: app://demo.js) [8,770] ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I/TiAPI ( 324): (kroll$2: app://demo.js) [1,771] [Ljava.lang.Object;@4501e938
D/TiHttpClient( 324): (kroll$2: app://demo.js) [3,774] Setting ready state to 1
D/TiFastDev( 324): (main) [15,789] sent tokens successfully
D/skia ( 324): --- decoder->decode returned false
D/TiFastDev( 324): (main) [323,1112] sent tokens successfully
D/skia ( 324): --- decoder->decode returned false

Thanks in advance for your help!!!!

Here's a sample code that

ishanmahajan's picture

Here's a sample code that should work:

var saveReq = Titanium.Network.createHTTPClient();
var params = new Object;
params.method = 'node.save';
var song_obj = new Object;
song_obj.title = "song name";
song_obj.body = "song body";
song_obj.type = 'song';
song_obj.uid = uid;
song_obj.field_cckfield = [{ "value": 'field value' }];
// node reference field
song_obj.field_artist_reference = [{ "nid": nid }];
params.node = JSON.stringify(song_obj);
saveReq.open("POST",url);
saveReq.setRequestHeader("Connection", "close");
saveReq.send({
data: JSON.stringify(params)
});
saveReq.onload = function() {
Ti.API.info('saved song: ' + this.responseText);
};

Regards,
Ishan

node reference field arguments

newnewuser's picture

Hi Ishan,

One more thing to bother. What's the format for the node reference field if I don't have nid. I'm using "noderefcreate" module to create new reference node. So, at the point of making a JSON call, I don't have the nid of the reference node. If I only input:

// node reference field
song_obj.field_artist_reference = "artist name";

For some reasons, node type artist is created with a title "a" not "artist name". This weird behavior occurs when initiate json call from both on service browser and Titanium.

Any idea? I think it's a services module problem, as I tried many modules that are used for creating reference nodes (node_widget, autocreate, nodereference_autocreate).

Highly appreciate if you could give some pointers of how to fix the problem.

THanks in advance!!!!

Note: I have tried with no success to put in different variations of reference argument:

If I pass an array like:

song_obj.field_reference_artist = [{ "title": "TI artist name" }];

I got an error:
Cannot use object of type stdClass as array in ../modules/cck/modules/nodereference/nodereference.module on line 580

If I stringify reference field object like:

var ref_obj = new Object;
ref_obj.title = "zzz artist";
song_obj.field_reference_artist = JSON.stringify(ref_obj);

Not surprising, the new artist reference node is created with a title "{" which is the first letter in the JSON stringify text.

node.save sample

newnewuser's picture

Hi Ishan,
Thanks so much for your prompt response.

I tried the code and got this error message:

I/TiAPI ( 570): (kroll$2: app://demo.js) [4,6617] saved song: {"#error":true,"#message":"Access denied"}

I tried echo the params and got this:

I/TiAPI ( 599): (kroll$2: app://demo.js) [146,754] {"method":"node.save","node":"{\"uid\":\"1\",\"type\":\"song\",\"body\":\"song body\",\"title\":\"song name\"}"}

On drupal site, I set create/edit/view/delete permissions on content/node 'song' for all user types. Testing on browser works fine (default to anonymous user). However, I tried passing param on services browswer interface with the "\" trailing as above and also got error "Missing required arguments: node". But I guess it's not relevant. On services browsers, "Access denied" message occured when I don't set format to 'JSON').

Thanks again in advance,
-newnew

Note: I comment song_obj.field_reference_artist out for the time being (as I want to pass only a title name in, not a nid. I'm using node reference create to auto generate the node if the artist node doesn't exist yet. It would be great if you could help point out as well, how to pass only a title text of the reference node.

Are you using any

ishanmahajan's picture

Are you using any authentication module? You can see the settings at admin/build/services/settings.
If not then the above code should work. Ah, I missed a field:
song_obj.name = username;
Try after adding this line.

Not yet working

newnewuser's picture

Hi ishanmahajan,

Thanks for further suggestion, but unfortunately it still doesn't work.
saved song: {"#error":true,"#message":"Access denied"}

I don't use authentication.
I put song_obj.name = "admin";

I tried other combinations e.g.

var usr_song_obj = new Object;
usr_song_obj.uid = 1;
usr_song_obj.name = "admin";
usr_song_obj.pass = "password";
song_obj.user = JSON.stringify(usr_song_obj);

I put a script on user.login prior to this set of code. The login returns login details (so I guess it works - yet the user list on admin menu doesn't record the user login). But, yet the node.save code still doesn't.

// test user.login

var usrLogin = Titanium.Network.createHTTPClient();
var loginParams = new Object;
loginParams.method = 'user.login';
loginParams.username = 'admin';
loginParams.password = 'password';

usrLogin.open("POST",url);
usrLogin.setRequestHeader("Connection", "Close");
usrLogin.send({
  data: JSON.stringify(loginParams)
});

usrLogin.onload = function() {
  Ti.API.info(data);
  Ti.API.info('login: ' + this.responseText);
};


// test drupal node.save

var saveReq = Titanium.Network.createHTTPClient();
var params = new Object;
params.method = 'node.save';
var song_obj = new Object;
song_obj.title = "song name";
song_obj.body = "song body";
song_obj.type = 'song';
song_obj.uid = 1;
song_obj.name = "admin";

params.node = JSON.stringify(song_obj);
Ti.API.info(params);

saveReq.open("POST",url);
saveReq.setRequestHeader("Connection", "Close");
saveReq.send({
  data: JSON.stringify(params)
});
saveReq.onload = function() {
  Ti.API.info('saved song: ' + this.responseText);
};

On versions:

drupal 6.22 +
ctool: 6.x-1.x-dev +
services 6.x-2.x-dev
json_server 6.x-2.0-alpha1 (Sumit's modified version http://civicactions.com/blog/2010/may/02/tutorial_code_developing_apps_i...)

I tried all other versions of json_server available on the project page. All give error "Invalid Arguments".

I have exhausted my imagination. Please please help me !!

Json_server problem

newnewuser's picture

I found the problem. It's jason_server alpha1 problem. I changed to alpha2, applied patches and add Sumit's two liners and now node.save works.

Titanium API

Group organizers

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds: