Skip to content

Quick Start

Oleksandr Savchenko edited this page May 21, 2018 · 2 revisions

To check how bundle works or define base structure of your project you can use following example:

<?php

// src/AppBundle/Controller/DefaultController.php

namespace AppBundle\Controller;

use Prismic;
use Osavchenko\PrismicBundle\Helper\PrismicContext;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class DefaultController
 */
class DefaultController extends Controller
{
    /**
     * Show prismic documents list
     *
     * @param Request $request
     *
     * @return Response
     *
     * @Route("/", name="home")
     */
    public function indexAction(Request $request)
    {
        /** @var PrismicContext $ctx */
        $ctx = $this->get('prismic.context');
        $docs = $ctx->getApi()->query(null, [
            'pageSize' => 10,
            'page' => $request->query->get('page', 1),
        ]);

        return $this->render('Default/index.html.twig', [
            'ctx' => $ctx,
            'docs' => $docs,
        ]);
    }

    /**
     * Show full prismic document
     *
     * @param string $id
     * @param string $slug
     *
     * @return RedirectResponse|Response
     *
     * @throws NotFoundHttpException
     *
     * @Route("/documents/{id}/{slug}", name="detail")
     */
    public function detailAction($id, $slug)
    {
        /** @var PrismicContext $ctx */
        $ctx = $this->get('prismic.context');
        $doc = $ctx->getDocument($id);

        if ($doc) {
            if ($doc->getSlug() == $slug) {
                return $this->render('Default/detail.html.twig', [
                    'ctx' => $ctx,
                    'doc' => $doc,
                ]);
            }

            if (in_array($slug, $doc->getSlugs())) {
                return $this->redirect(
                    $this->generateUrl('detail', ['id' => $id, 'slug' => $doc->getSlug(),])
                );
            }

        }

        throw $this->createNotFoundException('Document not found');
    }

    /**
     * Search by prismic documents
     *
     * @param Request $request
     *
     * @return Response
     *
     * @Route("/search", name="search")
     */
    public function searchAction(Request $request)
    {
        /** @var PrismicContext $ctx */
        $ctx = $this->get('prismic.context');
        $docs = $ctx->getApi()->query(
            Prismic\Predicates::fulltext('document', $request->query->get('q')),
            [
                'pageSize' => 10,
                'page' => $request->query->get('page', 1),
            ]
        );

        return $this->render('Default/search.html.twig', [
            'ctx' => $ctx,
            'docs' => $docs,
        ]);
    }

    /**
     * Preview
     *
     * @param Request $request
     *
     * @return RedirectResponse
     *
     * @Route("/preview", name="preview")
     */
    public function previewAction(Request $request)
    {
        /** @var PrismicContext $ctx */
        $ctx = $this->get('prismic.context');

        return $ctx->previewSession($request->query->get('token'), '/');
    }

}
{# app/Resources/views/Default/detail.html.twig #}
{% extends "layout.html.twig" %}

{% block content %}
    <article id="{{ doc.id }}" data-wio-id="{{ doc.id }}">
    {% autoescape false %}
        {{ doc.asHtml(ctx.linkResolver) }}
    {% endautoescape %}
    </article>
{% endblock %}
{# app/Resources/views/Default/index.html.twig #}
{% extends "layout.html.twig" %}

{% block content %}
    <form action="{{ path('search') }}" method="GET">
        <input type="text" name="q" value="">
        <input type="submit" value="Search">
    </form>

    <hr>

    <h2>
        {% if docs.totalResultsSize == 1 %}
            One document found
        {% elseif docs.totalResultsSize > 0 %}
            {{ docs.totalResultsSize }} documents found
        {% else %}
            No documents found
        {% endif %}
    </h2>

    <ul>
        {% for doc in docs.results %}
            <li>
                <a href="{{ path('detail', {'id': doc.getId, 'slug': doc.slug }) }}">
                    {{ doc.slug }}
                </a>
            </li>
        {% endfor %}
    </ul>

    {% include 'pagination.html.twig' %}
{% endblock %}
{# app/Resources/views/Default/search.html.twig #}
{% extends "layout.html.twig" %}

{% block content %}
    <h2>
        {% if docs.totalResultsSize == 1 %}
            One document found
        {% elseif docs.totalResultsSize > 0 %}
            {{ docs.totalResultsSize }} documents found
        {% else %}
            No results
        {% endif %}
    </h2>

    <ul>
        {% for doc in docs.results %}
            <li>
                <a href="{{ ctx.resolveLink(doc) }}">
                    {{ doc.slug }}
                </a>
            </li>
        {% endfor %}
    </ul>

    {% include 'pagination.html.twig' %}
{% endblock %}
{# app/Resources/AppBundle/views/layout.html.twig #}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>{% block title %}Welcome!{% endblock %}</title>
    {% block stylesheets %}{% endblock %}
    <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
</head>
<body>
{% block body %}
    <header>
        <a href="{{ path('home') }}">
            <h1>Your prismic.io project</h1>
        </a>
    </header>

    {% block content %}{% endblock %}
{% endblock %}
{% block javascripts %}{% endblock %}
</body>
</html>
{# app/Resources/views/pagination.html.twig #}
{% if docs.totalPages > 1 %}
    <ul id="pagination">
        {% if docs.page > 1 %}
            <li>
                <a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge(app.request.query.all()|merge({page: docs.page - 1}))) }}">Previous</a>
            </li>
        {% endif %}
        {% for i in 1..docs.totalPages %}
            <li {{ i == docs.page ? 'class="current"' : '' }}>
                <a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge(app.request.query.all()|merge({page: i}))) }}">{{ i }}</a>
            </li>
        {% endfor %}
        {% if docs.page < docs.totalPages %}
            <li>
                <a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge(app.request.query.all()|merge({page: docs.page + 1}))) }}">Next</a>
            </li>
        {% endif %}
    </ul>
{% endif %}

Notice: the code above will work out of the box on symfony2 and symfony3. and you need some small work to adapt it for symfony4.

Clone this wiki locally