Monday, September 15, 2008

Re: How do I turn data with belongs to into a json array

Just do a $this->set('myData', $pcnA) in the controller, and in the
view write:

<?php echo $javascript->block('var myData = ' . $javascript-
>object($pcnA)); ?>

Now in your view javascript you can access the data normally:

(Not that I'd "normally" generate a table like this, but it's just an
example)

<script type="text/javascript">
document.write('<table>');
document.write('<tr><th colspan="2">Pcn</th><th colspan="2">Account</
th></tr>');
document.write('<tr><th>Id</th><th>Name</th><th>Id</th><th>Name</th></
tr>');
for (var i=0; i<myData.length; i++) {
document.write('<tr>');
document.write('<td>' + myData[i].Pcn.id + '</td>');
document.write('<td>' + myData[i].Pcn.name + '</td>');
document.write('<td>' + myData[i].Account.id + '</td>');
document.write('<td>' + myData[i].Account.name + '</td>');
document.write('</tr>');
}
document.write('</table>');
</script>

hth
grigri

On Sep 14, 1:46 pm, Zac Tolley <ztol...@me.com> wrote:
> I have a simple application that gets data (from a model called pcn) ,  
> turns it into a json array and gets used to build a data table on the  
> browser. This is easy and uses
>
> // Get Data
> pcnA = $this->Pcn->findAll(null,'*','Pcn.name ASC');
>
> //convert $pncA into a json-friendly format
> $pcnArray = Set::extract($pcnA, '{n}.Pcn');
>
> This turns
>
> Array
> (
>      [0] => Array
>          (
>              [Pcn] => Array
>                  (
>                      [id] => d48ff921-141e-2ecb-244e-47d2da2e209a
>                      [name] => fred
>                  )
>
>              [Account] => Array
>                  (
>                      [id] => 76ab009a-ca15-2ff8-e2a8-47d2be5c4be9
>                      [name] => Freds Icecreams
>                  )
>          )
>
> Into:
>
> [{"id":"d48ff921-141e-2ecb-244e-47d2da2e209a","name":"fred"}
>
> But I want to take it a stage further and also bring in the 2 fields  
> from the account that is associated with the Pcn.
>
> I'm sure this is a common question, but I've not found an example  
> anywhere. Whats the best way to return related data in the form of a  
> json response that I can somehow handle when I'm generating my table,  
> and then there's the follow up question about how they both have a  
> field named name... :)
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

No comments: