Completed
Push — master ( c8f949...0179c6 )
by Kristijan
04:17
created

Form::addData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6
Metric Value
dl 0
loc 8
ccs 0
cts 0
cp 0
rs 9.4286
cc 2
eloc 4
nc 2
nop 1
crap 6
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
     * Build the form
109
     *
110
     * @return mixed
111
     */
112 2
    public function buildForm()
113
    {
114 2
    }
115
116
    /**
117
     * Rebuild the form from scratch
118
     *
119
     * @return $this
120
     */
121 17
    public function rebuildForm()
122
    {
123 17
        $this->rebuilding = true;
124
        // If form is plain, buildForm method is empty, so we need to take
125
        // existing fields and add them again
126 17
        if (get_class($this) === 'Kris\LaravelFormBuilder\Form') {
127 14
            foreach ($this->fields as $name => $field) {
128 4
                $this->add($name, $field->getType(), $field->getOptions());
129 14
            }
130 14
        } else {
131 7
            $this->buildForm();
132
        }
133 17
        $this->rebuilding = false;
134
135 17
        return $this;
136
    }
137
138
    /**
139
     * Create the FormField object
140
     *
141
     * @param string $name
142
     * @param string $type
143
     * @param array  $options
144
     * @return FormField
145
     */
146 36
    protected function makeField($name, $type = 'text', array $options = [])
147
    {
148 36
        $this->setupFieldOptions($name, $options);
149
150 36
        $fieldName = $this->getFieldName($name);
151
152 36
        $fieldType = $this->getFieldType($type);
153
154 35
        return new $fieldType($fieldName, $type, $this, $options);
155
    }
156
157
    /**
158
     * Create a new field and add it to the form
159
     *
160
     * @param string $name
161
     * @param string $type
162
     * @param array  $options
163
     * @param bool   $modify
164
     * @return $this
165
     */
166 37
    public function add($name, $type = 'text', array $options = [], $modify = false)
167
    {
168 37
        if (!$name || trim($name) == '') {
169 1
            throw new \InvalidArgumentException(
170 1
                'Please provide valid field name for class ['. get_class($this) .']'
171 1
            );
172
        }
173
174 36
        if ($this->rebuilding && !$this->has($name)) {
175 4
            return $this;
176
        }
177
178 36
        $this->addField($this->makeField($name, $type, $options), $modify);
179
180 32
        return $this;
181
    }
182
183
    /**
184
     * Add a FormField to the form's fields
185
     *
186
     * @param FormField $field
187
     * @return $this
188
     */
189 32
    protected function addField(FormField $field, $modify = false)
190
    {
191 32
        if (!$modify && !$this->rebuilding) {
192 32
            $this->preventDuplicate($field->getRealName());
193 32
        }
194
195
196 32
        if ($field->getType() == 'file') {
197 3
            $this->formOptions['files'] = true;
198 3
        }
199
200 32
        $this->fields[$field->getRealName()] = $field;
201
202 32
        return $this;
203
    }
204
205
    /**
206
     * Add field before another field
207
     *
208
     * @param string  $name         Name of the field before which new field is added
209
     * @param string  $fieldName    Field name which will be added
210
     * @param string  $type
211
     * @param array   $options
212
     * @param boolean $modify
213
     * @return $this
214
     */
215 1
    public function addBefore($name, $fieldName, $type = 'text', $options = [], $modify = false)
216
    {
217 1
        $offset = array_search($name, array_keys($this->fields));
218
219 1
        $beforeFields = array_slice($this->fields, 0, $offset);
220 1
        $afterFields = array_slice($this->fields, $offset);
221
222 1
        $this->fields = $beforeFields;
223
224 1
        $this->add($fieldName, $type, $options, $modify);
225
226 1
        $this->fields += $afterFields;
227
228 1
        return $this;
229
    }
230
231
    /**
232
     * Add field before another field
233
     * @param string  $name         Name of the field after which new field is added
234
     * @param string  $fieldName    Field name which will be added
235
     * @param string  $type
236
     * @param array   $options
237
     * @param boolean $modify
238
     * @return $this
239
     */
240 1
    public function addAfter($name, $fieldName, $type = 'text', $options = [], $modify = false)
