Skip to content

[Autocomplete] Fix loading autocomplete choices with ID value objects #494

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 7, 2022
Merged
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
1 change: 1 addition & 0 deletions src/Autocomplete/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"symfony/security-bundle": "^5.4|^6.0",
"symfony/security-csrf": "^5.4|^6.0",
"symfony/twig-bundle": "^5.4|^6.0",
"symfony/uid": "^5.4|^6.0",
"zenstruck/browser": "^1.1",
"zenstruck/foundry": "^1.19"
},
Expand Down
35 changes: 32 additions & 3 deletions src/Autocomplete/src/Form/AutocompleteEntityTypeSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@

namespace Symfony\UX\Autocomplete\Form;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\Parameter;
use Doctrine\ORM\Utility\PersisterHelper;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
Expand Down Expand Up @@ -53,9 +57,34 @@ public function preSubmit(FormEvent $event)
if (!isset($data['autocomplete']) || '' === $data['autocomplete']) {
$options['choices'] = [];
} else {
$options['choices'] = $options['em']->getRepository($options['class'])->findBy([
$options['id_reader']->getIdField() => $data['autocomplete'],
]);
/** @var EntityManagerInterface $em */
$em = $options['em'];
$repository = $em->getRepository($options['class']);

$idField = $options['id_reader']->getIdField();
$idType = PersisterHelper::getTypeOfField($idField, $em->getClassMetadata($options['class']), $em)[0];

if ($options['multiple']) {
$params = [];
$idx = 0;

foreach ($data['autocomplete'] as $id) {
$params[":id_$idx"] = new Parameter("id_$idx", $id, $idType);
++$idx;
}

$options['choices'] = $repository->createQueryBuilder('o')
->where(sprintf("o.$idField IN (%s)", implode(', ', array_keys($params))))
->setParameters(new ArrayCollection($params))
->getQuery()
->getResult();
} else {
$options['choices'] = $repository->createQueryBuilder('o')
->where("o.$idField = :id")
->setParameter('id', $data['autocomplete'], $idType)
->getQuery()
->getResult();
}
}

// reset some critical lazy options
Expand Down
53 changes: 53 additions & 0 deletions src/Autocomplete/tests/Fixtures/Entity/Ingredient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace Symfony\UX\Autocomplete\Tests\Fixtures\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\UuidV4;

#[ORM\Entity()]
class Ingredient
{
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'NONE')]
#[ORM\Column(type: 'uuid')]
private UuidV4 $id;

#[ORM\Column()]
private ?string $name = null;

#[ORM\ManyToOne(inversedBy: 'ingredients')]
private Product $product;

public function __construct(UuidV4 $id)
{
$this->id = $id;
}

public function getId(): UuidV4
{
return $this->id;
}

public function getName(): ?string
{
return $this->name;
}

public function setName(string $name): self
{
$this->name = $name;

return $this;
}

public function setProduct(?Product $product): void
{
$this->product = $product;
}

public function getProduct(): ?Product
{
return $this->product;
}
}
41 changes: 40 additions & 1 deletion src/Autocomplete/tests/Fixtures/Entity/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

namespace Symfony\UX\Autocomplete\Tests\Fixtures\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints\NotBlank;

#[ORM\Entity()]
class Product
Expand All @@ -30,6 +31,14 @@ class Product
#[ORM\JoinColumn(nullable: false)]
private ?Category $category = null;

#[Orm\OneToMany(targetEntity: Ingredient::class, mappedBy: 'product')]
private Collection $ingredients;

public function __construct()
{
$this->ingredients = new ArrayCollection();
}

public function getId(): ?int
{
return $this->id;
Expand Down Expand Up @@ -94,4 +103,34 @@ public function setCategory(?Category $category): self

return $this;
}

/**
* @return Collection<int, Ingredient>
*/
public function getIngredients(): Collection
{
return $this->ingredients;
}

public function addIngredient(Ingredient $ingredient): self
{
if (!$this->ingredients->contains($ingredient)) {
$this->ingredients[] = $ingredient;
$ingredient->setProduct($this);
}

return $this;
}

