📔
MySearchSystem
  • MySearchSystem
  • Funciones
Powered by GitBook
On this page

Was this helpful?

MySearchSystem

Clase para realizar filtros sobre listados bundle para Symfony

Ejemplo de uso en un Controlador ...

controller/PersonController.php

<?php

namespace App\Controller;

use App\Entity\Person;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Knp\Component\Pager\PaginatorInterface;

use DidWeb\MyResourcesBundle\MySearchSystem\MySearchSystem;

/**
 * @Route("/person")
 */
class PersonController extends AbstractController
{

    public $mySearchSystem;

    public function __construct() {
      $allFilters = ['Por nombres'=>'by_names'];
      $this->mySearchSystem = new MySearchSystem($allFilters, 'person_search_web');

    }

    /**
     * @Route("/", name="person_index", methods={"GET"})
     */
    public function index(Request $request, PersonRepository $personRepository, PaginatorInterface $paginator): Response
    {

      $formSearch = $this->createForm(PersonSearchWebType::class);
      $currentPage =  MyExtras::checkRequest('page', $request, 1);

      $allPerson =  $personRepository->findAll();
      $allPerson = $this->allFilters($allPerson, $request);

      $paginatePersons = $paginator->paginate(
          $allPerson,
          $currentPage,
          15
      );

        $this->mySearchSystem->updateStatus($request);

        return $this->render('person/index.html.twig', [
            'people' => $paginatePersons,
            'mySearchSystem' => $this->mySearchSystem,
            'formSearch' => $formSearch->createView(),
        ]);
    }


    public function allFilters($allElements, $request) {
      // Filtrado por nombre y apellidos
      $resultFilter = $this->mySearchSystem->filterByNames($allElements, $request,
                                                          'by_names',
                                                          ['getName', 'getSurnameFirst', 'getSurnameSecond']);

      return $resultFilter;
    }


    /**
    * @Route("/limpiar-filtro", name="person_admin_clean_filter")
    */
    public function cleanFilters(Request $request){

      $this->mySearchSystem->cleanFilters($request);

      return $this->redirectToRoute('person_index');
    }
  }  

Form/PersonSearchWebType.php

<?php

namespace App\Form;

use App\Entity\Person;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Doctrine\ORM\EntityRepository;

class PersonSearchWebType extends AbstractType
{

  public function buildForm(FormBuilderInterface $builder, array $options)
  {

     $builder
        ->add('by_names', TextType::class, ['attr' => ['class' => 'form-control mb-4',
                                                       'placeholder' => 'Buscar por nombre o apellidos...'],
                                            'mapped' => false,
                                              ])
         ->add('search', SubmitType::class, ['attr' => ['class' => 'btn btn-info'], 
                                             'label' => 'Buscar'])


        ;
    }

}

templates/index.html.twig


// Mostramos los filtros aplicados y el botón para limpiar el filtro.
{% if mySearchSystem.hasFilters  %}
  <div class="col-12">
    {% if mySearchSystem.filtersActives|length > 0 %}

    <div class="row pt-2 mb-2 rounded bg-light  p-1">

       <div class="col-sx-12 col-lg-10 text-left text-secondary">
        {% for key,filterActive in mySearchSystem.filtersActives %}Filtros aplicados...
        <span class="label-filteractive">{{ key }}</span> : <strong class="value-filteractive mr-3"> {{ filterActive|raw }}</strong>
        {% endfor %}
        </div>

        <div class="text-secondary col-sx-12 col-lg-2 text-right">
          <a href="{{ url('person_web_clean_filter') }}" title="Elimnar filtro"><i class="fas fa-trash-alt color-pinuaga"></i></a>
        </div>

    </div>
{% endif %}
      </div>
{% endif %}

// Pintamos el formulario para aplicar el filtro
  <div class="row  text-center col-12 mt-2">
    {{ form_start(formSearch, {'attr': {'class' : 'col-12'}}) }}
    <div class="col-sx-12 col-lg-1 float-left">
      <i class="fas fa-search color-pinuaga mt-2 float-right"></i>
    </div>
    <div class="col-sx-12 col-lg-10 float-left">
      {{ form_widget(formSearch.by_names) }}
    </div>
    <div class="col-sx-12 col-lg-1 float-left">
      {{ form_widget(formSearch.search) }}
    </div>

    {{ form_end(formSearch) }}
  </div>

// Pintamos el Resultado
  <div class="mt-3 col-lg-12 table-responsive ">
    <table class="table table-striped col-lg-12">
        <thead>
            <tr  class="bg-th-mor-info">
                <th>Nombre</th>
                <th>Primer apellido</th>
            </tr>
        </thead>
        <tbody>
        {% for person in people %}
            <tr id="tr-person-{{ person.id }}">
                <td>{{ person.name }}</td>
                <td>{{ person.surnameFirst }}</td>
            </tr>
        {% else %}
            <tr>
                <td colspan="13">No se han encontrado datos</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
    
    // Pintamos el paginador
    <div class="navigation mt-3 mb-2">
                {{ knp_pagination_render(people) }}
    </div>
 </div>
NextFunciones

Last updated 5 years ago

Was this helpful?