241
    {
242 1
        $offset = array_search($name, array_keys($this->fields));
243
244 1
        $beforeFields = array_slice($this->fields, 0, $offset + 1);
245 1
        $afterFields = array_slice($this->fields, $offset + 1);
246
247 1
        $this->fields = $beforeFields;
248
249 1
        $this->add($fieldName, $type, $options, $modify);
250
251 1
        $this->fields += $afterFields;
252
253 1
        return $this;
254
    }
255
256
    /**
257
     * Take another form and add it's fields directly to this form
258
     * @param mixed   $class        Form to merge
259
     * @param array   $options
260
     * @param boolean $modify
261
     * @return $this
262
     */
263 1
    public function compose($class, array $options = [], $modify = false)
264
    {
265 1
        $options['class'] = $class;
266
267
        // If we pass a ready made form just extract the fields
268 1
        if ($class instanceof Form) {
269 1
            $fields = $class->getFields();
270 1
        } elseif ($class instanceof Fields\ChildFormType) {
271
            $fields = $class->getForm()->getFields();
272
        } elseif (is_string($class)) {
273
            // If its a string of a class make it the usual way
274
            $options['model'] = $this->model;
275
            $options['name'] = $this->name;
276
277
            $form = $this->formBuilder->create($class, $options);
278
            $fields = $form->getFields();
279
        } else {
280
            throw new \InvalidArgumentException(
281
                "[{$class}] is invalid. Please provide either a full class name, Form or ChildFormType"
282
            );
283
        }
284
285 1
        foreach ($fields as $field) {
286 1
            $this->addField($field, $modify);
287 1
        }
288
289 1
        return $this;
290
    }
291
292
    /**
293
     * Remove field with specified name from the form
294
     *
295
     * @param $name
296
     * @return $this
297
     */
298 3
    public function remove($name)
299
    {
300 3
        if ($this->has($name)) {
301 2
            unset($this->fields[$name]);
302 2
            return $this;
303
        }
304
305 1
        $this->fieldDoesNotExist($name);
306
    }
307
308
    /**
309
     * Modify existing field. If it doesn't exist, it is added to form
310
     *
311
     * @param        $name
312
     * @param string $type
313
     * @param array  $options
314
     * @param bool   $overwriteOptions
315
     * @return Form
316
     */
317 1
    public function modify($name, $type = 'text', array $options = [], $overwriteOptions = false)
318
    {
319
        // If we don't want to overwrite options, we merge them with old options
320 1
        if ($overwriteOptions === false && $this->has($name)) {
321 1
            $options = $this->formHelper->mergeOptions(
322 1
                $this->getField($name)->getOptions(),
323
                $options
324 1
            );
325 1
        }
326
327 1
        return $this->add($name, $type, $options, true);
328
    }
329
330
    /**
331
     * Render full form
332
     *
333
     * @param array $options
334
     * @param bool  $showStart
335
     * @param bool  $showFields
336
     * @param bool  $showEnd
337
     * @return string
338
     */
339 6
    public function renderForm(array $options = [], $showStart = true, $showFields = true, $showEnd = true)
340
    {
341 6
        return $this->render($options, $this->fields, $showStart, $showFields, $showEnd);
342
    }
343
344
    /**
345
     * Render rest of the form
346
     *
347
     * @param bool $showFormEnd
348
     * @param bool $showFields
349
     * @return string
350
     */
351 1
    public function renderRest($showFormEnd = true, $showFields = true)
352
    {
353 1
        $fields = $this->getUnrenderedFields();
354
355 1
        return $this->render([], $fields, false, $showFields, $showFormEnd);
356
    }
357
358
    /**
359
     * Renders the rest of the form up until the specified field name
360
     *
361
     * @param string $field_name
362
     * @param bool   $showFormEnd
363
     * @param bool   $showFields
364
     * @return string
365
     */
366 2
    public function renderUntil($field_name, $showFormEnd = true, $showFields = true)
367
    {
368 2
        if (!$this->has($field_name)) {
369 1
            $this->fieldDoesNotExist($field_name);
370
        }
371
372 1
        $fields = $this->getUnrenderedFields();
373
374 1
        $i = 1;
375 1
        foreach ($fields as $key => $value) {
376 1
            if ($value->getRealName() == $field_name) {
377 1
                break;
378
            }
379 1
            $i++;
380 1
        }
381
382 1
        $fields = array_slice($fields, 0, $i, true);
383
384 1
        return $this->render([], $fields, false, $showFields, $showFormEnd);
385
    }
