GridFieldLevelup.php
2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
 * Adds a "level up" link to a GridField table, which is useful when viewing 
 * hierarchical data. Requires the managed record to have a "getParent()" 
 * method or has_one relationship called "Parent".
 *
 * @package forms
 * @subpackage fields-gridfield
 */
class GridFieldLevelup extends Object implements GridField_HTMLProvider {
	
	/**
	 * @var integer - the record id of the level up to
	 */
	protected $currentID = null;
	/**
	 * sprintf() spec for link to link to parent.
	 * Only supports one variable replacement - the parent ID.
	 * @var string
	 */
	protected $linkSpec = '';
	/**
	 * @var array Extra attributes for the link
	 */
	protected $attributes = array();
	/**
	 *
	 * @param integer $currentID - The ID of the current item; this button will find that item's parent
	 */
	public function __construct($currentID) {
		if($currentID && is_numeric($currentID)) $this->currentID = $currentID;
	}
	
	public function getHTMLFragments($gridField) {
		$modelClass = $gridField->getModelClass();
		$parentID = 0;
		if($this->currentID) {
			$modelObj = DataObject::get_by_id($modelClass, $this->currentID);
			if($modelObj->hasMethod('getParent')) {
				$parent = $modelObj->getParent();
			} elseif($modelObj->ParentID) {
				$parent = $modelObj->Parent();
			}
			if($parent) $parentID = $parent->ID;
			
			// Attributes
			$attrs = array_merge($this->attributes, array(
				'href' => sprintf($this->linkSpec, $parentID),
				'class' => 'cms-panel-link list-parent-link'
			));
			$attrsStr = '';
			foreach($attrs as $k => $v) $attrsStr .= " $k=\"" . Convert::raw2att($v) . "\"";
			$forTemplate = new ArrayData(array(
				'UpLink' => sprintf('<a%s>%s</a>', $attrsStr, _t('GridField.LEVELUP', 'Level up'))
			));
			return array(
				'before' => $forTemplate->renderWith('GridFieldLevelup'),
			);
		}
	}
	public function setAttributes($attrs) {
		$this->attributes = $attrs;
		return $this;
	}
	public function getAttributes() {
		return $this->attributes;
	}
	public function setLinkSpec($link) {
		$this->linkSpec = $link;
		return $this;
	}
	public function getLinkSpec() {
		return $this->linkSpec;
	}
} 