forked from FlintLabs/FormMetadataBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FormMapper.php
95 lines (80 loc) · 2.71 KB
/
FormMapper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
/*
* This file is part of the Form Metadata library
*
* (c) Cameron Manderson <camm@flintinteractive.com.au>
*
* For full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FlintLabs\Bundle\FormMetadataBundle;
use Symfony\Component\Form\FormFactory,
FlintLabs\Bundle\FormMetadataBundle\Driver\MetadataDriverInterface;
/**
* Obtains any metadata from the entity and adds it's configuration
* to the form
* @author camm (camm@flintinteractive.com.au), european(info@nils-werner.com)
*/
class FormMapper
{
/**
* Drivers that will be used to obtaining metadata
* @var array
*/
private $drivers = array();
/**
* @var \Symfony\Component\Form\FormFactory
*/
protected $factory;
/**
* @param \Symfony\Component\Form\FormFactory $factory
*/
public function __construct(FormFactory $factory)
{
$this->factory = $factory;
}
/**
* Obtains any form metadata from the entity and adds itself to the form
* @param $entity
* @param $form
* @return
*/
public function createFormBuilder($data = null, array $options = array())
{
// Build the $form
$formBuilder = $this->factory->createBuilder('form', $data, $options);
// Read the entity meta data and add to the form
if(empty($this->drivers)) return $formBuilder;
// Look to the readers to find metadata
foreach ($this->drivers as $driver) {
$metadata = $driver->getMetadata($data);
if(!empty($metadata)) break;
}
if(empty($metadata)) return $formBuilder;
// Configure the form
$fields = $metadata->getFields();
foreach($fields as $field) {
// TODO: Detect "new x()" in field value or type option for AbstractType creation
// TODO: Detect references to "%service.id%" for service constructor dependency
$formBuilder->add($field->name, $field->value, $field->options);
}
$groups = $metadata->getGroups();
foreach($groups as $groupName => $fields) {
$builder = $formBuilder->create($groupName, 'form', array('virtual' => true));
foreach($fields as $field) {
$builder->add($field->name, $field->value, $field->options);
}
$formBuilder->add($builder);
}
return $formBuilder;
}
/**
* Add an entity metadata reader to the readers
* @param EntityMetadataReaderInterface $reader
* @return void
*/
public function addDriver(MetadataDriverInterface $driver)
{
$this->drivers[] = $driver;
}
}