GridFieldClearAllButton::getActions()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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
            ->setAttribute('data-icon', 'clear-all-logs')
44
            ->addExtraClass('font-icon-trash-bin action_clear no-ajax action-delete btn btn-secondary')
45
            ->setForm($gridField->getForm());
46
47
        return [
48
            $this->targetFragment => $button->Field()
49
        ];
50
    }
51
52
    /**
53
     * {@inheritDoc}
54
     *
55
     * @throws ValidationException If the current user does not have permission to delete records
56
     */
57
    public function handleAction(GridField $gridField, $actionName, $arguments, $data)
58
    {
59
        /** @var \SilverStripe\ORM\DataList $gridField */
60
        $list = $gridField->getList();
61
62
        $dataClass = $list->dataClass();
63
        if (!$dataClass::singleton()->canDelete()) {
64
            throw new ValidationException(
65
                _t('GridFieldAction_Delete.EditPermissionsFailure', "No permission to unlink record")
66
            );
67
        }
68
69
        $gridField->getList()->removeAll();
70
71
        return $gridField->redirectBack();
72
    }
73
74
    /**
75
     * {@inheritDoc}
76
     */
77
    public function getActions($gridField)
78
    {
79
        return ['clear'];
80
    }
81
}
82