In my application, the user can create custom fields for some objects, and then set values for these custom fields for each entity object when the form is displayed.
The implementation is as follows:
1º) I created an interface for the forms and forms that I want to implement in this interface.
2º) I created a form extension for all forms:
app_core_form_builder.form_extension:
class: App\Core\Bundle\FormBuilderBundle\Form\FormExtension
arguments: ["@service_container", "@doctrine.orm.entity_manager"]
tags:
- { name: form.type_extension, alias: form }
3º) In this extension, if the form implements the interface specified in step 1, I add EventSubscriber:
if($formType instanceof \App\Core\Bundle\FormBuilderBundle\Model\IAllowCustomFieldsdInterface){
$builder->addEventSubscriber(new FormSubscriber($this->container, $this->em));
}
4º) preSetData FormEvent. Entity, , .
Symfony2.
, , . , , , , .
public function preSetData(FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
$formEntity = $form->getConfig()->getType()->getInnerType()->getEntity();
$DbEntity = $this->em->getRepository('AppCoreSchemaBundle:DbEntity')->findOneBy(array('id' => $formEntity));
if ($DbEntity && $DbEntity->getAllowCustomFields()) {
$organization = $this->container->get('app_user.user_manager')->getCurrentOrganization();
if (!$organization) {
throw $this->createNotFoundException('Unable to find Organization entity.');
}
$params = array(
'organization' => $organization,
'entity' => $DbEntity,
);
$entities = $this->em->getRepository('AppCoreSchemaBundle:DbCustomField')->getAll($params);
foreach ($entities as $customField) {
FieldConfiguration::configurate($customField, $form);
if ($data->getId()) {
$filters = array(
'custom_field' => $customField,
'object' => $data->getId(),
);
$DbCustomFieldValue = $this->em->getRepository('UebCoreSchemaBundle:DbCustomFieldValue')->getFieldValue($filters);
if ($DbCustomFieldValue) {
$form[$customField->getFieldAlias()]->setData($DbCustomFieldValue->getValue());
} else {
$form[$customField->getFieldAlias()]->setData(array());
}
}
}
}
}
, . , , " " .
, , , $form [field_alias '] → setData (, , Array).
, . , .
- , ? preSetData?
EDITED
Entity DbCustomField :
/**
* @var string
*
* @ORM\Column(name="value", type="array", nullable=true)
*/
protected $value;
`
var_dump($DbCustomFieldValue) → (Ueb\Core\Bundle\SchemaBundle\Entity\DbCustomFieldValue)
var_dump(DbCustomFieldValue->getValue())
- > string (11) "bruno valor"
- :
var_dump($customField->getFieldAlias());= (21) "testebruno-1383147874"
$form[$customField->getFieldAlias()]->setData('example1'); .
, :
$form['testebruno-1383147874']->setData('example2');
- >
?