Fix that allows previewing blocks (named repeaters) in Bolt 3.4+

Xiao-Hu Tai
2018-03-09T09:50:41Z

.bolt.yml

| extensions:
| - Bolt\Extension\Foo\Bar\FixPreviewBlocksExtension

composer.json

|
| {
| ...
| "autoload": {
| "psr-4": {
| "Bolt\\Extension\\Foo\\Bar\\": "extensions/bundles/foo/bar/src/"
| }
| }
| }

FixPreviewBlocksExtension.php

| <?php
|
| namespace Bolt\Extension\Foo\Bar;
|
| use Bolt\Extension\SimpleExtension;
|
| /**
| * @author Xiao-Hu Tai <xiao@twokings.nl>
| */
| class FixPreviewBlocksExtension extends SimpleExtension
| {
|
| /**
| * {@inheritdoc}
| */
| protected function registerTwigFilters()
| {
| return [
| 'prefillBlocks' => 'twigPrefillBlocks',
| ];
| }
|
| /**
| * Helper function to prefill `block` fields with an additional `block` field per item.
| *
| * This is needed for the preview function to work. In templates that makes extensive use
| * of blocks (i.e. testing for which type of 'block' it is), do:
| *
| * {% set record = record|prefillBlocks %}
| *
| * For a given record, check its contenttype and rewrite all of its block fields, iff
| * the value is an `array` instead of an `object` (e.g. `RepeatingFieldCollection` or
| * `LazyFieldCollection`).
| *
| * This function is probably obsolete once https://github.com/bolt/bolt/pull/7291 is
| * put into stable.
| */
| public function twigPrefillBlocks($record)
| {
| foreach ($record->contenttype['fields'] as $fieldSlug => $fieldSettings) {
| if ($fieldSettings['type'] === 'block'
| && isset($record->values[$fieldSlug])
| && is_array($record->values[$fieldSlug]
| )) {
| $newArray = [];
| foreach ($record->values[$fieldSlug] as $index => $item) {
| if (! empty($item)) {
| foreach ($item as $k => &$v) {
| $v['block'] = $k;
| }
| $newArray[] = $v;
| }
| }
| $record->values[$fieldSlug] = $newArray;
| }
| }
|
| return $record;
| }
|
| }