Skip to content

Instantly share code, notes, and snippets.

@brandonkelly
Created January 28, 2014 17:26
Show Gist options
  • Select an option

  • Save brandonkelly/8672116 to your computer and use it in GitHub Desktop.

Select an option

Save brandonkelly/8672116 to your computer and use it in GitHub Desktop.

Revisions

  1. brandonkelly created this gist Jan 28, 2014.
    59 changes: 59 additions & 0 deletions gistfile1.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    <?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);
    }