Jump to content

Iterate over Repeater and output it via JSON


sins7ven
 Share

Recommended Posts

Hi community,

I am trying to build a way to create some JSON output for some pages. For this I created a template called json.php. This one has URL segments enabled and based on this it gives me some page data. I mostly use this for getting some JSON into my JS libraries (like Vue.js) to build some interactive filters. 

So for example www.domain.com/json/referenzen should give me all data from the clients child pages (usually logo references). This works totally fine. 

But for one special case (getting management child pages) I have a repeater item on each page and I am not sure how to get this repeater item into my JSON data. My code looks as follows: 

<?php namespace ProcessWire;

if (!$input->urlSegment1) {
    $session->redirect($pages->get('/')->url);
}

$data = array();

switch ($input->urlSegment1) {
	case "referenzen":
		$p = $pages->get("name=referenzen");
		foreach ($p->logo_select as $logo) {
			$data[] = array(
				"name" => $logo->title,
				"url" => $logo->image->url,
				"category" => $logo->business_category->value
			);
		}
		break;
	case "management":
		$p = $pages->get("name=management")->children;
		
		foreach ($p as $m) {
			$data[] = array(
				"name" => $m->title,
				"venture" => $m->venture_select->title,
				"image"	=> array(
					"url" => $m->image->url,
					"description" => $m->image->description
				),
				"position" => $m->team_details->position,
				"email" => $m->team_details->email,
				"phone" => $m->team_details->phone,
				"socials" => $m->socials // This is the repeater item which has links to social networks
				),
			);

		};
		break;
}

header("Content-type: application/json");
echo wireEncodeJSON($data);
return $this->halt();
?>

I know there are some modules like Pages2JSON or PageQueryBoss but I thought I could solve this without extra need of a module. Would be nice if someone could point me into the right direction. Thanks!

Link to comment
Share on other sites

You can use WireArray's explode method to get the required property(s) from your repeater.

	"socials" => $m->socials->explode(['title', 'url'])

Pass it a function instead of a property name or names to add fancier processing:

	"socials" => $m->socials->explode(function($item, $key) {
		return [
			"name"	=>	$item->title,
			"link"	=>	$item->url
		];
	})

 

  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...