UserForm::getAttributes()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\UserForms\Form;
4
5
use ResetFormAction;
0 ignored issues
show
Bug introduced by
The type ResetFormAction was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Control\Session;
8
use SilverStripe\Forms\FieldList;
9
use SilverStripe\Forms\Form;
10
use SilverStripe\Forms\FormAction;
11
use SilverStripe\UserForms\FormField\UserFormsStepField;
12
use SilverStripe\UserForms\FormField\UserFormsFieldList;
13
14
/**
15
 * @package userforms
16
 */
17
class UserForm extends Form
18
{
19
    /**
20
     * @config
21
     * @var string
22
     */
23
    private static $button_text = '';
24
25
    /**
26
     * @param Controller $controller
27
     * @param string $name
28
     */
29
    public function __construct(Controller $controller, $name = Form::class)
30
    {
31
        $this->controller = $controller;
32
        $this->setRedirectToFormOnValidationError(true);
33
34
        parent::__construct(
35
            $controller,
36
            $name,
37
            new FieldList(),
38
            new FieldList()
39
        );
40
41
        $this->setFields($fields = $this->getFormFields());
42
43
        $fields->setForm($this);
44
        $this->setActions($actions = $this->getFormActions());
45
        $actions->setForm($this);
46
        $this->setValidator($this->getRequiredFields());
47
48
        // This needs to be re-evaluated since fields have been assigned
49
        $this->restoreFormState();
50
51
        // Number each page
52
        $stepNumber = 1;
53
        foreach ($this->getSteps() as $step) {
54
            $step->setStepNumber($stepNumber++);
55
        }
56
57
        if ($controller->DisableCsrfSecurityToken) {
58
            $this->disableSecurityToken();
59
        }
60
61
        $data = $this->getRequest()->getSession()->get("FormInfo.{$this->FormName()}.data");
62
63
        if (is_array($data)) {
64
            $this->loadDataFrom($data);
65
        }
66
67
        $this->extend('updateForm');
68
    }
69
70
    public function restoreFormState()
71
    {
72
        // Suppress restoreFormState if fields haven't been bootstrapped
73
        if ($this->fields && $this->fields->exists()) {
74
            return parent::restoreFormState();
75
        }
76
77
        return $this;
78
    }
79
80
    /**
81
     * Used for partial caching in the template.
82
     *
83
     * @return string
84
     */
85
    public function getLastEdited()
86
    {
87
        return $this->controller->LastEdited;
88
    }
89
90
    /**
91
     * @return bool
92
     */
93
    public function getDisplayErrorMessagesAtTop()
94
    {
95
        return (bool)$this->controller->DisplayErrorMessagesAtTop;
96
    }
97
98
    /**
99
     * Return the fieldlist, filtered to only contain steps
100
     *
101
     * @return \SilverStripe\ORM\ArrayList
102
     */
103
    public function getSteps()
104
    {
105
        return $this->Fields()->filterByCallback(function ($field) {
106
            return $field instanceof UserFormsStepField;
107
        });
108
    }
109
110
    /**
111
     * Get the form fields for the form on this page. Can modify this FieldSet
112
     * by using {@link updateFormFields()} on an {@link Extension} subclass which
113
     * is applied to this controller.
114
     *
115
     * This will be a list of top level composite steps
116
     *
117
     * @return FieldList
118
     */
119
    public function getFormFields()
120
    {
121
        $fields = new UserFormsFieldList();
122
        $target = $fields;
123
124
        foreach ($this->controller->data()->Fields() as $field) {
125
            $target = $target->processNext($field);
126
        }
127
        $fields->clearEmptySteps();
128
        $this->extend('updateFormFields', $fields);
129
        $fields->setForm($this);
130
        return $fields;
131
    }
132
133
    /**
134
     * Generate the form actions for the UserDefinedForm. You
135
     * can manipulate these by using {@link updateFormActions()} on
136
     * a decorator.
137
     *
138
     * @todo Make form actions editable via their own field editor.
139
     *
140
     * @return FieldList
141
     */
142
    public function getFormActions()
143
    {
144
        $submitText = ($this->controller->SubmitButtonText)
145
            ? $this->controller->SubmitButtonText
146
            : _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SUBMITBUTTON', 'Submit');
147
        $clearText = ($this->controller->ClearButtonText)
148
            ? $this->controller->ClearButtonText
149
            : _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.CLEARBUTTON', 'Clear');
150
151
        $actions = FieldList::create(FormAction::create('process', $submitText));
152
153
        if ($this->controller->ShowClearButton) {
154
            $actions->push(FormAction::create('clearForm', $clearText)->setAttribute('type', 'reset'));
155
        }
156
157
        $this->extend('updateFormActions', $actions);
158
        $actions->setForm($this);
159
        return $actions;
160
    }
161
162
    /**
163
     * Get the required form fields for this form.
164
     *
165
     * @return RequiredFields
0 ignored issues
show
Bug introduced by
The type SilverStripe\UserForms\Form\RequiredFields was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
166
     */
167
    public function getRequiredFields()
168
    {
169
        // Generate required field validator
170
        $requiredNames = $this
171
            ->getController()
172
            ->data()
173
            ->Fields()
174
            ->filter('Required', true)
175
            ->column('Name');
176
        $requiredNames = array_merge($requiredNames, $this->getEmailRecipientRequiredFields());
177
        $required = new UserFormsRequiredFields($requiredNames);
178
        $this->extend('updateRequiredFields', $required);
179
        $required->setForm($this);
180
        return $required;
181
    }
182
183
    /**
184
     * Override some we can add UserForm specific attributes to the form.
185
     *
186
     * @return array
187
     */
188
    public function getAttributes()
189
    {
190
        $attrs = parent::getAttributes();
191
192
        $attrs['class'] = $attrs['class'] . ' userform';
193
        $attrs['data-livevalidation'] = (bool)$this->controller->EnableLiveValidation;
194
        $attrs['data-toperrors'] = (bool)$this->controller->DisplayErrorMessagesAtTop;
195
196
        return $attrs;
197
    }
198
199
    /**
200
     * @return string
201
     */
202
    public function getButtonText()
203
    {
204
        return $this->config()->get('button_text');
205
    }
206
207
    /**
208
     * Push fields into the RequiredFields array if they are used by any Email recipients.
209
     * Ignore if there is a backup i.e. the plain string field is set
210
     *
211
     * @return array required fields names
212
     */
213
    protected function getEmailRecipientRequiredFields()
214
    {
215
        $requiredFields = [];
216
        $recipientFieldsMap = [
217
            'EmailAddress' => 'SendEmailToField',
218
            'EmailSubject' => 'SendEmailSubjectField',
219
            'EmailReplyTo' => 'SendEmailFromField'
220
        ];
221
222
        foreach ($this->getController()->data()->EmailRecipients() as $recipient) {
223
            foreach ($recipientFieldsMap as $textField => $dynamicFormField) {
224
                if (empty($recipient->$textField) && $recipient->getComponent($dynamicFormField)->exists()) {
225
                    $requiredFields[] = $recipient->getComponent($dynamicFormField)->Name;
226
                }
227
            }
228
        }
229
230
        return $requiredFields;
231
    }
232
}
233