AddToListHandler::index()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 21
rs 9.7666
cc 2
nc 2
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(['Content' => $form->forAjaxTemplate()->getValue()])
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\Core\Convert::raw2json() has been deprecated: 4.4.0:5.0.0 Use json_encode() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

76
                /** @scrutinizer ignore-deprecated */ Convert::raw2json(['Content' => $form->forAjaxTemplate()->getValue()])

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
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(['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
                FormAction::create('Cancel', _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.CANCEL_BTN_LABEL', 'Cancel'))
133
                    ->setAttribute('id', 'bulkEditingUpdateCancelBtn')
134
                    ->addExtraClass('btn btn-danger cms-panel-link')
135
                    ->setAttribute('data-icon', 'decline')
136
                    ->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...
137
                    ->setUseButtonTag(true)
138
                    ->setAttribute('src', '')
139
            )
140
        );
141
        
142
        if ($crumbs && $crumbs->count() >= 2) {
143
            $form->Backlink = $one_level_up->Link;
144
        }
145
        
146
        // override form action URL back to bulkEditForm
147
        // and add record ids GET var
148
        $form->setFormAction(
149
            $this->Link('Form?records[]='.implode('&', $recordList))
150
        );
151
152
        return $form;
153
    }
154
155
    /**
156
     * Saves the changes made in the bulk edit into the dataObject
157
     *
158
     * @return HTTPResponse
159
     */
160
    public function doAddToList($data, /** @scrutinizer ignore-unused */ $form)
161
    {
162
        $className  = $this->gridField->list->dataClass;
163
        $controller = $this->getToplevelController();
164
        $form = $controller->EditForm();
165
        $return = [];
166
167
        if (isset($data['RecordIDs'])) {
168
            $ids = explode(",", $data['RecordIDs']);
169
        } else {
170
            $ids = [];
171
        }
172
173
        $list_id = (isset($data['ContactListID'])) ? $data['ContactListID'] : 0;
174
        $list = ContactList::get()->byID($list_id);
175
        
176
        try {
177
            foreach ($ids as $record_id) {
178
                if ($list_id) {
179
                    $record = DataObject::get_by_id($className, $record_id);
180
                    
181
                    if ($record->hasMethod("Lists")) {
182
                        $list->Contacts()->add($record);
183
                        $list->write();
184
                    }
185
                    
186
                    $return[] = $record->ID;
187
                }
188
            }
189
        } catch (\Exception $e) {
190
            $form->sessionMessage(
191
                $e->getMessage(),
192
                ValidationResult::TYPE_ERROR
193
            );
194
                
195
            $responseNegotiator = new PjaxResponseNegotiator([
196
                'CurrentForm' => function () use (&$form) {
197
                    return $form->forTemplate();
198
                },
199
                'default' => function () use (&$controller) {
200
                    return $controller->redirectBack();
201
                }
202
            ]);
203
            
204
            if ($controller->getRequest()->isAjax()) {
205
                $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
206
            }
207
            
208
            return $responseNegotiator->respond($controller->getRequest());
209
        }
210
        
211
        if (!empty($list)) {
212
            $message = "Added " . count($return) . " contacts to mailing list '{$list->Title}'";
213
        } else {
214
            $message = _t("Contacts.NoListSelected", "No list selected");
215
        }
216
217
        $form->sessionMessage(
218
            $message,
219
            ValidationResult::TYPE_GOOD
220
        );
221
        
222
        // Changes to the record properties might've excluded the record from
223
        // a filtered list, so return back to the main view if it can't be found
224
        $link = $controller->Link();
225
        $controller->getRequest()->addHeader('X-Pjax', 'Content');
226
        return $controller->redirect($link);
227
    }
228
}
229