386
387
    /**
388
     * Get single field instance from form object
389
     *
390
     * @param $name
391
     * @return FormField
392
     */
393 20
    public function getField($name)
394
    {
395 20
        if ($this->has($name)) {
396 19
            return $this->fields[$name];
397
        }
398
399 1
        $this->fieldDoesNotExist($name);
400
    }
401
402
    /**
403
     * Check if form has field
404
     *
405
     * @param $name
406
     * @return bool
407
     */
408 32
    public function has($name)
409
    {
410 32
        return array_key_exists($name, $this->fields);
411
    }
412
413
    /**
414
     * Get all form options
415
     *
416
     * @return array
417
     */
418 2
    public function getFormOptions()
419
    {
420 2
        return $this->formOptions;
421
    }
422
423
    /**
424
     * Get single form option
425
     *
426
     * @param string $option
427
     * @param $default
428
     * @return mixed
429
     */
430 81
    public function getFormOption($option, $default = null)
431
    {
432 81
        return array_get($this->formOptions, $option, $default);
433
    }
434
435
    /**
436
     * Set single form option on form
437
     *
438
     * @param string $option
439
     * @param mixed $value
440
     *
441
     * @return $this
442
     */
443 2
    public function setFormOption($option, $value)
444
    {
445 2
        $this->formOptions[$option] = $value;
446
447 2
        return $this;
448
    }
449
450
    /**
451
     * Set form options
452
     *
453
     * @param array $formOptions
454
     * @return $this
455
     */
456 81
    public function setFormOptions($formOptions)
457
    {
458 81
        $this->formOptions = $this->formHelper->mergeOptions($this->formOptions, $formOptions);
459 81
        $this->checkIfNamedForm();
460 81
        $this->pullFromOptions('model', 'setModel');
461 81
        $this->pullFromOptions('data', 'addData');
462 81
        $this->pullFromOptions('errors_enabled', 'setErrorsEnabled');
463 81
        $this->pullFromOptions('client_validation', 'setClientValidationEnabled');
464 81
        $this->pullFromOptions('template_prefix', 'setTemplatePrefix');
465
466 81
        return $this;
467
    }
468
469
    /**
470
     * Get an option from provided options and call method with that value
471
     *
472
     * @param $name
473
     * @param $method
474
     */
475 81
    protected function pullFromOptions($name, $method)
476
    {
477 81
        if (array_get($this->formOptions, $name) !== null) {
478 11
            $this->{$method}(array_pull($this->formOptions, $name));
479 11
        }
480 81
    }
481
482
    /**
483
     * Get form http method
484
     *
485
     * @return string
486
     */
487 3
    public function getMethod()
488
    {
489 3
        return $this->formOptions['method'];
490
    }
491
492
    /**
493
     * Set form http method
494
     *
495
     * @param string $method
496
     * @return $this
497
     */
498 1
    public function setMethod($method)
499
    {
500 1
        $this->formOptions['method'] = $method;
501
502 1
        return $this;
503
    }
504
505
    /**
506
     * Get form action url
507
     *
508
     * @return string
509
     */
510 3
    public function getUrl()
511
    {
512 3
        return $this->formOptions['url'];
513
    }
514
515
    /**
516
     * Set form action url
517
     *
518
     * @param string $url
519
     * @return $this
520
     */
521 1
    public function setUrl($url)
522
    {
523 1
        $this->formOptions['url'] = $url;
524
525 1
        return $this;
526
    }
527
528
    /**
529
     * @return string|null
530
     */
531 41
    public function getName()
532
    {
533 41
        return $this->name;
534
    }
535
536
    /**
537
     * @param string $name
538
     * @param bool $rebuild
539
     *
540
     * @return $this
541
     */
542 5
    public function setName($name, $rebuild = true)
543
    {
544 5
        $this->name = $name;
545
546 5
        if ($rebuild) {
547 5
            $this->rebuildForm();
548 5
        }
549
550 5
        return $this;
551
    }
552
553
    /**
554
     * Get model that is bind to form object
555
     *
556
     * @return mixed
557
     */
558 58
    public function getModel()
559
    {
560 58
        return $this->model;
561
    }
