Reputation: 1017
Using the php SDK, I would like to get all the content for a landing page, this will include sections with different content types / components with different fields per entry.
eg.
Section 1 - hero
Section 2 - article
Section 3 - image
Q. How do I loop through and get the linked section content.
If an entry contains a link to an asset or another entry, the SDK will automatically load it.
I am struggling to understand the documentation. How exactly do I break into these values?
<?php
$query = new \Contentful\Delivery\Query();
$query->setContentType('page_landing')
->where("fields.urlHandle[match]", $slug);
$products = $client->getEntries($query);
foreach ($products as $product) {
echo $product['name'];
// Example of what I am trying to achieve
if($product['sections']['id']=='hero'){
$title= $product['sections']['hero']['title'];
}
if($product['sections']['id']=='article'){
$text = $product['sections']['article']['text'];
}
}
?>
Upvotes: 2
Views: 322
Reputation: 1017
I would love to know if there is a better way, the documentation does not have many examples. Below is where I ended up but feel there must be a simpler way.
<?php
require_once 'vendor/autoload.php';
require_once 'vendor/credentials.php';
// if we need to use rich text
$renderer = new \Contentful\RichText\Renderer();
// Get the section entry id's
foreach ($products as $product) {
$dataJson = json_encode($product);
$revertJson[] = json_decode($dataJson, true);
foreach ($revertJson as $Json) {
foreach ($Json['fields']['sections'] as $entries) {
$entryID[] = $entries['sys']['id'];
}
}
}
// Loop out the sections
foreach ($entryID as $entry) {
// Get individual linked entries
$entry = $client->getEntry($entry);
$type = $entry->getSystemProperties()->getcontentType();
$json = json_encode($type);
$comp = json_decode($json, true);
if ($comp['sys']['id'] == 'Hero') {
// field
echo $entry['urlHandle'];
// rich text
echo $renderer->render($entry['text']);
// asset
$asset = $client->getAsset($entry['imageId']);
echo $asset->getFile()->getUrl();
} elseif ($comp['sys']['id'] == 'Landmark') {
echo $entry['title'];
}
}
Upvotes: 0