Completed
Push — master ( b0b5e0...18cf69 )
by Kristijan
07:07
created

Form::getFormOption()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

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