Skip to content

Commit 4251a87

Browse files
committed
Add choice_label support to CrudAutocompleteType
When using EntityFilter with autocomplete() and a custom choice_label, the form crashed because CrudAutocompleteType did not define choice_label as a valid option. Changes: - Add choice_label option to CrudAutocompleteType - Preserve user-defined choice_label in CrudAutocompleteSubscriber Fix #7462
1 parent 640e870 commit 4251a87

2 files changed

Lines changed: 17 additions & 10 deletions

File tree

src/Form/EventListener/CrudAutocompleteSubscriber.php

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -48,16 +48,20 @@ public function preSetData(FormEvent $event)
4848
// the renderAsHtml flag controls how TomSelect renders the item (via data-ea-autocomplete-render-items-as-html).
4949
$callback = $options['autocomplete_callback'] ?? null;
5050
$template = $options['autocomplete_template'] ?? null;
51-
52-
if (null !== $template) {
53-
$twig = $this->twig;
54-
$options['choice_label'] = static function ($entity) use ($twig, $template): string {
55-
return $twig->render($template, ['entity' => $entity]);
56-
};
57-
} elseif (null !== $callback) {
58-
$options['choice_label'] = static function ($entity) use ($callback): string {
59-
return (string) $callback($entity);
60-
};
51+
$choiceLabel = $options['choice_label'] ?? null;
52+
53+
// only generate choice_label from template/callback if not already set by the user
54+
if (null === $choiceLabel) {
55+
if (null !== $template) {
56+
$twig = $this->twig;
57+
$options['choice_label'] = static function ($entity) use ($twig, $template): string {
58+
return $twig->render($template, ['entity' => $entity]);
59+
};
60+
} elseif (null !== $callback) {
61+
$options['choice_label'] = static function ($entity) use ($callback): string {
62+
return (string) $callback($entity);
63+
};
64+
}
6165
}
6266

6367
// remove custom options before passing to EntityType

src/Form/Type/CrudAutocompleteType.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,14 @@ public function configureOptions(OptionsResolver $resolver): void
4848
// options for custom rendering of selected items (to match the rendering of the other entries in the dropdown)
4949
'autocomplete_callback' => null,
5050
'autocomplete_template' => null,
51+
// allow choice_label to customize how selected items are displayed
52+
'choice_label' => null,
5153
]);
5254

5355
$resolver->setRequired(['class']);
5456
$resolver->setAllowedTypes('autocomplete_callback', ['null', 'callable']);
5557
$resolver->setAllowedTypes('autocomplete_template', ['null', 'string']);
58+
$resolver->setAllowedTypes('choice_label', ['null', 'string', 'callable', 'bool']);
5659
}
5760

5861
public function getBlockPrefix(): string

0 commit comments

Comments
 (0)