Search code examples
phpsqlsymfonydql

research in the DB by the start of the name symfony


I would need a little help. I'm trying to implement a search bar with symfony, this search bar in the database. What I can do but the problem is that I absolutely have to put the full name to find the person (s) corresponds to that name. Except that I would like to be able to retrieve all the people starting with the beginning of the name I entered. For example : I type "dub" and I find: "Dubois", "Dubost", "Dubububu", ....

 public function searchAction (Request $request)
{
    $defaultData = array('search' => 'Type your search here');
    $form = $this->createFormBuilder()
        ->add('search', TextType::class, array('label'=>'Surname ?','required'=>true))
        ->add('send', SubmitType::class)
        ->getForm();


    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();
            $repository = $this
                    ->getDoctrine()
                    ->getManager()
                    ->getRepository('PegasusWebBundle:Clients')
                ;

                //$clients = $repository->findBySurname($form->get('search')->getData()); // Method 1
                $clients = $repository->myFindname($form->get('search')->getData());   // Method 2 with Repository
                return $this->render('PegasusWebBundle:Default:searchresult.html.twig',array(
                'clients'=> $clients ));
            }
    else

    return $this->render('PegasusWebBundle:Default:search.html.twig', array(
        'form' => $form->createView(),
    ));
}

The repository for the method 2

`class ClientsRepository extends \Doctrine\ORM\EntityRepository {

     public function myFindname($name)
    {
    // Method 2
    $qb = $this->createQueryBuilder('a');
    $qb->where(
    $qb->expr()->like('a.surname' ,':surname'))
        ->setParameter('surname', $name);

    return $qb
        ->getQuery()
        ->getResult();
    }

}`


Solution

  • Try adding the wildchar eg:

    $query = $repo->createQueryBuilder('a')
               ->where('a.surname LIKE :surname')
               ->setParameter('surname', '%'.$name.'%')
               ->getQuery();