Skip to content

Commit

Permalink
Merge pull request #80 from tetranz/tag-submit-fix
Browse files Browse the repository at this point in the history
Fix resubmit for new tagged entities.
  • Loading branch information
tetranz authored Apr 18, 2017
2 parents fff2fea + 8a1f9e9 commit c22c34c
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Form/Type/Select2EntityType.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Routing\RouterInterface;
use Tetranz\Select2EntityBundle\Form\DataTransformer\EntitiesToPropertyTransformer;
use Tetranz\Select2EntityBundle\Form\DataTransformer\EntityToPropertyTransformer;
Expand Down Expand Up @@ -107,6 +108,41 @@ public function finishView(FormView $view, FormInterface $form, array $options)
}
}

if ($view->vars['allow_add']['enabled'] && $form->isSubmitted()) {
// Form is being displayed again after a submit that failed validation.
// $view->vars['value'] needs to be rebuilt to handle new entities added with a tag.

// get entities as iterable collection or array.
$entities = $options['multiple'] ? $form->getData() : [$form->getData()];

$accessor = PropertyAccess::createPropertyAccessor();
$textProperty = isset($options['text_property']) ? $options['text_property'] : null;
$newTagPrefix = $view->vars['allow_add']['new_tag_prefix'];

$view->vars['value'] = [];

foreach ($entities as $entity) {
// Get text value
$text = is_null($textProperty)
? (string) $entity
: $accessor->getValue($entity, $textProperty);

// Get choice field (primary key).
$choiceFieldValue = $accessor->getValue($entity, $options['primary_key']);

if (!$this->em->contains($entity)) {
// This is a new entity, added via a tag, not persisted yet.
// A new entity may or may not already have a non-null choice field.
// If the new entity already has a choice field, use it, otherwise use the text field.
$choiceFieldValue = $newTagPrefix . ($choiceFieldValue ? : $text);

$text .= $view->vars['allow_add']['new_tag_text'];
}

$view->vars['value'][$choiceFieldValue] = $text;
}
}

if ($options['multiple']) {
$view->vars['full_name'] .= '[]';
}
Expand Down

0 comments on commit c22c34c

Please sign in to comment.