XF 2.2 Returning results in new API endpoint

Orit

Active member
Hello,
I've added a new API endpoint to an addon we use (Snogs Advanced forms).
It seems to fetch the items (forms) but the api result returns an array of objects sorted alphabetically.
The code for returning the data is:
PHP:
return $this->apiResult([
    'forms' => $forms->toApiResults(),
    'pagination' => $this->getPaginationData($forms, $page, $perPage, $total)
]);


The JSON example:

JSON:
{
    "posid": 1,
    "z_connectedThread": 0,
    "z_description": "testing form",
    "z_email": "email@example.com",
    "z_node_id": 123
}

Is there a way to re-order the results differently?
for some reason the posid column is returned by default. The other columns were called by the
setupApiResultData function in the entity.

I currently renamed them with a z_ prefix but hope for a better way...

Thanks!!
 
JSON objects are inheritently unordered (granted most implementations will iterate over them in the defined order), and sorting keys consistently can be a good idea for downstream purposes (cacheability, etc). Not to mention the order wouldn't be too reliable if they were not sorted since add-ons can introduce their own keys at different points anyway. You can always define an array of keys and iterate over that to consume them in a specific order:

JavaScript:
const keys = ['z', 'a', 'c'];
for (const key of keys) {
    console.log(someEntity[key]);
}

If it's absolutely critical to customize the response sorting, you might be able subclass \XF\Api\Result\EntityResult with your own render method and return an instance of that from the entity's setupApiResultData method.
 
Last edited:
If it's absolutely critical to customize the response sorting, you might be able subclass \XF\Api\Result\EntityResult with your own render method and return an instance of that from the entity's setupApiResultData method.
Thank you!
It's not critical, but would be a nice thing to play with ;)
Once I figure out why one of the controller classes does not get called...
 
Back
Top Bottom