Skip to content

Instantly share code, notes, and snippets.

@xiaohutai
Last active March 19, 2018 13:01
Show Gist options
  • Save xiaohutai/4db57e07fc68caab4febde21ba3bf743 to your computer and use it in GitHub Desktop.
Save xiaohutai/4db57e07fc68caab4febde21ba3bf743 to your computer and use it in GitHub Desktop.
Fix that allows previewing blocks (named repeaters) in Bolt 3.4+
extensions:
- Bolt\Extension\Foo\Bar\FixPreviewBlocksExtension
{
...
"autoload": {
"psr-4": {
"Bolt\\Extension\\Foo\\Bar\\": "extensions/bundles/foo/bar/src/"
}
}
}
<?php
namespace Bolt\Extension\Foo\Bar;
use Bolt\Extension\SimpleExtension;
/**
* @author Xiao-Hu Tai <[email protected]>
*/
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;
}
}
@xiaohutai
Copy link
Author

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