I made a search form where several entities are present. I would like to keep last values entered so that when user comes back to the form, he retrieves his last choices.
By trying to do so, I retrieve myself with the following error :
Entity of type "App\Entity\BigCity" passed to the choice field must be managed. Maybe you forget to persist it in the entity manager?
When I saw this error, I added the following line : $entityManagerInterface->persist($data); but I retrieve myself with an other error :
EntityManager#persist() expects parameter 1 to be an entity object, array given.
What should I do to avoid these errors ?
EventsController.php
<?php
namespace App\Controller;
use App\Form\SearchType;
use App\Repository\EventsRepository;
use App\Repository\CategoriesRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class EventsController extends AbstractController
{
private $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
#[Route('/search', name: 'search')]
public function search(Request $request, EntityManagerInterface $entityManagerInterface,)
{
$data = $request->query->all();
$sessionFormData = $sessionInterface->get('data');
$form = $this->createForm(SearchType::class, $sessionFormData);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$session->set('data', $data);
return $this->render('front/events.html.twig', $data);
}
return $this->renderForm('front/search.html.twig', [
'form' => $form
]);
}
SearchType.php
<?php
namespace App\Form;
use App\Entity\BigCity;
use App\Entity\Categories;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class SearchType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('bigcity', EntityType::class, [
'class' => BigCity::class,
'choice_label' => 'name',
'placeholder' => 'Sélectionne une grande ville'
])
->add('category', EntityType::class, [
'class' => Categories::class,
'choice_label' => 'image',
'expanded' => true,
'multiple' => false,
])
->add('save', SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => null
]);
}
}