Passed
Push — 1.0 ( 56130b...3dec11 )
by Morven
03:53
created

AddToListHandler::getI18nLabel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace SilverCommerce\ContactAdmin\BulkActions;
4
5
use SilverStripe\Forms\Form;
6
use SilverStripe\Core\Convert;
7
use SilverStripe\View\ArrayData;
8
use SilverStripe\ORM\DataObject;
9
use SilverStripe\Forms\FieldList;
10
use SilverStripe\Forms\FormAction;
11
use SilverStripe\TagField\TagField;
12
use SilverStripe\Admin\LeftAndMain;
13
use SilverStripe\Forms\HiddenField;
14
use SilverStripe\Control\Controller;
15
use SilverStripe\Forms\DropdownField;
16
use SilverStripe\ORM\ValidationResult;
17
use SilverStripe\Control\HTTPResponse;
18
use SilverStripe\Core\Injector\Injector;
19
use SilverStripe\Control\PjaxResponseNegotiator;
20
use SilverCommerce\ContactAdmin\Model\ContactTag;
21
use SilverCommerce\ContactAdmin\Model\ContactList;
22
23
/**
24
 * Bulk action handler that adds selected records to a list
25
 * 
26
 * @author ilateral
27
 * @package Contacts
28
 */
29
class AddToListHandler extends AddRelatedHandler
30
{
31
32
    private static $url_segment = 'addtolist';
0 ignored issues
show
introduced by
The private property $url_segment is not used, and could be removed.
Loading history...
33
34
    /**
35
     * Front-end label for this handler's action
36
     * 
37
     * @var string
38
     */
39
    protected $label = 'Add to List';
40
41
    /**
42
     * RequestHandler allowed actions
43
     * @var array
44
     */
45
    private static $allowed_actions = [
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
46
        'index',
47
        'Form'
48
    ];
49
50
    /**
51
     * Return i18n localized front-end label
52
     *
53
     * @return array
54
     */
55
    public function getI18nLabel()
56
    {
57
        return _t(__CLASS__ . '.Label', $this->getLabel());
58
    }
59
    
60
    /**
61
     * Creates and return the editing interface
62
     * 
63
     * @return string Form's HTML
64
     */
65
    public function index()
66
    {
67
        $leftandmain = Injector::inst()->create(LeftAndMain::class);
68
69
        $form = $this->Form();
70
        $form->setTemplate($leftandmain->getTemplatesWithSuffix('_EditForm'));
71
        $form->addExtraClass('cms-edit-form center cms-content');
72
        $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
73
        
74
        if ($this->request->isAjax()) {
75
            $response = new HTTPResponse(
76
                Convert::raw2json(array('Content' => $form->forAjaxTemplate()->getValue()))
77
            );
78
            $response->addHeader('X-Pjax', 'Content');
79
            $response->addHeader('Content-Type', 'text/json');
80
            $response->addHeader('X-Title', 'SilverStripe - Bulk ' . $this->gridField->list->dataClass . ' Editing');
81
82
            return $response;
83
        } else {
84
            $controller = $this->getToplevelController();
85
            return $controller->customise(array('Content' => $form));
86
        }
87
    }
88
89
    /**
90
     * Return a form with a dropdown to select the list you want to use
91
     * 
92
     * @return Form
93
     */
94
    public function Form()
95
    {
96
        $crumbs = $this->Breadcrumbs();
97
        
98
        if ($crumbs && $crumbs->count()>=2) {
99
            $one_level_up = $crumbs->offsetGet($crumbs->count()-2);
100
        }
101
        
102
        $record_ids = "";
103
        $query_string = "";
104
        $recordList = $this->getRecordIDList();
105
        
106
        foreach ($this->getRecordIDList() as $id) {
107
            $record_ids .= $id . ',';
108
            $query_string .= "records[]={$id}&";
109
        }
110
        
111
        // Cut off the last 2 parts of the string
112
        $record_ids = substr($record_ids, 0, -1);
113
        $query_string = substr($query_string, 0, -1);
0 ignored issues
show
Unused Code introduced by
The assignment to $query_string is dead and can be removed.
Loading history...
114
        
115
        $form = new Form(
116
            $this,
117
            'Form',
118
            $fields = FieldList::create(
119
                HiddenField::create("RecordIDs", "", $record_ids),
120
                DropdownField::create(
121
                    "ContactListID",
122
                    _t("Contacts.ChooseList", "Choose a list"),
123
                    ContactList::get()->map()
124
                )->setEmptyString(_t("Contacts.SelectList", "Select a List"))
125
            ),
126
            $actions = FieldList::create(
127
                FormAction::create('doAddToList', _t("Contacts.Add", 'Add'))
128
                    ->setAttribute('id', 'bulkEditingSaveBtn')
129
                    ->addExtraClass('btn btn-success')
130
                    ->setAttribute('data-icon', 'accept')
131
                    ->setUseButtonTag(true),
132
                    
133
                FormAction::create('Cancel', _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.CANCEL_BTN_LABEL', 'Cancel'))
134
                    ->setAttribute('id', 'bulkEditingUpdateCancelBtn')
135
                    ->addExtraClass('btn btn-danger cms-panel-link')
136
                    ->setAttribute('data-icon', 'decline')
137
                    ->setAttribute('href', $one_level_up->Link)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $one_level_up does not seem to be defined for all execution paths leading up to this point.
Loading history...
138
                    ->setUseButtonTag(true)
139
                    ->setAttribute('src', '')
140
            )
141
        );
142
        
143
        if ($crumbs && $crumbs->count() >= 2) {
144
            $form->Backlink = $one_level_up->Link;
145
        }
146
        
147
        // override form action URL back to bulkEditForm
148
        // and add record ids GET var
149
        $form->setFormAction(
150
            $this->Link('Form?records[]='.implode('&', $recordList))
151
        );
152
153
        return $form;
154
    }
155
156
    /**
157
     * Saves the changes made in the bulk edit into the dataObject
158
     * 
159
     * @return HTTPResponse 
160
     */
161
    public function doAddToList($data, /** @scrutinizer ignore-unused */ $form)
162
    {
163
        $className  = $this->gridField->list->dataClass;
164
        $controller = $this->getToplevelController();
165
        $form = $controller->EditForm();
166
        $return = array();
167
168
        if (isset($data['RecordIDs'])) {
169
            $ids = explode(",", $data['RecordIDs']);
170
        } else {
171
            $ids = array();
172
        }
173
174
        $list_id = (isset($data['ContactListID'])) ? $data['ContactListID'] : 0;
175
        $list = ContactList::get()->byID($list_id);
176
        
177
        try {
178
            foreach ($ids as $record_id) {
179
                if ($list_id) {
180
                    $record = DataObject::get_by_id($className, $record_id);
181
                    
182
                    if ($record->hasMethod("Lists")) {
183
                        $list->Contacts()->add($record);
184
                        $list->write();
185
                    }
186
                    
187
                    $return[] = $record->ID;
188
                }
189
            }
190
        } catch (\Exception $e) {
191
            $form->sessionMessage(
192
                $e->getMessage(),
193
                ValidationResult::TYPE_ERROR
194
            );
195
                
196
            $responseNegotiator = new PjaxResponseNegotiator(array(
197
                'CurrentForm' => function () use (&$form) {
198
                    return $form->forTemplate();
199
                },
200
                'default' => function () use (&$controller) {
201
                    return $controller->redirectBack();
202
                }
203
            ));
204
            
205
            if ($controller->getRequest()->isAjax()) {
206
                $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
207
            }
208
            
209
            return $responseNegotiator->respond($controller->getRequest());
210
        }
211
        
212
        if (!empty($list)) {
213
            $message = "Added " . count($return) . " contacts to mailing list '{$list->Title}'";
214
        } else {
215
            $message = _t("Contacts.NoListSelected", "No list selected");
216
        }
217
218
        $form->sessionMessage(
219
            $message,
220
            ValidationResult::TYPE_GOOD
221
        );
222
        
223
        // Changes to the record properties might've excluded the record from
224
        // a filtered list, so return back to the main view if it can't be found
225
        $link = $controller->Link();
226
        $controller->getRequest()->addHeader('X-Pjax', 'Content');
227
        return $controller->redirect($link);
228
    }
229
}
230