General developer forum

External function returning an array with undefined levels and undefined fields.

 
Picture of Lawrence Lagerlof
External function returning an array with undefined levels and undefined fields.
 

Hi devs.

I created some external functions for my webservice, and everything is working fine, but I found a problem I couldn't solve. Maybe the Moodle Dev community could help me.


The problem:

This new external function I am writing returns a external_multiple_structure, but with different fieldnames for each "record". Added to this, it's an array with multiple dimensions and undefined levels (a tree structure).

So I can't define the fields in the external_single_structure for each node of my array because they vary.


This is a fine example of my structure:



Array
(
[0] => Array
(
[id] => 7
[name] => Test name
[type] => 50
)

[1] => Array
(
[id] => 3
[data] => just an example
[children] => Array
(
[0] => Array
(
[id] => 16
[data] => More one item
[children] => Array
(
[0] => Array
(
[id] => 4
[name] => 2
[type] => 50
)

[1] => Array
(
[id] => 5
[data] => last node example
[children] => Array ... any node with 'children' can have more children, indefinitely.
...


Just to elaborate the problem I am facing, I can't do:


return new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_INT, 'ID'),
'name' => new external_value(PARAM_RAW, 'ID_ITEM'),
'type' => new external_value(PARAM_INT, 'PARENTID'),
...
)
)
);


Because the next item of my example (index 1) has other fields.


Just to be clear, I know how to return a multiple structure tree with fixed fields and fixed levels, but with different fields for each "record" and undefined levels, I don't know.

So, obviously, I can't return this structure normally, but maybe Moodle provides some way to return this type of data?

Thank you.




 
Average of ratings: -
Picture of Lawrence Lagerlof
Re: External function returning an array with undefined levels and undefined fields.
 

I found a workaround solution myself. I will left this here in case someone had had the same problem:

If you need to make a webservice function that returns and array with multiple, undefined levels:

In my webservice plugin at the main method public static function get_tree($rootid), after I build my tree, I don't return it, I simply print it:

header('Content-Type: application/json');
die(json_encode($my_tree));


And in my method public static function get_tree_returns(), I just return null.

It works like a charm, however be aware of this small issues:

  • The Moodle webservice documentation relies on the existence of the _returns() method. Returning null causes the method entry in documentation not show the returning values.
  • The moodlewsrestformat is ignored for this method. The returning format will be always json in this case.


 
Average of ratings: -