562
563
    /**
564
     * Set model to form object
565
     *
566
     * @param mixed $model
567
     * @return $this
568
     * @deprecated deprecated since 1.6.31, will be removed in 1.7 - pass model as option when creating a form
569
     */
570
    public function setModel($model)
571
    {
572
        $this->model = $model;
573
574
        $this->setupNamedModel();
575
576
        $this->rebuildForm();
577
578
        return $this;
579
    }
580
581
    /**
582
     * Get all fields
583
     *
584
     * @return FormField[]
585
     */
586 14
    public function getFields()
587
    {
588 14
        return $this->fields;
589
    }
590
591
    /**
592
     * Get field dynamically
593
     *
594
     * @param $name
595
     * @return FormField
596
     */
597 15
    public function __get($name)
598
    {
599 15
        if ($this->has($name)) {
600 14
            return $this->getField($name);
601
        }
602 3
    }
603
604
    /**
605
     * Set the form helper only on first instantiation
606
     *
607
     * @param FormHelper $formHelper
608
     * @return $this
609
     */
610 81
    public function setFormHelper(FormHelper $formHelper)
611
    {
612 81
        $this->formHelper = $formHelper;
613
614 81
        return $this;
615
    }
616
617
    /**
618
     * Get form helper
619
     *
620
     * @return FormHelper
621
     */
622 62
    public function getFormHelper()
623
    {
624 62
        return $this->formHelper;
625
    }
626
627
    /**
628
     * Add custom field
629
     *
630
     * @param $name
631
     * @param $class
632
     */
633 2
    public function addCustomField($name, $class)
634
    {
635 2
        $this->formHelper->addCustomField($name, $class);
636 2
    }
637
638
    /**
639
     * Should form errors be shown under every field ?
640
     *
641
     * @return bool
642
     */
643 62
    public function haveErrorsEnabled()
644
    {
645 62
        return $this->showFieldErrors;
646
    }
647
648
    /**
649
     * Enable or disable showing errors under fields
650
     *
651
     * @param boolean $enabled
652
     * @return $this
653
     */
654 7
    public function setErrorsEnabled($enabled)
655
    {
656 7
        $this->showFieldErrors = (boolean) $enabled;
657
658 7
        return $this;
659
    }
660
661
    /**
662
     * Is client validation enabled?
663
     *
664
     * @return boolean
665
     */
666 62
    public function clientValidationEnabled()
667
    {
668 62
        return $this->clientValidationEnabled;
669
    }
670
671
    /**
672
     * Enable/disable client validation
673
     *
674
     * @param boolean $enable
675
     * @return $this
676
     */
677 7
    public function setClientValidationEnabled($enable)
678
    {
679 7
        $this->clientValidationEnabled = (boolean) $enable;
680
681 7
        return $this;
682
    }
683
684
    /**
685
     * Add any aditional data that field needs (ex. array of choices)
686
     *
687
     * @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
688
     * will be switched to protected in 1.7
689
     * @param string $name
690
     * @param mixed $data
691
     */
692
    public function setData($name, $data)
693
    {
694
        $this->data[$name] = $data;
695
    }
696
697
    /**
698
     * Get single additional data
699
     *
700
     * @param string $name
701
     * @param null   $default
702
     * @return mixed
703
     */
704 9
    public function getData($name = null, $default = null)
705
    {
706 9
        if (is_null($name)) {
707 8
            return $this->data;
708
        }
709
710 1
        return array_get($this->data, $name, $default);
711
    }
712
713
    /**
714
     * Add multiple peices of data at once
715
     *
716
     * @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
717
     * will be switched to protected in 1.7
718
     * @param $data
719
     * @return $this
720
     **/
721
    public function addData(array $data)
722
    {
723
        foreach ($data as $key => $value) {
724
            $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...
725
        }
726
727
        return $this;
728
    }
729
730
    /**
731
     * Get current request
732
     *
733
     * @return \Illuminate\Http\Request
734
     */
735 62
    public function getRequest()
736
    {
737 62
        return $this->request;
738
    }
739
740
    /**
741
     * Set request on form
742
     *
743
     * @param Request $request
744
     * @return $this
745
     */
746 81
    public function setRequest(Request $request)
747
    {
748 81
        $this->request = $request;
749
750 81
        return $this;
751
    }
752
753
    /**
754
     * Get template prefix that is prepended to all template paths
755
     *
756
     * @return string
757
     */
