Completed
Push — master ( 07fcd3...4fbd85 )
by Robbie
9s
created

GridFieldClearAllButton::getHTMLFragments()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 1
eloc 6
nc 1
nop 1
1
<?php
2
3
namespace SilverLeague\LogViewer\Forms\GridField;
4
5
use SilverStripe\ORM\ValidationException;
6
use SilverStripe\Forms\GridField\GridField;
7
use SilverStripe\Forms\GridField\GridField_FormAction;
8
use SilverStripe\Forms\GridField\GridField_HTMLProvider;
9
use SilverStripe\Forms\GridField\GridField_ActionProvider;
10
11
/**
12
 * Adds a "Clear all" button to a GridField
13
 *
14
 * @package silverstripe-logviewer
15
 * @author  Robbie Averill <[email protected]>
16
 */
17
class GridFieldClearAllButton implements GridField_HTMLProvider, GridField_ActionProvider
18
{
19
    /**
20
     * Fragment to write the button to
21
     *
22
     * @var string
23
     */
24
    protected $targetFragment;
25
26
    /**
27
     * @param string $targetFragment The HTML fragment to write the button into
28
     */
29
    public function __construct($targetFragment = 'after')
30
    {
31
        $this->targetFragment = $targetFragment;
32
    }
33
34
    /**
35
     * Add a "clear all" button to a <p> tag and assign it to the target fragment
36
     *
37
     * @param  GridField $gridField
38
     * @return array
39
     */
40
    public function getHTMLFragments($gridField)
41
    {
42
        $button = GridField_FormAction::create($gridField, 'clear', 'Clear all', 'clear', null);
43
        $button->setAttribute('data-icon', 'clear-all-logs');
44
        $button->addExtraClass('font-icon-trash-bin action_clear');
45
        $button->setForm($gridField->getForm());
46
47
        return [$this->targetFragment => '<p class="grid-clear-all-button">' . $button->Field() . '</p>'];
48
    }
49
50
    /**
51
     * {@inheritDoc}
52
     *
53
     * @throws ValidationException If the current user does not have permission to delete records
54
     */
55
    public function handleAction(GridField $gridField, $actionName, $arguments, $data)
56
    {
57
        /** @var \SilverStripe\ORM\DataList $gridField */
58
        $list = $gridField->getList();
59
60
        $dataClass = $list->dataClass();
61
        if (!$dataClass::singleton()->canDelete()) {
62
            throw new ValidationException(
63
                _t('GridFieldAction_Delete.EditPermissionsFailure', "No permission to unlink record")
64
            );
65
        }
66
67
        $gridField->getList()->removeAll();
68
    }
69
70
    /**
71
     * {@inheritDoc}
72
     */
73
    public function getActions($gridField)
74
    {
75
        return ['clear'];
76
    }
77
}
78