John Davidson

php - Symfony 5.4 Form: Issue with EntityType custom query_builder orderBy('rand') and setMaxResult

0 comments
Message:


I'm struggling with a 'strange' behavior.
When I use setMaxResult() + Rand() on my query_builder. I got randomly the message that my value is not valid.


Symfony\Component\Validator\ConstraintViolation {#1320 ▼
-message: "Cette valeur n'est pas valide."
-messageTemplate: "This value is not valid."
-parameters: [▶]
-plural: null
-root: Symfony\Component\Form\Form {#911 ▶}
-propertyPath: "children[press]"
-invalidValue: "8"
-constraint: Symfony\Component\Form\Extension\Validator\Constraints\Form {#987 …}
-code: "1dafa156-89e1-4736-b832-419c2e501fca"
-cause: Symfony\Component\Form\Exception\TransformationFailedException {#916 …}
}


If I remove setMaxResult(10) it works fine, if I remove Rand() It works too but not both


Could you please help me... I don't get it and I don't know what I can do


Here is my code:


GridType:



namespace App\Form;

use App\Entity\Press;
use App\Model\GridModel;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class GridType extends AbstractType
{
/**
* @var EntityManagerInterface
*/
private $entityManager;

public function __construct(
EntityManagerInterface $entityManager
)
{
$this->entityManager = $entityManager;
}

public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('press', EntityType::class, [
'class' => Press::class,
'query_builder' => $this->entityManager->getRepository(Press::class)->getIncluded($options['grid']),
'choice_label' => 'number',
'placeholder' => 'Sélectionner une presse',
]);
}

public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'grid' => null,
'data_class' => GridModel::class,
'csrf_protection' => false,
]);
}
}

PressRepository:


<?php

namespace App\Repository;

use App\Constant\GlobalConstant;
use App\Entity\Grid;
use App\Entity\Press;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;

/**
* @method Press|null find($id, $lockMode = null, $lockVersion = null)
* @method Press|null findOneBy(array $criteria, array $orderBy = null)
* @method Press[] findAll()
* @method Press[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class PressRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Press::class);
}

/**
* @param Grid|null $grid
* @return QueryBuilder|null
*/
public function getIncluded(Grid $grid = null): ?QueryBuilder
{
$result = $this->createQueryBuilder('i')
->andWhere('i.status = :status')
->andWhere('i.include = :include')
->setParameters([
'status' => GlobalConstant::STATUS_VALID,
'include' => true,
]);

if ($grid) {
$result->andWhere('i NOT IN (:grid)')
->setParameter(
'grid', $grid->getPress()
);
}

return $result->orderBy('i.number', 'ASC')
->setMaxResults(5)
->orderBy('RAND()');
}


My Answer:
When using the EntityType field in Symfony forms, you can specify a custom query builder to fetch the entities for the dropdown list. If you want to order the entities by a specific field, you can use the `orderBy()` method in the query builder.

Here's an example of how you can use the `orderBy()` method in the custom query builder for an EntityType field in Symfony 5.4:

php
use App\Entity\Category;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Doctrine\ORM\EntityRepository;

class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('category', EntityType::class, [
'class' => Category::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('c')
->orderBy('c.name', 'ASC');
},
'choice_label' => 'name',
]);
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Product::class,
]);
}
}


In this example, we have an EntityType field for selecting a Category entity. We have specified a custom query builder that orders the categories by the `name` field in ascending order using the `orderBy()` method.

Make sure to replace `Category::class` with the actual class name of your entity and adjust the field names accordingly in the `orderBy()` method.

Rate this post

3 of 5 based on 4241 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us