MODX Community

List all parents or childs RESTFUL API

Hi,

How view parents or childs in restful/api?

<? class MyControllerItems extends modRestController {
    public $classKey = 'modResource';
    public $defaultSortField = 'id';
    public $defaultSortDirection = 'ASC';
} ?>

What will the input look like?

Do you want a single parent or multiple parents?

A call to getChildIds should get you the Ids of the children.

Hi, @bobray

Single parent, some practical example?

What information are you starting with related to the resource you want the parent of (resource object, pagetitle, id, etc.)?

And what information do you want to send about the parent?

looking into the pdoTools - Extra could give you good ideas.

The id of the parent resource should already be available in the response of your rest-controller by default.
To add the ids of the child-resources you have to override the functions prepareListObject() respectively afterRead().

You can also override the function prepareListQueryBeforeCount(). This allows you for example to call the route .../rest/items/?parent=1 with a parent-parameter and get back a list of the child-resources.

<?php 
class MyControllerItems extends modRestController {
    public $classKey = 'modResource';
    public $defaultSortField = 'id';
    public $defaultSortDirection = 'ASC';
	
	public function prepareListObject(xPDOObject $object){
    	$objectArray = $object->toArray();
		$children_ids = $this->modx->getChildIds($objectArray['id'],1);
		$objectArray['children'] = $children_ids;
    	return $objectArray;
    }
	
	public function afterRead(array &$objectArray) {
		$children_ids = $this->modx->getChildIds($objectArray['id'],1);
		$objectArray['children'] = $children_ids;
        return !$this->hasErrors();
    }

	protected function prepareListQueryBeforeCount(xPDOQuery $c) {
		if ($id_parent = (int)$this->getProperty('parent')) {
			$c->where(['parent' => $id_parent]);
		}
        return $c;
    }	
}
?>
1 Like

Hi, @bobray

See sample
https://c1102.paas1.tx.modxcloud.com/rest-json

1 Like

What would you like to return about the parent?

If it’s just the ID, you already have that in the resource’s parent field.
If you want other fields from the parent, you’d have to get the parent object with the following code and extract them with something like this:

$parent = $this-modx->getObject('modResource', $resource->get('parent');

$parentPageTitle = $parent->get('pagetitle');
1 Like