Passed
Pull Request — master (#650)
by Loz
04:12
created

src/Forms/EditFormFactory.php (1 issue)

Severity
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
$contentField is of type SilverStripe\Forms\HTMLEditor\HTMLEditorField, thus it always evaluated to true.
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
        $fieldsToNamespace = $fields->dataFields();
57
        $fieldsToNamespace[] = $fields->fieldByName('Root.Main.Title');
58
59
        foreach ($fieldsToNamespace as $field) {
60
            $namespacedName = sprintf(self::FIELD_NAMESPACE_TEMPLATE, $elementID, $field->getName());
61
            $field->setName($namespacedName);
62
        }
63
    }
64
}
65