Completed
Push — master ( cd834b...e038e5 )
by Leo
03:10
created

BlockinPage::gridBuilder()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 22
rs 9.2
cc 3
eloc 13
nc 4
nop 5
1
<?php
2
3
class BlockinPage extends Extension {
4
	protected static $belongs_many_many = array (
5
		'Blocks'			=>	'Block'
6
	);
7
	
8
	public function updateCMSFields( FieldList $fields ) {
9
		$ancestry = ClassInfo::ancestry($this->owner->ClassName);
10
		if (!in_array('RedirectorPage', $ancestry) && !in_array('VirtualPage', $ancestry)) {
11
			$blocks = $this->owner->Blocks();
12
			$blocks_grid = $this->gridBuilder('Blocks', $blocks, '', true,'GridFieldConfig_RelationEditor');
13
			$docked_grid = $this->gridBuilder('DockedBlocks', $this->dockedBlocks(), '');
14
			
15
			$fields->addFieldToTab('Root.MyBlocks', $blocks_grid);
16
			$fields->addFieldToTab('Root.DockedBlocks', $docked_grid);
17
		}
18
	}
19
	
20
	private function gridBuilder($name, $source, $label = '', $canAdd = false, $gridHeaderType = 'GridFieldConfig_RecordEditor') {
21
		/*
22
		GridFieldConfig_Base
23
		GridFieldConfig_RecordViewer
24
		GridFieldConfig_RecordEditor
25
		GridFieldConfig_RelationEditor
26
		*/
27
		if ($label == '') { $label = $name; }
28
		$grid = new GridField($name, $label, $source);
29
		$config = $gridHeaderType::create();
30
		$config->removeComponentsByType('GridFieldAddNewButton');
31
		if ( $canAdd ) {
32
			$config->addComponents(
33
				$multiClass = new MultiClassSelector(),
34
				$sortable = new GridFieldOrderableRows('SortOrder')
35
			);
36
			$subBlocks = BlocksAdmin::getAvaiableTypes();
37
			$multiClass->setClasses($subBlocks);
38
		}
39
		$grid->setConfig($config);
40
		return $grid;
41
	}
42
		
43
	private function dockedBlocks() {
44
		$blocks = Block::get();
45
		$IDs = array();
46
		$ClassName = $this->owner->ClassName;
47
		$Classes = $blocks->map('ID', 'shownInClass');
48
		foreach ($Classes as $BlockID => $Class) {
49
			$listedClasses = explode(',', $Class);
50
			if (in_array($ClassName, $listedClasses)) {
51
				$IDs[] = $BlockID;
52
			}
53
		}
54
		$blocks = Block::get()->filter('ID', $IDs)->sort('SortOrder','ASC');
55
		return $blocks;
56
	}
57
}