Skip to content

Instantly share code, notes, and snippets.

@brandonkelly
Created January 28, 2014 17:26
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save brandonkelly/8672116 to your computer and use it in GitHub Desktop.
Save brandonkelly/8672116 to your computer and use it in GitHub Desktop.
A function for converting an entry in Craft to JSON
<?php
public function getEntryJson(EntryModel $entry)
{
$entryData = array();
foreach ($entry->getType()->getFieldLayout()->getFields() as $field)
{
$field = $field->getField();
$handle = $field->handle;
$value = $entry->$handle;
if ($field instanceof BaseElementFieldType)
{
$entryData[$handle] = array();
foreach ($value as $relElement)
{
$entryData[$handle][] = array(
'id' => $relElement->id,
'label' => (string) $relElement
);
}
}
else if ($field instanceof MatrixFieldType)
{
$entryData[$handle] = array();
foreach ($value as $block)
{
$entryData[$handle][] = array(
// ...
);
}
}
else
{
// Deal with Checkboxes and Multi-select fields
if ($value instanceof \ArrayObject)
{
$value = array_merge($value);
}
if (is_array($value))
{
$entryData[$handle] = $value;
}
else
{
// Let's just force anything else to a string, in case it's something like a SingleOptionFieldData class
$entryData[$handle] = (string) $value;
}
$entryData[$handle] = $value;
}
}
return JsonHelper::encode($entryData);
}
@keithmancuso
Copy link

Started to play with this for a plugin and running into a couple issues.

if ($field instanceof CategoryFieldType) {

doesnt seem to catch any fields, but it does work if i used

if ( $field['type'] == 'Categories') {

for categories specifically im trying to get all teh fields on the category and not having much luck, is there a getFieldLayout() method for categories?

this doesnt seem to work
foreach ($category->getFieldLayout()->getFields() as $subField) {

@keithmancuso
Copy link

Scratch that was able to make some more progress and getting custom fields nicely on related elements regardless of type.

Still going through other field types but making progress on a plugin here

https://github.com/familiar-studio/craft-json-expand

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment