Skip to content

Commit

Permalink
Allowed blocks can be set via config.
Browse files Browse the repository at this point in the history
`VirtualBlock` now respects the parent `allowed_blocks` if set.
  • Loading branch information
bummzack committed Nov 9, 2015
1 parent 0c49256 commit f0e61ee
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
20 changes: 18 additions & 2 deletions README.md
Expand Up @@ -102,8 +102,24 @@ VideoBlock:

Imagine that there are two different Page-types. One page can only have *Text-* and *Video-Blocks* attached, the other page should only have *Text-* and *Image-Blocks* as valid options.

The provided `GridFieldConfig_BlockEditor` has a method `setAllowedBlocks` which lets you specify the blocks that can be created on a per-gridfield basis.
This is also being used by the `PageBlocks` Extension.
The best way to do so is to set the `allowed_blocks` config for your page.

```yml
# in your config.yml

MyBlockPage:
allowed_blocks:
- TextBlock
- VideoBlock

MyOtherBlockPage:
allowed_blocks:
- TextBlock
- ImageBlock
```


If you need to set the allowed-blocks on a per-GridField basis, then use `GridFieldConfig_BlockEditor::setAllowedBlocks` which lets you specify the blocks that can be created.

Here's an example, where we limit the allowed blocks to just `ImageBlock` and `TextBlock`:

Expand Down
10 changes: 9 additions & 1 deletion code/blocks/VirtualBlock.php
Expand Up @@ -31,7 +31,15 @@ public function getCMSFields()

$mainTab->setTitle(_t('SiteTree.TABMAIN', "Main"));

$source = Block::get()->exclude('ClassName', 'VirtualBlock')->sort('ParentID, SortOrder')->map('ID', 'FullTitle');
$blockList = Block::get()->exclude('ClassName', 'VirtualBlock');

// Apply the allowed blocks config to the virtual-block
$allowed = $this->Parent()->config()->get('allowed_blocks');
if(is_array($allowed)){
$blockList = $blockList->filter(array('ClassName' => $allowed));
}

$source = $blockList->sort('ParentID, SortOrder')->map('ID', 'FullTitle');

$fields->addFieldsToTab('Root.Main', array(
ReadonlyField::create('Title', _t('Block.TITLE', 'Title'), $this->getTitle()),
Expand Down
4 changes: 3 additions & 1 deletion code/extensions/PageBlocks.php
Expand Up @@ -18,7 +18,7 @@ class PageBlocks extends DataExtension
private static $allow_publish_all = true;

public function updateCMSFields(FieldList $fields) {
$gridConfig = GridFieldConfig_BlockEditor::create('SortOrder');
$gridConfig = GridFieldConfig_BlockEditor::create('SortOrder', $this->owner->config()->get('allowed_blocks'));

$gridField = GridField::create('Blocks', _t('PageBlocks.BLOCK', 'Block', 'GridField Title'),
$this->owner->Blocks(), $gridConfig);
Expand Down Expand Up @@ -164,5 +164,7 @@ public function setAllowedBlocks(array $allowedBlocks)

}

// for method chaining
return $this;
}
}

0 comments on commit f0e61ee

Please sign in to comment.