Completed
Push — master ( 74f120...db766c )
by
unknown
11s
created

EditFormFactory::namespaceFields()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace DNADesign\Elemental\Forms;
4
5
use SilverStripe\Control\RequestHandler;
6
use SilverStripe\Forms\DefaultFormFactory;
7
use SilverStripe\Forms\FieldList;
8
use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
9
10
class EditFormFactory extends DefaultFormFactory
11
{
12
    /**
13
     * @var string
14
     */
15
    const FIELD_NAMESPACE_TEMPLATE = 'PageElements_%d_%s';
16
17
    public function getForm(RequestHandler $controller = null, $name = self::DEFAULT_NAME, $context = [])
18
    {
19
        $form = parent::getForm($controller, $name, $context);
20
21
        // Remove divider lines between form fields
22
        $form->addExtraClass('form--no-dividers');
23
24
        // Namespace all fields - do this after getting getFormFields so they still get populated
25
        $formFields = $form->Fields();
26
        $this->namespaceFields($formFields, $context);
27
        $form->setFields($formFields);
28
29
        return $form;
30
    }
31
32
    protected function getFormFields(RequestHandler $controller = null, $name, $context = [])
33
    {
34
        $fields = parent::getFormFields($controller, $name, $context);
35
36
        /** @var HTMLEditorField $contentField */
37
        $contentField = $fields->fieldByName('Root.Main.HTML');
38
        if ($contentField) {
0 ignored issues
show
introduced by
$contentField is of type SilverStripe\Forms\HTMLEditor\HTMLEditorField, thus it always evaluated to true. If $contentField can have other possible types, add them to src/Forms/EditFormFactory.php:36
Loading history...
39
            $contentField->setRows(5);
40
        }
41
42
        return $fields;
43
    }
44
45
    /**
46
     * Given a {@link FieldList}, give all fields a unique name so they can be used in the same context as
47
     * other elemental edit forms and the page (or other DataObject) that owns them.
48
     *
49
     * @param FieldList $fields
50
     * @param array $context
51
     */
52
    protected function namespaceFields(FieldList $fields, array $context)
53
    {
54
        $elementID = $context['Record']->ID;
55
56
        foreach ($fields->dataFields() as $field) {
57
            $namespacedName = sprintf(self::FIELD_NAMESPACE_TEMPLATE, $elementID, $field->getName());
58
            $field->setName($namespacedName);
59
        }
60
    }
61
}
62