Completed
Push — master ( 1be2e7...d38097 )
by Sam
23s
created

GridFieldAddNewButton   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 44
rs 10
c 0
b 0
f 0
wmc 5
lcom 1
cbo 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setButtonName() 0 6 1
A __construct() 0 4 1
B getHTMLFragments() 0 24 3
1
<?php
2
3
namespace SilverStripe\Forms\GridField;
4
5
use SilverStripe\Control\Controller;
6
use SilverStripe\View\ArrayData;
7
use SilverStripe\View\SSViewer;
8
9
/**
10
 * This component provides a button for opening the add new form provided by
11
 * {@link GridFieldDetailForm}.
12
 *
13
 * Only returns a button if {@link DataObject->canCreate()} for this record
14
 * returns true.
15
 */
16
class GridFieldAddNewButton implements GridField_HTMLProvider
17
{
18
19
    protected $targetFragment;
20
21
    protected $buttonName;
22
23
    public function setButtonName($name)
24
    {
25
        $this->buttonName = $name;
26
27
        return $this;
28
    }
29
30
    public function __construct($targetFragment = 'before')
31
    {
32
        $this->targetFragment = $targetFragment;
33
    }
34
35
    public function getHTMLFragments($gridField)
36
    {
37
        $singleton = singleton($gridField->getModelClass());
38
39
        if (!$singleton->canCreate()) {
40
            return array();
41
        }
42
43
        if (!$this->buttonName) {
44
            // provide a default button name, can be changed by calling {@link setButtonName()} on this component
45
            $objectName = $singleton->i18n_singular_name();
46
            $this->buttonName = _t('GridField.Add', 'Add {name}', array('name' => $objectName));
47
        }
48
49
        $data = new ArrayData(array(
50
            'NewLink' => Controller::join_links($gridField->Link('item'), 'new'),
51
            'ButtonName' => $this->buttonName,
52
        ));
53
54
        $templates = SSViewer::get_templates_by_class($this, '', __CLASS__);
55
        return array(
56
            $this->targetFragment => $data->renderWith($templates),
57
        );
58
    }
59
}
60