Completed
Push — master ( c02fab...ffc04d )
by Kristijan
06:15
created

Form::remove()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php namespace Kris\LaravelFormBuilder;
2
3
use Illuminate\Contracts\Validation\Factory as ValidatorFactory;
4
use Illuminate\Contracts\Validation\Validator;
5
use Illuminate\Http\Request;
6
use Kris\LaravelFormBuilder\Fields\FormField;
7
8
class Form
9
{
10
11
    /**
12
     * All fields that are added
13
     *
14
     * @var array
15
     */
16
    protected $fields = [];
17
18
    /**
19
     * Model to use
20
     *
21
     * @var mixed
22
     */
23
    protected $model = [];
24
25
    /**
26
     * @var FormHelper
27
     */
28
    protected $formHelper;
29
30
    /**
31
     * Form options
32
     *
33
     * @var array
34
     */
35
    protected $formOptions = [
36
        'method' => 'GET',
37
        'url' => null
38
    ];
39
40
    /**
41
     * Additional data which can be used to build fields
42
     *
43
     * @var array
44
     */
45
    protected $data = [];
46
47
    /**
48
     * Should errors for each field be shown when called form($form) or form_rest($form) ?
49
     *
50
     * @var bool
51
     */
52
    protected $showFieldErrors = true;
53
54
    /**
55
     * Enable html5 validation
56
     *
57
     * @var bool
58
     */
59
    protected $clientValidationEnabled = true;
60
61
    /**
62
     * Name of the parent form if any
63
     *
64
     * @var string|null
65
     */
66
    protected $name = null;
67
68
    /**
69
     * @var FormBuilder
70
     */
71
    protected $formBuilder;
72
73
    /**
74
     * @var ValidatorFactory
75
     */
76
    protected $validatorFactory;
77
78
    /**
79
     * @var Validator
80
     */
81
    protected $validator = null;
82
83
    /**
84
     * @var Request
85
     */
86
    protected $request;
87
88
    /**
89
     * List of fields to not render
90
     *
91
     * @var array
92
     **/
93
    protected $exclude = [];
94
95
    /**
96
     * Are form being rebuilt?
97
     *
98
     * @var bool
99
     */
100
    protected $rebuilding = false;
101
102
    /**
103
     * @var string
104
     */
105
    protected $templatePrefix;
106
107
    /**
108
     * @var string
109
     */
110
    protected $languageName;
111
112
    /**
113
     * Build the form
114
     *
115
     * @return mixed
116
     */
117 2
    public function buildForm()
118
    {
119 2
    }
120
121
    /**
122
     * Rebuild the form from scratch
123
     *
124
     * @return $this
125
     */
126 14
    public function rebuildForm()
127
    {
128 14
        $this->rebuilding = true;
129
        // If form is plain, buildForm method is empty, so we need to take
130
        // existing fields and add them again
131 14
        if (get_class($this) === 'Kris\LaravelFormBuilder\Form') {
132 13
            foreach ($this->fields as $name => $field) {
133
                // Remove any temp variables added in previous instance
134 5
                $options = array_except($field->getOptions(), 'tmp');
135 13
                $this->add($name, $field->getType(), $options);
136
            }
137
        } else {
138 3
            $this->buildForm();
139
        }
140 14
        $this->rebuilding = false;
141
142 14
        return $this;
143
    }
144
145
    /**
146
     * Create the FormField object
147
     *
148
     * @param string $name
149
     * @param string $type
150
     * @param array  $options
151
     * @return FormField
152
     */
153 42
    protected function makeField($name, $type = 'text', array $options = [])
154
    {
155 42
        $this->setupFieldOptions($name, $options);
156
157 42
        $fieldName = $this->getFieldName($name);
158
159 42
        $fieldType = $this->getFieldType($type);
160
161 41
        return new $fieldType($fieldName, $type, $this, $options);
162
    }
163
164
    /**
165
     * Create a new field and add it to the form
166
     *
167
     * @param string $name
168
     * @param string $type
169
     * @param array  $options
170
     * @param bool   $modify
171
     * @return $this
172
     */
173 43
    public function add($name, $type = 'text', array $options = [], $modify = false)
174
    {
175 43
        if (!$name || trim($name) == '') {
176 1
            throw new \InvalidArgumentException(
177 1
                'Please provide valid field name for class ['. get_class($this) .']'
178
            );
179
        }
180
181 42
        if ($this->rebuilding && !$this->has($name)) {
182
            return $this;
183
        }
184
185 42
        $this->addField($this->makeField($name, $type, $options), $modify);
186
187 38
        return $this;
188
    }
189
190
    /**
191
     * Add a FormField to the form's fields
192
     *
193
     * @param FormField $field
194
     * @return $this
195
     */
196 38
    protected function addField(FormField $field, $modify = false)
197
    {
198 38
        if (!$modify && !$this->rebuilding) {
199 38
            $this->preventDuplicate($field->getRealName());
200
        }
201
202
203 38
        if ($field->getType() == 'file') {
204 3
            $this->formOptions['files'] = true;
205
        }
206
207 38
        $this->fields[$field->getRealName()] = $field;
208
209 38
        return $this;
210
    }
211
212
    /**
213
     * Add field before another field
214
     *
215
     * @param string  $name         Name of the field before which new field is added
216
     * @param string  $fieldName    Field name which will be added
217
     * @param string  $type
218
     * @param array   $options
219
     * @param boolean $modify
220
     * @return $this
221
     */
222 1
    public function addBefore($name, $fieldName, $type = 'text', $options = [], $modify = false)
223
    {
224 1
        $offset = array_search($name, array_keys($this->fields));
225
226 1
        $beforeFields = array_slice($this->fields, 0, $offset);
227 1
        $afterFields = array_slice($this->fields, $offset);
228
229 1
        $this->fields = $beforeFields;
230
231 1
        $this->add($fieldName, $type, $options, $modify);
232
233 1
        $this->fields += $afterFields;
234
235 1
        return $this;
236
    }
237
238
    /**
239
     * Add field before another field
240
     * @param string  $name         Name of the field after which new field is added
241
     * @param string  $fieldName    Field name which will be added
242
     * @param string  $type
243
     * @param array   $options
244
     * @param boolean $modify
245
     * @return $this
246
     */
247 1
    public function addAfter($name, $fieldName, $type = 'text', $options = [], $modify = false)
248
    {
249 1
        $offset = array_search($name, array_keys($this->fields));
250
251 1
        $beforeFields = array_slice($this->fields, 0, $offset + 1);
252 1
        $afterFields = array_slice($this->fields, $offset + 1);
253
254 1
        $this->fields = $beforeFields;
255
256 1
        $this->add($fieldName, $type, $options, $modify);
257
258 1
        $this->fields += $afterFields;
259
260 1
        return $this;
261
    }
262
263
    /**
264
     * Take another form and add it's fields directly to this form
265
     * @param mixed   $class        Form to merge
266
     * @param array   $options
267
     * @param boolean $modify
268
     * @return $this
269
     */
270 1
    public function compose($class, array $options = [], $modify = false)
271
    {
272 1
        $options['class'] = $class;
273
274
        // If we pass a ready made form just extract the fields
275 1
        if ($class instanceof Form) {
276 1
            $fields = $class->getFields();
277
        } elseif ($class instanceof Fields\ChildFormType) {
278
            $fields = $class->getForm()->getFields();
279
        } elseif (is_string($class)) {
280
            // If its a string of a class make it the usual way
281
            $options['model'] = $this->model;
282
            $options['name'] = $this->name;
283
284
            $form = $this->formBuilder->create($class, $options);
285
            $fields = $form->getFields();
286
        } else {
287
            throw new \InvalidArgumentException(
288
                "[{$class}] is invalid. Please provide either a full class name, Form or ChildFormType"
289
            );
290
        }
291
292 1
        foreach ($fields as $field) {
293 1
            $this->addField($field, $modify);
294
        }
295
296 1
        return $this;
297
    }
298
299
    /**
300
     * Remove field with specified name from the form
301
     *
302
     * @param $name
303
     * @return $this
304
     */
305 2
    public function remove($name)
306
    {
307 2
        if ($this->has($name)) {
308 2
            unset($this->fields[$name]);
309
        }
310
311 2
        return $this;
312
    }
313
314
    /**
315
     * Modify existing field. If it doesn't exist, it is added to form
316
     *
317
     * @param        $name
318
     * @param string $type
319
     * @param array  $options
320
     * @param bool   $overwriteOptions
321
     * @return Form
322
     */
323 1
    public function modify($name, $type = 'text', array $options = [], $overwriteOptions = false)
324
    {
325
        // If we don't want to overwrite options, we merge them with old options
326 1
        if ($overwriteOptions === false && $this->has($name)) {
327 1
            $options = $this->formHelper->mergeOptions(
328 1
                $this->getField($name)->getOptions(),
329
                $options
330
            );
331
        }
332
333 1
        return $this->add($name, $type, $options, true);
334
    }
335
336
    /**
337
     * Render full form
338
     *
339
     * @param array $options
340
     * @param bool  $showStart
341
     * @param bool  $showFields
342
     * @param bool  $showEnd
343
     * @return string
344
     */
345 6
    public function renderForm(array $options = [], $showStart = true, $showFields = true, $showEnd = true)
346
    {
347 6
        return $this->render($options, $this->fields, $showStart, $showFields, $showEnd);
348
    }
349
350
    /**
351
     * Render rest of the form
352
     *
353
     * @param bool $showFormEnd
354
     * @param bool $showFields
355
     * @return string
356
     */
357 1
    public function renderRest($showFormEnd = true, $showFields = true)
358
    {
359 1
        $fields = $this->getUnrenderedFields();
360
361 1
        return $this->render([], $fields, false, $showFields, $showFormEnd);
362
    }
363
364
    /**
365
     * Renders the rest of the form up until the specified field name
366
     *
367
     * @param string $field_name
368
     * @param bool   $showFormEnd
369
     * @param bool   $showFields
370
     * @return string
371
     */
372 2
    public function renderUntil($field_name, $showFormEnd = true, $showFields = true)
373
    {
374 2
        if (!$this->has($field_name)) {
375 1
            $this->fieldDoesNotExist($field_name);
376
        }
377
378 1
        $fields = $this->getUnrenderedFields();
379
380 1
        $i = 1;
381 1
        foreach ($fields as $key => $value) {
382 1
            if ($value->getRealName() == $field_name) {
383 1
                break;
384
            }
385 1
            $i++;
386
        }
387
388 1
        $fields = array_slice($fields, 0, $i, true);
389
390 1
        return $this->render([], $fields, false, $showFields, $showFormEnd);
391
    }
392
393
    /**
394
     * Get single field instance from form object
395
     *
396
     * @param $name
397
     * @return FormField
398
     */
399 24
    public function getField($name)
400
    {
401 24
        if ($this->has($name)) {
402 23
            return $this->fields[$name];
403
        }
404
405 1
        $this->fieldDoesNotExist($name);
406
    }
407
408
    /**
409
     * Check if form has field
410
     *
411
     * @param $name
412
     * @return bool
413
     */
414 38
    public function has($name)
415
    {
416 38
        return array_key_exists($name, $this->fields);
417
    }
418
419
    /**
420
     * Get all form options
421
     *
422
     * @return array
423
     */
424 2
    public function getFormOptions()
425
    {
426 2
        return $this->formOptions;
427
    }
428
429
    /**
430
     * Get single form option
431
     *
432
     * @param string $option
433
     * @param $default
434
     * @return mixed
435
     */
436 90
    public function getFormOption($option, $default = null)
437
    {
438 90
        return array_get($this->formOptions, $option, $default);
439
    }
440
441
    /**
442
     * Set single form option on form
443
     *
444
     * @param string $option
445
     * @param mixed $value
446
     *
447
     * @return $this
448
     */
449 2
    public function setFormOption($option, $value)
450
    {
451 2
        $this->formOptions[$option] = $value;
452
453 2
        return $this;
454
    }
455
456
    /**
457
     * Set form options
458
     *
459
     * @param array $formOptions
460
     * @return $this
461
     */
462 90
    public function setFormOptions($formOptions)
463
    {
464 90
        $this->formOptions = $this->formHelper->mergeOptions($this->formOptions, $formOptions);
465 90
        $this->checkIfNamedForm();
466 90
        $this->pullFromOptions('data', 'addData');
467 90
        $this->pullFromOptions('model', 'setupModel');
468 90
        $this->pullFromOptions('errors_enabled', 'setErrorsEnabled');
469 90
        $this->pullFromOptions('client_validation', 'setClientValidationEnabled');
470 90
        $this->pullFromOptions('template_prefix', 'setTemplatePrefix');
471 90
        $this->pullFromOptions('language_name', 'setLanguageName');
472
473 90
        return $this;
474
    }
475
476
    /**
477
     * Get an option from provided options and call method with that value
478
     *
479
     * @param $name
480
     * @param $method
481
     */
482 90
    protected function pullFromOptions($name, $method)
483
    {
484 90
        if (array_get($this->formOptions, $name) !== null) {
485 15
            $this->{$method}(array_pull($this->formOptions, $name));
486
        }
487 90
    }
488
489
    /**
490
     * Get form http method
491
     *
492
     * @return string
493
     */
494 3
    public function getMethod()
495
    {
496 3
        return $this->formOptions['method'];
497
    }
498
499
    /**
500
     * Set form http method
501
     *
502
     * @param string $method
503
     * @return $this
504
     */
505 1
    public function setMethod($method)
506
    {
507 1
        $this->formOptions['method'] = $method;
508
509 1
        return $this;
510
    }
511
512
    /**
513
     * Get form action url
514
     *
515
     * @return string
516
     */
517 3
    public function getUrl()
518
    {
519 3
        return $this->formOptions['url'];
520
    }
521
522
    /**
523
     * Set form action url
524
     *
525
     * @param string $url
526
     * @return $this
527
     */
528 1
    public function setUrl($url)
529
    {
530 1
        $this->formOptions['url'] = $url;
531
532 1
        return $this;
533
    }
534
535
    /**
536
     * @return string|null
537
     */
538 47
    public function getName()
539
    {
540 47
        return $this->name;
541
    }
542
543
    /**
544
     * @param string $name
545
     * @param bool $rebuild
546
     *
547
     * @return $this
548
     */
549 8
    public function setName($name, $rebuild = true)
550
    {
551 8
        $this->name = $name;
552
553 8
        if ($rebuild) {
554 8
            $this->rebuildForm();
555
        }
556
557 8
        return $this;
558
    }
559
560
    /**
561
     * Get model that is bind to form object
562
     *
563
     * @return mixed
564
     */
565 67
    public function getModel()
566
    {
567 67
        return $this->model;
568
    }
569
570
    /**
571
     * Set model to form object
572
     *
573
     * @param mixed $model
574
     * @return $this
575
     * @deprecated deprecated since 1.6.31, will be removed in 1.7 - pass model as option when creating a form
576
     */
577
    public function setModel($model)
578
    {
579
        $this->model = $model;
580
581
        $this->setupNamedModel();
582
583
        $this->rebuildForm();
584
585
        return $this;
586
    }
587
588
    /**
589
     * Setup model for form, add namespace if needed for child forms
590
     * @return $this
591
     */
592 9
    protected function setupModel($model)
593
    {
594 9
        $this->model = $model;
595
596 9
        $this->setupNamedModel();
597
598 9
        return $this;
599
    }
600
601
    /**
602
     * Get all fields
603
     *
604
     * @return FormField[]
605
     */
606 18
    public function getFields()
607
    {
608 18
        return $this->fields;
609
    }
610
611
    /**
612
     * Get field dynamically
613
     *
614
     * @param $name
615
     * @return FormField
616
     */
617 19
    public function __get($name)
618
    {
619 19
        if ($this->has($name)) {
620 18
            return $this->getField($name);
621
        }
622 3
    }
623
624
    /**
625
     * Set the form helper only on first instantiation
626
     *
627
     * @param FormHelper $formHelper
628
     * @return $this
629
     */
630 90
    public function setFormHelper(FormHelper $formHelper)
631
    {
632 90
        $this->formHelper = $formHelper;
633
634 90
        return $this;
635
    }
636
637
    /**
638
     * Get form helper
639
     *
640
     * @return FormHelper
641
     */
642 71
    public function getFormHelper()
643
    {
644 71
        return $this->formHelper;
645
    }
646
647
    /**
648
     * Add custom field
649
     *
650
     * @param $name
651
     * @param $class
652
     */
653 2
    public function addCustomField($name, $class)
654
    {
655 2
        $this->formHelper->addCustomField($name, $class);
656 2
    }
657
658
    /**
659
     * Should form errors be shown under every field ?
660
     *
661
     * @return bool
662
     */
663 71
    public function haveErrorsEnabled()
664
    {
665 71
        return $this->showFieldErrors;
666
    }
667
668
    /**
669
     * Enable or disable showing errors under fields
670
     *
671
     * @param boolean $enabled
672
     * @return $this
673
     */
674 1
    public function setErrorsEnabled($enabled)
675
    {
676 1
        $this->showFieldErrors = (boolean) $enabled;
677
678 1
        return $this;
679
    }
680
681
    /**
682
     * Is client validation enabled?
683
     *
684
     * @return boolean
685
     */
686 71
    public function clientValidationEnabled()
687
    {
688 71
        return $this->clientValidationEnabled;
689
    }
690
691
    /**
692
     * Enable/disable client validation
693
     *
694
     * @param boolean $enable
695
     * @return $this
696
     */
697 1
    public function setClientValidationEnabled($enable)
698
    {
699 1
        $this->clientValidationEnabled = (boolean) $enable;
700
701 1
        return $this;
702
    }
703
704
    /**
705
     * Add any aditional data that field needs (ex. array of choices)
706
     *
707
     * @deprecated deprecated since 1.6.20, will be removed in 1.7 - use 3rd param on create, or 2nd on plain method to pass data
708
     * will be switched to protected in 1.7
709
     * @param string $name
710
     * @param mixed $data
711
     */
712
    public function setData($name, $data)
713
    {
714
        $this->data[$name] = $data;
715
    }
716
717
    /**
718
     * Get single additional data
719
     *
720
     * @param string $name
721
     * @param null   $default
722
     * @return mixed
723
     */
724 13
    public function getData($name = null, $default = null)
725
    {
726 13
        if (is_null($name)) {
727 12
            return $this->data;
728
        }
729
730 1
        return array_get($this->data, $name, $default);
731
    }
732
733
    /**
734
     * Add multiple peices of data at once
735
     *
736
     * @deprecated deprecated since 1.6.12, will be removed in 1.7 - use 3rd param on create, or 2nd on plain method to pass data
737
     * will be switched to protected in 1.7
738
     * @param $data
739
     * @return $this
740
     **/
741
    public function addData(array $data)
742
    {
743
        foreach ($data as $key => $value) {
744
            $this->setData($key, $value);
0 ignored issues
show
Deprecated Code introduced by
The method Kris\LaravelFormBuilder\Form::setData() has been deprecated with message: deprecated since 1.6.20, will be removed in 1.7 - use 3rd param on create, or 2nd on plain method to pass data
will be switched to protected in 1.7

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

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

Loading history...
745
        }
746
747
        return $this;
748
    }
749
750
    /**
751
     * Get current request
752
     *
753
     * @return \Illuminate\Http\Request
754
     */
755 71
    public function getRequest()
756
    {
757 71
        return $this->request;
758
    }
759
760
    /**
761
     * Set request on form
762
     *
763
     * @param Request $request
764
     * @return $this
765
     */
766 90
    public function setRequest(Request $request)
767
    {
768 90
        $this->request = $request;
769
770 90
        return $this;
771
    }
772
773
    /**
774
     * Get template prefix that is prepended to all template paths
775
     *
776
     * @return string
777
     */
778 31
    public function getTemplatePrefix()
779
    {
780 31
        if ($this->templatePrefix !== null) {
781 4
            return $this->templatePrefix;
782
        }
783
784 27
        return $this->formHelper->getConfig('template_prefix');
785
    }
786
787
    /**
788
     * Set a template prefix for the form and its fields
789
     *
790
     * @param string $prefix
791
     * @return $this
792
     */
793 4
    public function setTemplatePrefix($prefix)
794
    {
795 4
        $this->templatePrefix = (string) $prefix;
796
797 4
        return $this;
798
    }
799
800
    /**
801
     * Get the language name
802
     *
803
     * @return string
804
     */
805 69
    public function getLanguageName()
806
    {
807 69
        return $this->languageName;
808
    }
809
810
    /**
811
     * Set a language name, used as prefix for translated strings
812
     *
813
     * @param string $prefix
814
     * @return $this
815
     */
816 9
    public function setLanguageName($prefix)
817
    {
818 9
        $this->languageName = (string) $prefix;
819
820 9
        return $this;
821
    }
822
823
    /**
824
     * Render the form
825
     *
826
     * @param $options
827
     * @param $fields
828
     * @param boolean $showStart
829
     * @param boolean $showFields
830
     * @param boolean $showEnd
831
     * @return string
832
     */
833 8
    protected function render($options, $fields, $showStart, $showFields, $showEnd)
834
    {
835 8
        $formOptions = $this->formHelper->mergeOptions($this->formOptions, $options);
836
837 8
        $this->setupNamedModel();
838
839 8
        return $this->formHelper->getView()
840 8
            ->make($this->getTemplate())
841 8
            ->with(compact('showStart', 'showFields', 'showEnd'))
842 8
            ->with('formOptions', $formOptions)
843 8
            ->with('fields', $fields)
844 8
            ->with('model', $this->getModel())
845 8
            ->with('exclude', $this->exclude)
846 8
            ->with('form', $this)
847 8
            ->render();
848
    }
849
850
    /**
851
     * Get template from options if provided, otherwise fallback to config
852
     *
853
     * @return mixed
854
     */
855 8
    protected function getTemplate()
856
    {
857 8
        return $this->getTemplatePrefix() . $this->getFormOption('template', $this->formHelper->getConfig('form'));
858
    }
859
860
    /**
861
     * Get all fields that are not rendered
862
     *
863
     * @return array
864
     */
865 2
    protected function getUnrenderedFields()
866
    {
867 2
        $unrenderedFields = [];
868
869 2
        foreach ($this->fields as $field) {
870 2
            if (!$field->isRendered()) {
871 2
                $unrenderedFields[] = $field;
872 2
                continue;
873
            }
874
        }
875
876 2
        return $unrenderedFields;
877
    }
878
879
    /**
880
     * Prevent adding fields with same name
881
     *
882
     * @param string $name
883
     */
884 38
    protected function preventDuplicate($name)
885
    {
886 38
        if ($this->has($name)) {
887 1
            throw new \InvalidArgumentException('Field ['.$name.'] already exists in the form '.get_class($this));
888
        }
889 38
    }
890
891
    /**
892
     * @param string $type
893
     * @return string
894
     */
895 42
    protected function getFieldType($type)
896
    {
897 42
        $fieldType = $this->formHelper->getFieldType($type);
898
899 41
        return $fieldType;
900
    }
901
902
    /**
903
     * Check if form is named form
904
     */
905 90
    protected function checkIfNamedForm()
906
    {
907 90
        if ($this->getFormOption('name')) {
908 5
            $this->name = array_pull($this->formOptions, 'name', $this->name);
909
        }
910 90
    }
911
912
    /**
913
     * Set up options on single field depending on form options
914
     *
915
     * @param string $name
916
     * @param $options
917
     */
918 42
    protected function setupFieldOptions($name, &$options)
919
    {
920 42
        $options['real_name'] = $name;
921 42
    }
922
923
    /**
924
     * Set namespace to model if form is named so the data is bound properly
925
     * Returns true if model is changed, otherwise false
926
     *
927
     * @return bool
928
     */
929 26
    protected function setupNamedModel()
930
    {
931 26
        if (!$this->getModel() || !$this->getName()) {
932 25
            return false;
933
        }
934
935 4
        $dotName = $this->formHelper->transformToDotSyntax($this->getName());
936 4
        $model = $this->formHelper->convertModelToArray($this->getModel());
937
938 4
        if (!array_get($model, $dotName)) {
939 4
            $newModel = [];
940 4
            array_set($newModel, $dotName, $model);
941 4
            $this->model = $newModel;
942
943 4
            return true;
944
        }
945
946 3
        return false;
947
    }
948
949
950
    /**
951
     * Set form builder instance on helper so we can use it later
952
     *
953
     * @param FormBuilder $formBuilder
954
     * @return $this
955
     */
956 90
    public function setFormBuilder(FormBuilder $formBuilder)
957
    {
958 90
        $this->formBuilder = $formBuilder;
959
960 90
        return $this;
961
    }
962
963
    /**
964
     * @return FormBuilder
965
     */
966 9
    public function getFormBuilder()
967
    {
968 9
        return $this->formBuilder;
969
    }
970
971
    /**
972
     * @param ValidatorFactory $validator
973
     * @return $this
974
     */
975 90
    public function setValidator(ValidatorFactory $validator)
976
    {
977 90
        $this->validatorFactory = $validator;
978
979 90
        return $this;
980
    }
981
982
    /**
983
     * Exclude some fields from rendering
984
     *
985
     * @return $this
986
     */
987
    public function exclude(array $fields)
988
    {
989
        $this->exclude = array_merge($this->exclude, $fields);
990
991
        return $this;
992
    }
993
994
995
    /**
996
     * If form is named form, modify names to be contained in single key (parent[child_field_name])
997
     *
998
     * @param string $name
999
     * @return string
1000
     */
1001 42
    protected function getFieldName($name)
1002
    {
1003 42
        if ($this->getName() !== null) {
1004 10
            return $this->getName().'['.$name.']';
1005
        }
1006
1007 42
        return $name;
1008
    }
1009
1010
    /**
1011
     * Disable all fields in a form
1012
     */
1013 1
    public function disableFields()
1014
    {
1015 1
        foreach ($this->fields as $field) {
1016 1
            $field->disable();
1017
        }
1018 1
    }
1019
1020
    /**
1021
     * Enable all fields in a form
1022
     */
1023 1
    public function enableFields()
1024
    {
1025 1
        foreach ($this->fields as $field) {
1026 1
            $field->enable();
1027
        }
1028 1
    }
1029
1030
    /**
1031
     * Validate the form
1032
     *
1033
     * @param array $validationRules
1034
     * @param array $messages
1035
     * @return Validator
1036
     */
1037 4
    public function validate($validationRules = [], $messages = [])
1038
    {
1039 4
        $fieldRules = $this->formHelper->mergeFieldsRules($this->fields);
1040 4
        $rules = array_merge($fieldRules['rules'], $validationRules);
1041 4
        $messages = array_merge($fieldRules['error_messages'], $messages);
1042
1043 4
        $this->validator = $this->validatorFactory->make($this->getRequest()->all(), $rules, $messages);
1044 4
        $this->validator->setAttributeNames($fieldRules['attributes']);
1045
1046 4
        return $this->validator;
1047
    }
1048
1049
    /**
1050
     * Get validatdion rules for the form
1051
     *
1052
     * @param array $overrideRules
1053
     * @return array
1054
     */
1055 1
    public function getRules($overrideRules = [])
1056
    {
1057 1
        $fieldRules = $this->formHelper->mergeFieldsRules($this->fields);
1058
1059 1
        return array_merge($fieldRules['rules'], $overrideRules);
1060
    }
1061
1062
    /**
1063
     * Check if the form is valid
1064
     *
1065
     * @return bool
1066
     */
1067 4
    public function isValid()
1068
    {
1069 4
        if (!$this->validator) {
1070 3
            $this->validate();
1071
        }
1072
1073 4
        return !$this->validator->fails();
1074
    }
1075
1076
    /**
1077
     * Get validation errors
1078
     *
1079
     * @return array
1080
     */
1081 4
    public function getErrors()
1082
    {
1083 4
        if (!$this->validator || !$this->validator instanceof Validator) {
1084 1
            throw new \InvalidArgumentException(
1085
                sprintf(
1086 1
                    'Form %s was not validated. To validate it, call "isValid" method before retrieving the errors',
1087
                    get_class($this)
1088
                )
1089
            );
1090
        }
1091
1092 3
        return $this->validator->getMessageBag()->getMessages();
1093
    }
1094
1095
    /**
1096
     * Throw an exception indicating a field does not exist on the class
1097
     *
1098
     * @param string $name
1099
     * @throws \InvalidArgumentException
1100
     */
1101 2
    protected function fieldDoesNotExist($name)
1102
    {
1103 2
        throw new \InvalidArgumentException('Field ['.$name.'] does not exist in '.get_class($this));
1104
    }
1105
}
1106