concrete5 – searching and cloning pages

In this short tutorial I’ll show you two different things. We’ll start with a simple example that explains one function of the PageList class and then another method you can use to duplicate a page.

Searching for pages by an attribute with PageList

The PageList class is very powerful, especially in combination with attributes. In order to be able to search after an attribute, we’ll create a new attribute called “Duplicate this Page”. We’ll use it to mark pages we’d like to clone. First, open the attributes page (/index.php/dashboard/pages/attributes/) and select the checkbox type like shown here:

page_attr

Click on the “Add” button and create the attribute using these values:

page_attr_detail

Now go back to the sitemap and pick a few random pages and assign the new attribute to them and tick the checkbox. Let’s have a quick look at some code. We’ll create a new file called “test.php” in the “tools” directory.

1
2
3
4
5
6
7
8
9
10
// build PageList object to get all pages where the attribute
// with the handle "duplicate_page" is checked
$pl = new PageList();
$pl->filterByDuplicatePage(true);
 
$pages = $pl->get(0);
 
foreach ($pages as $page) {
    echo $page->getCollectionName() . '<br/>';
}

When you now open /index.php/tools/test/ you’ll get the names of all pages where you’ve assigned our new attribute.

The PageList class has a magic method with which you can search for attribute values in an elegant way. Simple append the handle in CamelCase notation after “filterBy”. Your attribute handle is “very_lovely_day”, use $pl->filterByVeryLovelyDay(…); This works not only with checkbox attributes but with almost all attributes you can find.

Cloning pages

Assuming we’d want to copy those pages to a new location, we could easily use the “duplicate” method. But first, create a new page in the sitemap underneath you want the cloned pages to appear. Mine is called “Target Container” and hass the path “/target-container”. We use this in combination with the script we wrote above to get the final result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
 
// get target container underneath which we'll create the cloned pages
$targetPage = Page::getByPath('/target-container/');
 
// build PageList object to get all pages where the attribute
// with the handle "duplicate_page" is checked
$pl = new PageList();
$pl->filterByDuplicatePage(true);
 
// return _ALL_ pages we've found. If you have hundreds of pages
// you might want to use $pl->getPage(); and run the script several
// times
$pages = $pl->get(0);
 
foreach ($pages as $page) {
    $page->duplicate($targetPage);
}

When you open /index.php/tools/test again, you’ll get some clones in no time! But be aware, if you run the script again, you’ll get more clones.




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *