I am trying to read a field collection and build an array in PHP.
The array I want to build goes like this:(it's in JS notation but you can easily imagine the equivalent in PHP)
highlights = [
{highlightTitle:A sample test title,
highlightImage: a sample img url,
highlightBody: a sample text body},
{highlightTitle:A sample test title,
highlightImage: a sample img url,
highlightBody: a sample text body}
]
As you can see it is just an array with objects inside, where each object represents a field collection entry. That field collection entry has 3 fields obviously, highlightTitle
,highlightImage
& highlightBody
.
Now I want to read that field collection and build the array I described above.
The thing I care about is best practises. What is the best possible way to do this?
Currently I use the following code dumped in <?php ?>
brackets on the top of my layout's tpl files:
(I use Omega 4, and I have different layouts for different content types)
This is the code I use now:
$highlightsArr; //this is the result array
$highlightsCounter = 0;
$highlights = field_get_items('node', $node, 'field_highlights');
foreach ($highlights as $item) {
$fc = field_collection_field_get_entity($item);
$highlightSnippet = $fc->field_highlight_snippet["und"][0]["value"];
$arr = $fc->field_highlight_snippet["und"][$i]["value"];
$innerArray = entity_load('field_collection_item', array($arr));
$innerCounter = 0;
foreach ($innerArray as $item) {
$highlightsArr[$innerCounter]["sectionItemTitle"] = $item->field_highlights_title["und"][0]["value"];
$highlightsArr[$innerCounter]["highlightsImage"] = file_create_url($item->field_highlights_image["und"][0]["uri"]);
$highlightsArr[$innerCounter]["sectionItemPrice"] = $item->field_highlights_body["und"][0]["value"];
$innerCounter++;
}
}
The issue with the above code:
The code above returns undefined variables/indexes on things that are obviously defined. When I first create a content type and want to view it's node, it returns errors. But as soon as I refresh the page the errors go away which seems rather strange to me.
In any case I would like to know best practises for doing this kind of stuff. Unfortunately I come from a strictly JS background (I'm a front-end dev), so Drupal and PHP is something new for me.
Many thanks in advance.