TV values from children

I am trying to get 2 different TV values from the children of a resource. I have the the children id’s in an array, but when i try to loop through them the page gives a 500 error.

$locations = $modx->getChildIds(28, 1, array('context' => 'web'))

$distance_array = array();

foreach($locations as $value) {
    $location_resource = $modx->getObject('modResource', $value);
    $lat = $location_resource->getTVValue('latitude');
    $long = $location_resource->getTVValue('longitude');
    array_push($distance_array, array($lat, $long));
}

Is there a better way if doing this? do i have to use a query?

Thanks in advance.

1 Like

I think the problem is with the third argument, which you shouldn’t need unless there is a resource 28 in more than one context.

However . . . it would be much more efficient to get all the resources in a single query rather than making a call to getChildIds() and then a separate call to get object() (query) for each resource. Using getChildIds() is seldom a good idea unless you need depth beyond the immediate children.

$docs = $modx->getObject('modResource', array('parent' => 28));

foreach ($docs as $location_resource) {
    $lat = $location_resource->getTVValue('latitude');
    $long = $location_resource->getTVValue('longitude');
    array_push($distance_array, array($lat, $long));
}

If you need to specify the context you can do this:

$docs = $modx->getObject(‘modResource’, array(‘parent’ => 28, ‘context_key’ => ‘web’));

1 Like

that gives me this error

Fatal error: Uncaught Error: Call to a member function getTVValue() on string 
1 Like

Sorry, that should be:

$docs = $modx->getCollection('modResource', array('parent' => 28));
2 Likes

Thanks @bobray, that works famously

2 Likes

I’m glad it worked. :slight_smile:

2 Likes