Working with entities and pages
Sometimes you will have structured data laying somewhere in a database (or any other storage) that is used to virtually generate a large amount of pages: for example when using a list of news and a dynamic route like /news/{slug} that points to the detail page of the news.
You could create a single page for each entity, in order to customize any aspect of the page (for example because of an advertising campaign). Since the CMS has some import/export capabilities and is able to represent an entire page as an array, you could leverage this feature to add callbacks to admin editing of entities and this way generate the corresponding page.
For example, consider the export file of this page, edited to be a page template:
// news.yml.twig
pages:
-
url: /news/{{ news.slug }}
locale: '{{ news.locale }}'
controller: 'EightPageBundle:Default:index'
title: '{{ news.title }}'
tags:
- news
- '{{ news.slug }}'
blocks:
-
name: h1
type: default
contents:
-
name: heading
type: choices
content: '"h1"'
-
name: text
type: label
content: '{{ news.title }}'
-
name: html_classes
type: label
content: 'mt-5 mb-5'
-
name: two_columns_one_two
type: default
blocks:
-
name: text
type: left
contents:
-
name: text
type: text
content: "{{ news.content }}"
-
name: text
type: left
contents:
-
name: news
type: entity
content: \AppBundle\Entity\News::{{ news.id }}
You can use the yml export of a page as a template and replace the fields you want to dynamically populate data with the entity currently being edited.
For example:
// inside sonata admin class
public function postPersist($object)
{
$template = $this
->container
->get('templating')
->render('AppBundle:Template:news.yml.twig', array(
'news' => $object,
));
$data = Yaml::parse($template);
$this->container->get('eight.page_generator')->createPage($data);
}
This will create a page once the entity is persisted.
Note that the page will be tagged with two tags: "news" and the news slug. This allows you to retrieve the page title and url by using twig helpers i18n_path(slug) and i18n_title(slug) from any other twig template.
This is also usefull for internationalization links: just tag two pages "about.en" and "about.it" and when you call i18n_path('about') in a template the helper will retrieve the page tagged "about.[locale]" with the same locale as the current route.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.