Query a specific entry from structure-collection

I have created a blueprint with a structure-field.

Next, I populated this field with three entries, every entry has an unique-id (chart_id).

I am creating a plugin that spits out dynamic highcharts, and I want to be able to query a specific entry from that structure-field.

Is this possible?

I have tried methods like pluck, query, find, filter and ->filterBy() but nothing did work…

In MySQL you can query a specific entry that matches your preferences;

Something like echo $page->charts(WHERE chart_id = chart_02)->kt(), but how do you do this Kirby-style?

I did manage to create a working solution, but I don’t like it - it loops through every entry and shows only the content when the query-selector matches (well… this is what I want, but maybe there is a shortcut / shortcode / shorthand for it?).

And I was able to solve it, using the default array_filter() but I am looking for a native Kirby solution (if any).


##BLUEPRINT


  charts:
    label: Create new chart
    type: structure
    fields:

      chart_id:
        label: ID
        type: text

      chart_title:
        label: TITLE
        type: text

      chart_content:
        label: CONTENT
        type: text

##ENTRIES



##WORKING CODE #1


<?php

$charts = yaml($page->charts());
foreach($charts as $chart):

  if($chart['chart_id'] == 'chart02')
    {
  echo '<h4>'.$chart['chart_title'].'</h4>';
  echo '<b>'.$chart['chart_content'].'</b>';
    }

endforeach

?>

##WORKING CODE #2


<?php

$charts = array_filter(yaml($page->charts()),function($select)
  {
return ($select['chart_id'] == 'chart02');
  });

foreach($charts as $chart):

  echo '<h4>'.$chart['chart_title'].'</h4>';
  echo '<b>'.$chart['chart_content'].'</b>';

endforeach

?>

##RESULT


Have you tried to use filterBy() with the toStructure() method instead of yaml()? Not sure if this works, though, but if it doesn’t it should be a feature.

It looks like that is Kirbies alternative, for the native php array_filter(...) !

This code does work (just like working code #2 example in my opening post).

<?php

foreach($page->charts()->toStructure()->filterBy('chart_id', 'chart02') as $chart):

  echo '<h4>'.$chart->chart_title().'</h4>';
  echo '<b>'.$chart->chart_content().'</b>';

endforeach

?>

If this is the best “native” way to approach / solve the problem I will use it.

Once my dynamic HighCharts Kirby Plugin is finished, I’ll share the code in this forum - so everybody can create highcharts from the panel using a nice and easy interface :slight_smile:


This chart is completely created using the plugin (labels, colors, values, chart-type, etc).

1 Like