symfonysymfony4

How to make a search query for Max and Min in Symfony4?


I have two fields for searching, that are:

Here, I want to display all the products which are between min and maximum price.

Help me I'm new to Symfony.

Here is my website

The website

How can I filter?


Solution

  • There are two options :

    1. Simple.

      • create ordinary html form in template (that you've already done):
    <form>
        <input name="min" value="{{ min }}">
        <input name="max" value="{{ max }}">
        <input type="submit" value="Search">
    </form>
    
    public function listPhones(Request $request, EntityManagerInterface $em) 
    {
        // get submitted values
        $min = $request->get('min');
        $min = $request->get('min');
    
        $phones = $em->getRepository(Phone::class)->search($min, $max);
    
        return ['phones' => $phones, 'min' => $min, 'max' => $max]
    }
    
    class PhoneRepository extends EntityRepository 
    {
        public function search($min = null, $max = null) 
        {
            $qb = $this->createQueryBuilder('p');
            if (!is_null($min)) {
                $qb->andWhere('p.price >= :min')
                   ->setParameter('min', $min);
            }
            if (!is_null($max)) {
                $qb->andWhere('p.price <= :max')
                   ->setParameter('max', $max);
            }
    
            return $qb->getQuery()->getResult();
        }
    }
    
    1. Symfony way, using Symfony Forms. It is a way more complex, I will explain on demand.