758 28
    public function getTemplatePrefix()
759
    {
760 28
        if ($this->templatePrefix !== null) {
761 4
            return $this->templatePrefix;
762
        }
763
764 24
        return $this->formHelper->getConfig('template_prefix');
765
    }
766
767
    /**
768
     * Set a template prefix for the form and its fields
769
     *
770
     * @param string $prefix
771
     * @return $this
772
     */
773 4
    public function setTemplatePrefix($prefix)
774
    {
775 4
        $this->templatePrefix = (string) $prefix;
776
777 4
        return $this;
778
    }
779
780
    /**
781
     * Render the form
782
     *
783
     * @param $options
784
     * @param $fields
785
     * @param boolean $showStart
786
     * @param boolean $showFields
787
     * @param boolean $showEnd
788
     * @return string
789
     */
790 8
    protected function render($options, $fields, $showStart, $showFields, $showEnd)
791
    {
792 8
        $formOptions = $this->formHelper->mergeOptions($this->formOptions, $options);
793
794 8
        $this->setupNamedModel();
795
796 8
        return $this->formHelper->getView()
797 8
            ->make($this->getTemplate())
798 8
            ->with(compact('showStart', 'showFields', 'showEnd'))
799 8
            ->with('formOptions', $formOptions)
800 8
            ->with('fields', $fields)
801 8
            ->with('model', $this->getModel())
802 8
            ->with('exclude', $this->exclude)
803 8
            ->with('form', $this)
804 8
            ->render();
805
    }
806
807
    /**
808
     * Get template from options if provided, otherwise fallback to config
809
     *
810
     * @return mixed
811
     */
812 8
    protected function getTemplate()
813
    {
814 8
        return $this->getTemplatePrefix() . $this->getFormOption('template', $this->formHelper->getConfig('form'));
815
    }
816
817
    /**
818
     * Get all fields that are not rendered
819
     *
820
     * @return array
821
     */
822 2
    protected function getUnrenderedFields()
823
    {
824 2
        $unrenderedFields = [];
825
826 2
        foreach ($this->fields as $field) {
827 2
            if (!$field->isRendered()) {
828 2
                $unrenderedFields[] = $field;
829 2
                continue;
830
            }
831 2
        }
832
833 2
        return $unrenderedFields;
834
    }
835
836
    /**
837
     * Prevent adding fields with same name
838
     *
839
     * @param string $name
840
     */
841 32
    protected function preventDuplicate($name)
842
    {
843 32
        if ($this->has($name)) {
844 1
            throw new \InvalidArgumentException('Field ['.$name.'] already exists in the form '.get_class($this));
845
        }
846 32
    }
847
848
    /**
849
     * @param string $type
850
     * @return string
851
     */
852 36
    protected function getFieldType($type)
853
    {
854 36
        $fieldType = $this->formHelper->getFieldType($type);
855
856 35
        return $fieldType;
857
    }
858
859
    /**
860
     * Check if form is named form
861
     */
862 81
    protected function checkIfNamedForm()
863
    {
864 81
        if ($this->getFormOption('name')) {
865 4
            $this->name = array_pull($this->formOptions, 'name', $this->name);
866 4
        }
867 81
    }
868
869
    /**
870
     * Set up options on single field depending on form options
871
     *
872
     * @param string $name
873
     * @param $options
874
     */
875 36
    protected function setupFieldOptions($name, &$options)
876
    {
877 36
        $options['real_name'] = $name;
878
879 36
        if (!$this->getName()) {
880 36
            return;
881
        }
882
883 8
        if (!isset($options['label'])) {
884 6
            $options['label'] = $this->formHelper->formatLabel($name);
885 6
        }
886 8
    }
887
888
    /**
889
     * Set namespace to model if form is named so the data is bound properly
890
     */
891 22
    protected function setupNamedModel()
892
    {
893 22
        if (!$this->getModel() || !$this->getName()) {
894 21
            return;
895
        }
896
897 3
        $dotName = $this->formHelper->transformToDotSyntax($this->getName());
898 3
        $model = $this->formHelper->convertModelToArray($this->getModel());
899
900 3
        if (!array_get($model, $dotName)) {
901 3
            $newModel = [];
902 3
            array_set($newModel, $dotName, $model);
903 3
            $this->model = $newModel;
904 3
        }
905 3
    }
