2

I've written a custom plugin that stores data as JSON in a TEXT column (field_gridcontrol) in Craft's content table that looks something like this:

[
  {
    "id": "35", // id is an element's id
    "classes": "item w1 h2", // classes to add to the dom element
    "x": 0 // x coordinate on where it shows up in a grid
  },
  {
    "id": "56",
    "classes": "item w2 h2",
    "x": 0.25
  },
  {
    "id": "24",
    "classes": "item w1 h1",
    "x": 0.75
  }
]

I can print this as a string {{entry.fieldcontrol}}, which is all well and good, but I'd like to be able to loop through it as an object like a traditional element criteria model:

<ul>
{% for block in entry.gridcontrol %}
  {% set entry = craft.entries.id(block.id) %}
  <li class="{{block.classes}}" style="left:{{block.x}}%">
    {{entry.title}}
  </li>
{% endfor %}
<ul>

However when I try this I don't get any errors, just an empty ul. I guess this is because it's not seeing gridcontrol as an object.

My question is: Did I go about structuring this the wrong way? I've seen other plugins, like nystudio107's SEOmatic, that store data this way. Or am I missing something super silly to get this up and running?

3

You'll simply need to decode the JSON string. Unfortunately, Twig doesn't ship with a json_decode filter, but there's a plugin.

Here's how you'd use it:

<ul>
{% for block in entry.gridcontrol|json_decode %}
  {% set entry = craft.entries.id(block.id) %}
  <li class="{{ block.classes }}" style="left:{{ block.x }}%">
    {{ entry.title }}
  </li>
{% endfor %}
<ul>
| improve this answer | |
  • Perfect, this worked wonderfully. Thanks for the tip. – Rob Erskine Jan 5 '17 at 0:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.