Accessing navItems from the tools folder in an AJAX call.

Permalink
Greetings fellow programmers,
I'm stuck in a chicken/egg situation. Ultimately, my goal is to make a navigation menu, using jsTree. The menu needs to be populated by an AJAX call.

If my AJAX calls a single page, concrete adds a template to the page and also loads several classes, I only want the raw data.

If you have a page in the tools folder, you're free to do what you want. The problem is, when I try to generate my JSON object with nav items, I get an error message. I suspect that the classes used to access the nav items aren't loaded.

I tried to access the nav items like so:

$navController = BlockType::getByHandle('autonav')->getController();
$navItems = $navController->getNavItems();


I get this message: Fatal error: Call to a member function getCollectionID() on a non-object.

Is there a way I can access the nav objects from the tools folder? Thanks!

slafleche
 
JohntheFish replied on at Permalink Reply
JohntheFish
In a tools file, there is no collection (page) object. You need to create it in the context within which you want to work.
slafleche replied on at Permalink Reply
slafleche
How do I do that?
slafleche replied on at Permalink Reply
slafleche
Do you have an example of this? I'm not sure how to do this...
slafleche replied on at Permalink Reply
slafleche
Well, I solved my problem. I'll share the answer in case anybody else has this problem.

So, the trick is, you make a single_page, but also a controller for it. You put your JSON data in the controller.

To get access to the nav items, I ended up hard coding an Autonav block, but without rendering it at the end. I had access to the controller through that.

Thanks JohntheFish for taking the time to reply.
slafleche replied on at Permalink Best Answer Reply
slafleche
I got a PM asking for more clarification, so i'll share it here instead.

Create a single_page as you normally would. Then in your active theme folder (themes/yourActiveTheme), create a php file with an identical name as the one you have in your single_page folder. The php file in the single page is left blank. When that page is requested, the controller for it will be called instead (the one in the theme folder). I'm not sure why it doesn't work with the single page, but this worked for me.

In the controller (the php page in your theme folder), I needed to get my hands on the actual nav data. Hard code an autonav block, but don't render it. (really good documentation on hard coding autonav:
c5blog.jordanlev.com/blog/2012/04/hard-coded-autonav-options/)

Example:
$siteNav= BlockType::getByHandle('autonav');
$siteNav->controller->displayPages = 'top';
$siteNav->controller->orderBy = 'display_asc';
$siteNav->controller->displaySubPages = 'all';
$siteNav->controller->displaySubPageLevels = 'all';
$navItems = $siteNav->getController()->getNavItems();


You're now free to echo a json_encode!