public function removeIngredient(Ingredient $ingredient): self
{
if ($this->ingredients->removeElement($ingredient)) {
// set the owning side to null (unless already changed)
if ($ingredient->getProduct() === $this) {
$ingredient->setProduct(null);
}
}

return $this;
}
}
49 changes: 49 additions & 0 deletions src/Autocomplete/tests/Fixtures/Factory/IngredientFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace Symfony\UX\Autocomplete\Tests\Fixtures\Factory;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Uid\UuidV4;
use Symfony\UX\Autocomplete\Tests\Fixtures\Entity\Ingredient;
use Zenstruck\Foundry\RepositoryProxy;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Proxy;

/**
* @extends ModelFactory<Ingredient>
*
* @method static Ingredient|Proxy createOne(array $attributes = [])
* @method static Ingredient[]|Proxy[] createMany(int $number, array|callable $attributes = [])
* @method static Ingredient|Proxy find(object|array|mixed $criteria)
* @method static Ingredient|Proxy findOrCreate(array $attributes)
* @method static Ingredient|Proxy first(string $sortedField = 'id')
* @method static Ingredient|Proxy last(string $sortedField = 'id')
* @method static Ingredient|Proxy random(array $attributes = [])
* @method static Ingredient|Proxy randomOrCreate(array $attributes = []))
* @method static Ingredient[]|Proxy[] all()
* @method static Ingredient[]|Proxy[] findBy(array $attributes)
* @method static Ingredient[]|Proxy[] randomSet(int $number, array $attributes = []))
* @method static Ingredient[]|Proxy[] randomRange(int $min, int $max, array $attributes = []))
* @method static EntityRepository|RepositoryProxy repository()
* @method Ingredient|Proxy create(array|callable $attributes = [])
*/
final class IngredientFactory extends ModelFactory
{
protected function getDefaults(): array
{
return [
'id' => new UuidV4(),
'name' => self::faker()->text(),
];
}

protected function initialize(): self
{
return $this;
}

protected static function getClass(): string
{
return Ingredient::class;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Symfony\UX\Autocomplete\Tests\Fixtures\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\UX\Autocomplete\Form\AsEntityAutocompleteField;
use Symfony\UX\Autocomplete\Form\ParentEntityAutocompleteType;
use Symfony\UX\Autocomplete\Tests\Fixtures\Entity\Ingredient;

#[AsEntityAutocompleteField]
class IngredientAutocompleteType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'class' => Ingredient::class,
'choice_label' => function(Ingredient $ingredient) {
return '<strong>'.$ingredient->getName().'</strong>';
},
'multiple' => true,
]);
}

public function getParent(): string
{
return ParentEntityAutocompleteType::class;
}
}
1 change: 1 addition & 0 deletions src/Autocomplete/tests/Fixtures/Form/ProductType.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('category', CategoryAutocompleteType::class)
->add('ingredients', IngredientAutocompleteType::class)
->add('portionSize', ChoiceType::class, [
'choices' => [
'extra small <span>🥨</span>' => 'xs',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\UX\Autocomplete\Tests\Fixtures\Factory\CategoryFactory;
use Symfony\UX\Autocomplete\Tests\Fixtures\Factory\IngredientFactory;
use Zenstruck\Browser\Test\HasBrowser;
use Zenstruck\Foundry\Test\Factories;
use Zenstruck\Foundry\Test\ResetDatabase;
Expand Down Expand Up @@ -60,4 +61,34 @@ public function testCategoryFieldSubmitsCorrectly()
->assertContains('First cat')
;
}

public function testProperlyLoadsChoicesWithIdValueObjects()
{
$ingredient1 = IngredientFactory::createOne(['name' => 'Flour']);
$ingredient2 = IngredientFactory::createOne(['name' => 'Sugar']);

$this->browser()
->throwExceptions()
->get('/test-form')
->assertElementCount('#product_ingredients_autocomplete option', 0)
->assertNotContains('Flour')
->assertNotContains('Sugar')
->post('/test-form', [
'body' => [
'product' => [
'ingredients' => [
'autocomplete' => [
(string) $ingredient1->getId(),
(string) $ingredient2->getId(),
],
],
],
],
])
// assert that selected options are not lost
->assertElementCount('#product_ingredients_autocomplete option', 2)
->assertContains('Flour')
->assertContains('Sugar')
;
}
}