Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions src/Form/EventListener/CrudAutocompleteSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,20 @@ public function preSetData(FormEvent $event)
// the renderAsHtml flag controls how TomSelect renders the item (via data-ea-autocomplete-render-items-as-html).
$callback = $options['autocomplete_callback'] ?? null;
$template = $options['autocomplete_template'] ?? null;

if (null !== $template) {
$twig = $this->twig;
$options['choice_label'] = static function ($entity) use ($twig, $template): string {
return $twig->render($template, ['entity' => $entity]);
};
} elseif (null !== $callback) {
$options['choice_label'] = static function ($entity) use ($callback): string {
return (string) $callback($entity);
};
$choiceLabel = $options['choice_label'] ?? null;

// only generate choice_label from template/callback if not already set by the user
if (null === $choiceLabel) {
if (null !== $template) {
$twig = $this->twig;
$options['choice_label'] = static function ($entity) use ($twig, $template): string {
return $twig->render($template, ['entity' => $entity]);
};
} elseif (null !== $callback) {
$options['choice_label'] = static function ($entity) use ($callback): string {
return (string) $callback($entity);
};
}
}

// remove custom options before passing to EntityType
Expand All @@ -66,6 +70,12 @@ public function preSetData(FormEvent $event)
$options['autocomplete_template']
);

// Don't pass null choice_label to EntityType - let it use __toString() default
// (passing null explicitly behaves differently than omitting the option in Symfony < 8.1)
if (null === ($options['choice_label'] ?? null)) {
unset($options['choice_label']);
}

$form->add('autocomplete', EntityType::class, $options);
}

Expand Down
3 changes: 3 additions & 0 deletions src/Form/Type/CrudAutocompleteType.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,14 @@ public function configureOptions(OptionsResolver $resolver): void
// options for custom rendering of selected items (to match the rendering of the other entries in the dropdown)
'autocomplete_callback' => null,
'autocomplete_template' => null,
// allow choice_label to customize how selected items are displayed
'choice_label' => null,
]);

$resolver->setRequired(['class']);
$resolver->setAllowedTypes('autocomplete_callback', ['null', 'callable']);
$resolver->setAllowedTypes('autocomplete_template', ['null', 'string']);
$resolver->setAllowedTypes('choice_label', ['null', 'string', 'callable', 'bool']);
}

public function getBlockPrefix(): string
Expand Down
Loading