906
907
908
    /**
909
     * Set form builder instance on helper so we can use it later
910
     *
911
     * @param FormBuilder $formBuilder
912
     * @return $this
913
     */
914 81
    public function setFormBuilder(FormBuilder $formBuilder)
915
    {
916 81
        $this->formBuilder = $formBuilder;
917
918 81
        return $this;
919
    }
920
921
    /**
922
     * @return FormBuilder
923
     */
924 8
    public function getFormBuilder()
925
    {
926 8
        return $this->formBuilder;
927
    }
928
929
    /**
930
     * @param ValidatorFactory $validator
931
     * @return $this
932
     */
933 81
    public function setValidator(ValidatorFactory $validator)
934
    {
935 81
        $this->validatorFactory = $validator;
936
937 81
        return $this;
938
    }
939
940
    /**
941
     * Exclude some fields from rendering
942
     *
943
     * @return $this
944
     */
945
    public function exclude(array $fields)
946
    {
947
        $this->exclude = array_merge($this->exclude, $fields);
948
949
        return $this;
950
    }
951
952
953
    /**
954
     * If form is named form, modify names to be contained in single key (parent[child_field_name])
955
     *
956
     * @param string $name
957
     * @return string
958
     */
959 36
    protected function getFieldName($name)
960
    {
961 36
        if ($this->getName() !== null) {
962 8
            return $this->getName().'['.$name.']';
963
        }
964
965 36
        return $name;
966
    }
967
968
    /**
969
     * Disable all fields in a form
970
     */
971 1
    public function disableFields()
972
    {
973 1
        foreach ($this->fields as $field) {
974 1
            $field->disable();
975 1
        }
976 1
    }
977
978
    /**
979
     * Enable all fields in a form
980
     */
981 1
    public function enableFields()
982
    {
983 1
        foreach ($this->fields as $field) {
984 1
            $field->enable();
985 1
        }
986 1
    }
987
988
    /**
989
     * Validate the form
990
     *
991
     * @param array $validationRules
992
     * @param array $messages
993
     * @return Validator
994
     */
995 3
    public function validate($validationRules = [], $messages = [])
996
    {
997 3
        $fieldRules = $this->formHelper->mergeFieldsRules($this->fields);
998 3
        $rules = array_merge($fieldRules['rules'], $validationRules);
999
1000 3
        $this->validator = $this->validatorFactory->make($this->getRequest()->all(), $rules, $messages);
1001 3
        $this->validator->setAttributeNames($fieldRules['attributes']);
1002
1003 3
        return $this->validator;
1004
    }
1005
1006
    /**
1007
     * Get validatdion rules for the form
1008
     *
1009
     * @param array $overrideRules
1010
     * @return array
1011
     */
1012 1
    public function getRules($overrideRules = [])
1013
    {
1014 1
        $fieldRules = $this->formHelper->mergeFieldsRules($this->fields);
1015
1016 1
        return array_merge($fieldRules['rules'], $overrideRules);
1017
    }
1018
1019
    /**
1020
     * Check if the form is valid
1021
     *
1022
     * @return bool
1023
     */
1024 3
    public function isValid()
1025
    {
1026 3
        if (!$this->validator) {
1027 2
            $this->validate();
1028 2
        }
1029
1030 3
        return !$this->validator->fails();
1031
    }
1032
1033
    /**
1034
     * Get validation errors
1035
     *
1036
     * @return array
1037
     */
1038 3
    public function getErrors()
1039
    {
1040 3
        if (!$this->validator || !$this->validator instanceof Validator) {
1041 1
            throw new \InvalidArgumentException(
1042 1
                sprintf(
1043 1
                    'Form %s was not validated. To validate it, call "isValid" method before retrieving the errors',
1044 1
                    get_class($this)
1045 1
                )
1046 1
            );
1047
        }
1048
1049 2
        return $this->validator->getMessageBag()->getMessages();
1050
    }
1051
1052
    /**
1053
     * Throw an exception indicating a field does not exist on the class
1054
     *
1055
     * @param string $name
1056
     * @throws \InvalidArgumentException
1057
     */
1058 3
    protected function fieldDoesNotExist($name)
1059
    {
1060 3
        throw new \InvalidArgumentException('Field ['.$name.'] does not exist in '.get_class($this));
1061
    }
1062
}
1063