Creating pages dynamically is a central concept of concrete5 development and can unlock a lot of powerful features in custom applications. Imagine a concrete5 website that has a recipes database. You could make it so, that every time a recipe is added to the database, a new page for that recipe is added to the sitemap, immediately improving the depth of content on your website, its usability, and even search engine performance.
In this example, we will create an "About Us" page and add it to the sitemap.
We are continuing the practice of putting our code in /config/site_post.php
for the purposes of demonstration and testing. In real-world use, your dynamic page creation would happen in controller files or in add-on packages.
We will be assigning the new page a page type with the handle of right_sidebar
. If this doesn't exist in your own concrete5 installation, please adapt the recipe to suit your needs.
The steps for creating a page are as follows:
Open
/config/site_post.php
in your code editor.Load the page type that the new page will use. We will load the page type using its handle (
right_sidebar
, in this case).$pageType = CollectionType::getByHandle('right_sidebar');
Create an associative array that contains the fields that you wish to specify for the new page. In this example, we will only specify the page's name and handle.
$data = array( 'cName' => 'About Us', 'cHandle' => 'about' );
Load the parent page that the new page will be placed under. In this case, we are loading the home page, since the new page will be available at the top level.
$parent = Page::getByID(1);
Add the page by passing the
$pageType
object and$data
array to the add function of the parentPage
class.$newPage = $parent->add($pageType, $data);
Output a message and exit the process.
echo 'done!'; exit;
Visit your site's homepage to execute the code in
site_post.php
.If you see the success message, comment out the code in
site_post.php
so you can visit the newly created page. Otherwise, concrete5 will create a new page every time the site is loaded into a browser.Visit the newly created page at
http://example.com/about
.
The add()
function is a wrapper for the Collection
class's add()
function. Calling it will create a new Collection
record in the database, and a new pending CollectionVersion
record (which will be approved if the cvIsApproved
variable is set to true
or left blank). Then the new page will inherit the necessary permissions and get all of the blocks and other attributes from the Master Collection of the related page type.
You will need to provide two parameters to the add()
function, a CollectionType
object (which we worked with earlier in this chapter), and an associative array containing all of the data needed to create the page. The associative array can contain the following fields.