Skip to content

Instantly share code, notes, and snippets.

@cordoval
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cordoval/3839b6014f0d945b01ef to your computer and use it in GitHub Desktop.
Save cordoval/3839b6014f0d945b01ef to your computer and use it in GitHub Desktop.
class FormFieldManager
{
/**
* Recria fields com rebra de bloqueio.
*
* @param FormInterface $sourceForm
* @param FormInterface $child
*/
public function rebuildChild(FormInterface $sourceForm, FormInterface $child)
{
$iterator = $child->all();
foreach ($iterator as $name => $child) {
$type = $child->getConfig()->getType()->getName();
if ($child->all() && !in_array($type, array('choice'))) {
$subSource = $sourceForm->get($name);
$this->rebuildChild($subSource, $child);
} else {
$this->lockFormField($name, $sourceForm, $child);
}
}
}
/**
* Efetua o bloqueio de field preenchidos
*
* @param $name
* @param FormInterface $form
* @param FormInterface $child
*/
public function lockFormField($name, FormInterface $form, FormInterface $child)
{
$form->remove($name);
$options = $child->getConfig()->getOptions();
$dataModel = $child->getData();
$dataView = $child->getViewData();
if (!is_null($dataModel) && !empty($dataView)) {
if ($dataModel instanceof PersistentCollection) {
if ($dataModel->count()) {
$options['disabled'] = true;
}
} else {
$options['disabled'] = true;
}
}
$modelTransformer = $child->getConfig()->getModelTransformers();
$builder = $form->getConfig()->getFormFactory()->createBuilder();
if (!$modelTransformer) {
$form->add(
$name, $child->getConfig()->getType()->getName(), array_replace(array(
'property_path' => '['.$name.']',
), $options)
);
} else {
$options['auto_initialize'] = false;
$field = $builder->create(
$name, $child->getConfig()->getType()->getName(), array_replace(array(
'property_path' => '['.$name.']',
), $options));
foreach ($modelTransformer as $transformer) {
$field->addModelTransformer($transformer);
}
$form->add($field->getForm());
}
}
}
$fieldManager = $this->fieldManager;
$builder->addEventListener(FormEvents::POST_SET_DATA, function(FormEvent $event) use ($fieldManager) {
$form = $event->getForm();
$clone = clone $form;
$fieldManager->rebuildChild($form, $clone);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment