ccc

Mostrando entradas con la etiqueta Symfony Controllers. Mostrar todas las entradas
Mostrando entradas con la etiqueta Symfony Controllers. Mostrar todas las entradas

Symfony: Controller: Filtrando datos de la BD

Mostrar todos los registros:
public function listadoActoresAction()
    {
        $repository = $this->getDoctrine()->getRepository('cineactoresBundle:Actores');
        $arrActores = $repository->findAll();
        return $this->render('cineactoresBundle:Default:listadoActores.html.twig', array('actores' => $arrActores));
    }

http://symfonylsg.dev/app_dev.php/listadoActores

Mostrar los resultados de un registro por su Id:
public function showActorPorIdAction($id)
    {  
        $repository = $this->getDoctrine()->getRepository('cineactoresBundle:Actores');
        $arrActores = $repository->findOneById($id); // solo devolverá uno
        return $this->render('cineactoresBundle:Default:showActor.html.twig', array('actores' => $arrActores));
    }

http://symfonylsg.dev/app_dev.php/showActorPorId/3

Mostrar los resultados de un registro filtrando por un campo concreto:
En el routing:
cineactores_showActorPorCampo:
    pattern:  /showActorPorCampo/{nombre_campo}/{valor}
    defaults: { _controller: cineactoresBundle:Default:showActorPorCampo }

En el controller:
public function showActorPorCampoAction($nombre_campo, $valor)
    {
        $repository = $this->getDoctrine()->getRepository('cineactoresBundle:Actores');
        $arrActores = $repository->findBy(array($nombre_campo=>$valor));
        return $this->render('cineactoresBundle:Default:showActor.html.twig', array('actores' => $arrActores));
    }

Ejemplos:
symfonylsg.dev/app_dev.php/showActorPorCampo/tituloPelicula/El sargento York
http://symfonylsg.dev/app_dev.php/showActorPorCampo/nombre/James%20Cagney

Las vista de showActor.html.twig sería: 
{% extends 'cineactoresBundle::main.html.twig' %}

{% block title %} Mostrando detalles  {%endblock%}

{% block contenido %}
    {# comentario: {{ dump(actores) }} #}
    <h1>Detalles del actor </h1>
    {% if actores.id is defined %} {#Ha filtrado por id y solo hay un registro #}
            <div><h2>{{actores.id}} - {{actores.nombre}} - {{ actores.tituloPelicula }} - {{ actores.annoOscar }}</h2> </div>
    {% else %} {#Ha filtrado por un campo y devuelve varios registros #}
            {% for actor in actores %}
                <div><h2>{{actor.id}} - {{actor.nombre}} - {{ actor.tituloPelicula }} - {{ actor.annoOscar }}</h2> </div>
            {%  endfor %}
    {% endif %}
{% endblock %}

{% block lateralDer %}
<a href="../listadoActores">Volver al listado</a>
{% endblock %}

Symfony: Redireccionamientos desde el controller

Mostrar directamente en el Controller un mensaje HTML sin vista ni nada:
return new Response("Todo OK"); // debe estar incluido use Symfony\Component\HttpFoundation\Response;

Crear una excepción de página no encontrada:
if ($pagina != "xxx")
    throw $this->createNotFoundException('Lo siento. Página no encontrada');


Cargar la vista normalmente:
return $this->render('librerianovelasBundle:Info:'.$pagina.'.html.twig', array());

Redirigir directamente a una web externa:
return $this->redirect('http://www.google.es');

Redirigir a otro controller distinto: // el nombre se saca del routing

return $this->redirect($this->generateUrl('librerianovelas_ayuda',
                array("tema"=>"introducción")));
Incluso se puede especificar las páginas que se van a pasar por url con Slug
return $this->redirect($this->generateUrl('librerianovelas_ayuda',
                array("slug"=>"librerias")));
// sería lo mismo que poner a pelo /info/ayuda/librerias/

Cargar en ese mismo controller otro controller (sin redirigir para que no cambie la url del navegador):
$response = $this->forward('librerianovelasBundle:Info:nosotros',
                    array(
                        "nombre" => "Pepee",
                        "apellidos" => "Pérez",
                        "edad" => "29"
          
                    ));
return $response;

Más información en: http://symfony.com/doc/current/book/controller.html