Completed
Push — master ( 720fed...5dcbd9 )
by Leo
02:39
created

BlockinPage::gridBuilder()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
c 6
b 0
f 0
dl 0
loc 27
rs 8.8571
cc 3
eloc 18
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
33
			->removeComponentsByType('GridFieldPaginator')
34
			->removeComponentsByType('GridFieldDetailForm')
35
			->addComponents(
36
				new VersionedForm(),
37
				new GridFieldPaginatorWithShowAll(30),
38
				$multiClass = new MultiClassSelector(),
39
				$sortable = new GridFieldOrderableRows('SortOrder')
40
			);
41
			$subBlocks = BlocksAdmin::getAvaiableTypes();
42
			$multiClass->setClasses($subBlocks);
43
		}
44
		$grid->setConfig($config);
45
		return $grid;
46
	}
47
		
48
	private function dockedBlocks() {
49
		$blocks = Block::get();
50
		$IDs = array();
51
		$ClassName = $this->owner->ClassName;
52
		$Classes = $blocks->map('ID', 'shownInClass');
53
		foreach ($Classes as $BlockID => $Class) {
54
			$listedClasses = explode(',', $Class);
55
			if (in_array($ClassName, $listedClasses)) {
56
				$IDs[] = $BlockID;
57
			}
58
		}
59
		$blocks = Block::get()->filter('ID', $IDs)->sort('SortOrder','ASC');
60
		return $blocks;
61
	}
62
}