### Install a Block Type
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Provides an example of how to install a block type programmatically. It first checks if the block type already exists by its handle and then proceeds with the installation if it doesn't.
```PHP
$bt = BlockType::getByHandle('my_block');
if (!is_object($bt)) {
BlockType::installBlockType('my_block', $pkg = null);
}
```
--------------------------------
### PHP Configuration File Example
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
An example of a PHP configuration file that returns an array of key-value pairs.
```PHP
return array(
'configItem' => true,
'configItem2' => 2,
'configItem3' => 'Hey!',
);
```
--------------------------------
### PHP: Managing Config Directly via Config Class (File System)
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Provides an example of directly using the Config class for file system configuration operations, including saving, getting with a default, and checking for keys. Mentions that 'set' and 'clear' methods are not functional.
```PHP
$key = 'configNamespace::configGroup.configItem';
$value = '5';
$default = -1;
/** FileSystem */
\Config::save($key, $value);
\Config::get($key, $default);
\Config::has($key);
//\Config::set($key, $value); //not working
//\Config::clear($key); // not working
```
--------------------------------
### Concrete CMS CLI Commands
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Provides a list of essential command-line interface (CLI) commands for managing a Concrete CMS installation. This includes commands for installation, configuration, cache management, package operations, and running jobs.
```Bash
concrete/bin/concrete5 list
c5:install
c5:reset
c5:ide-symbols
c5:config
c5:job
c5:clear-cache
c5:package-install
c5:package-update
c5:package-uninstall
c5:package-translate
c5:info
c5:update
```
--------------------------------
### Check Package Dependencies
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Checks if a required package dependency is installed. If the dependency is not found, it throws an exception indicating that the prerequisite add-on must be installed.
```PHP
$pkg_dependency = Package::getByHandle('handle_dependency');
if (!is_object($pkg_dependency)){
throw new Exception(t('Exception: Installation requires as a prerequisite that "X" Add-on is already installed.'));
}
```
--------------------------------
### Get List of Pages (PHP)
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Initializes a `PageList` object to retrieve a list of pages and their collection IDs. Also shows how to get the total number of results.
```PHP
$pageList = new PageList();
$pages = $pageList->getResults();
foreach ((array) $pages as $page) {
echo $page->getCollectionID();
}
// total number of results
echo $pageList->getTotalResults();
// OR: echo count($pages);
```
--------------------------------
### Get List of Entries with Pagination
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Fetches a paginated list of entries for an entity. This example shows how to set the number of items per page and retrieve the current page's results.
```PHP
//use Concrete\Core\Express\EntryList;
$entity = Express::getObjectByHandle('entity_handle');
$entryList = new EntryList($entity);
$pagination = $entryList->getPagination();
$pagination->setMaxPerPage(5);
$entries = $pagination->getCurrentPageResults();
//echo count($entries);
foreach ($entries as $entry) {
//
}
```
--------------------------------
### PHP: Managing Config via Service Provider (Database)
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Shows how to interact with database configuration using a service provider. Includes saving, getting with a default, and checking for configuration keys. Commented-out methods indicate they are not functional.
```PHP
$key = 'configNamespace::configGroup.configItem';
$value = '5';
$default = -1;
/** Database */
$configDatabase = \Core::make('config/database');
$configDatabase->save($key, $value);
$configDatabase->get($key, $default);
$configDatabase->has($key);
//$configDatabase->set($key, $value); // not working
//$configDatabase->clear($key); // not working
```
--------------------------------
### Get All Defined Constants
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Retrieves all defined constants in the PHP environment, optionally categorized.
```PHP
print_r(get_defined_constants($categorize = true));
```
--------------------------------
### PHP: Managing Config via Package Object (Database)
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Demonstrates saving, getting, and checking for configuration values in the database using a Package object. Includes commented-out methods that are noted as not working.
```PHP
$pkg = \Package::getByHandle('my_package');
/** Database */
// save config value
$pkg->getConfig()->save('front_end.show_header', true);
// get config value
$showHeader = $pkg->getConfig()->get('front_end.show_header');
// has config value?
$hasShowHeader = $pkg->getConfig()->has('front_end.show_header');
// set config value
//$pkg->getConfig()->set('front_end.show_header'); //not working
// clear config value
//$pkg->getConfig()->clear('front_end.show_header'); //not working
```
--------------------------------
### Get File Set
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Demonstrates how to retrieve a file set either by its unique ID or by its name.
```PHP
$fileSet = FileSet::getByID(1); // by ID
$fileSet = FileSet::getByName('File Set Name'); // name
```
--------------------------------
### PHP: Managing Config via Package Object (File System)
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Demonstrates saving, getting, and checking for configuration values in the file system using a Package object. Includes commented-out methods that are noted as not working.
```PHP
$pkg = \Package::getByHandle('my_package');
/** FileSystem */
// save config value
$pkg->getFileConfig()->save('front_end.show_header', true);
// get config value
$showHeader = $pkg->getFileConfig()->get('front_end.show_header');
// has config value?
$hasShowHeader = $pkg->getFileConfig()->has('front_end.show_header');
// set config value
//$pkg->getConfig()->set('front_end.show_header'); //not working
// clear config value
//$pkg->getConfig()->clear('front_end.show_header'); //not working
```
--------------------------------
### Get an Attribute Key
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Provides methods to retrieve attribute keys by their ID or handle, and access their properties like ID, handle, and name. It also shows how to get options for 'Option List' attributes and placeholders for 'Text' attributes.
```PHP
$attr = CollectionAttributeKey::getByID(1); // by ID
$attr = CollectionAttributeKey::getByHandle('attr_handle'); // by handle
$attrID = $attr->getAttributeKeyID(); //echo $attrID;
$attrHandle = $attr->getAttributeKeyHandle(); //echo $attrHandle;
$attrName = $attr->getAttributeKeyName(); //echo $attrName;
// options of an 'Option List' attribute
$controller = $attr->getController();
$attrOptions = $controller->getOptions();
foreach ((object) $attrOptions as $attrOption) {
$attrOptionID = $attrOption->getSelectAttributeOptionID(); //echo $attrOptionID;
$attrOptionValue = $attrOption->getSelectAttributeOptionValue(); //echo $attrOptionValue;
}
// placeholder of a `Text` attribute
$type = $attr->getAttributeKeySettings();
if ($type instanceof \Concrete\Core\Entity\Attribute\Key\Settings\TextSettings) {
$attrPlaceholder = $type->getPlaceholder();
}
//\concrete\src\Entity\Attribute\Key\Settings\TextSettings.php
```
--------------------------------
### Get File Set Info
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Retrieves the ID and name of a file set.
```PHP
$filesetID = $fileSet->getFileSetID();// echo $filesetID;
$filesetName = $fileSet->getFileSetID();// echo $filesetName;
```
--------------------------------
### Update a Page
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Provides examples for updating various properties of an existing page, such as its name, description, theme, and cache settings. It also shows how to rescan the collection path after changing the handle.
```PHP
$page->update(
array(
'cName' => 'My new page name',
'cDescription' => 'My new page description',
//'cDatePublic' => '2019-01-02 20:21:22',
//'cDateCreated' => date('Y-m-d H:i:s'),
//'uID' => 1,
//'pTemplateID' => 1,
//'ptID' => 13,
//'pkgID' => 1,
//'cHandle' => 'new-handle',
//'cCacheFullPageContent' => false,
//'cCacheFullPageContentOverrideLifetime' => false,
//'cCacheFullPageContentLifetimeCustom' => false,
)
);
// this should be run afterwards if the handle is changed
$page->rescanCollectionPath();
// update theme of a page
$pTheme = \PageTheme::getByID(3);
$page->setTheme($pTheme);
$page->update([]); // necessary?
```
--------------------------------
### Generate URL
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Generates a URL for a given path. The example shows how to create a URL to '/path/to/somewhere', which resolves to 'http://ursite/index.php/path/to/somewhere'.
```PHP
$url = URL::to('/path/to/somewhere'); //http://ursite/index.php/path/to/somewhere
```
--------------------------------
### Logging Messages
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Provides examples for logging messages at different severity levels (Info, Warning, Alert, Notice) using the Log facade. The logs can be found at '/dashboard/reports/logs'.
```PHP
//use Log;
Log::addInfo('This is an informative message.');
Log::addWarning('Uh oh.');
Log::addAlert('Red alert!');
Log::addNotice('A notice error.');
// see logs at /dashboard/reports/logs
```
--------------------------------
### Get Package Data
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Retrieves various data points associated with a Package object, including its ID, handle, name, description, version, path, and dependencies.
```PHP
echo $pkg->getPackageID();
echo $pkg->getPackageHandle();
echo $pkg->getPackageName();
echo $pkg->getPackageDescription();
echo $pkg->getPackageVersion();
echo $pkg->getPackagePath();
print_r($pkg->getPackageDependencies());
```
--------------------------------
### Create File Folder
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Creates a new folder within the file system, starting from the root folder. The folder name includes a timestamp to ensure uniqueness.
```PHP
//use ConcreteCoreFileFilesystem;
$filesystem = new Filesystem();
$folder = $filesystem->getRootFolder();
$folderName = 'My Folder - '.time();
$folder = $filesystem->addFolder($folder, $folderName);
```
--------------------------------
### Get List of Files (PHP)
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Retrieves a list of all files managed by Concrete CMS. It initializes a FileList, fetches the results, and iterates through them to display file IDs.
```PHP
$fileList = new FileList();
$files = $fileList->getResults();
//echo count($files);
foreach ((array) $files as $file) {
echo $file->getFileID();
}
```
--------------------------------
### Get List of Users
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Retrieves a list of all users and iterates through them to display their user IDs.
```PHP
$userList = new UserList();
$users = $userList->getResults();
//echo count($users);
foreach ((array) $users as $user) {
echo $user->getUserID();
}
```
--------------------------------
### Sort Entries by Attribute
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Provides examples for sorting entries by display order or by a specific attribute in ascending or descending order.
```PHP
$entryList->sortByDisplayOrderAscending();
$entryList->sortByAttributeHandle('desc'); // by an attribute: asc OR desc
//\concrete\src\Express\EntryList.php
```
--------------------------------
### Block Instance Operations
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Work with instances of blocks, including hard-coding blocks with custom templates and getting or setting block instance data.
```APIDOC
Blocks:
Working with Blocks:
Hard-coding a Block with Custom Template
Get data of an instance of a Block
Set data of an instance of a Block
```
--------------------------------
### Get Environment
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Retrieves the current application environment using the `$app->environment()` method. The environment value can then be echoed or used for conditional logic.
```PHP
$environment = $app->environment(); //echo $environment;
```
--------------------------------
### Get Package by Handle
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Retrieves a Package object using its unique handle. This is a common way to access package information and functionality within the framework.
```PHP
$pkg = Package::getByHandle('theme_pixel');
```
--------------------------------
### Block Type Management
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Manage block types, including retrieving block type information and installing new block types.
```APIDOC
Blocks:
A Block Type:
Get a Block Type
Get a Block Type data
Install a Block Type
```
--------------------------------
### List Attribute Set Categories
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Shows how to retrieve a list of all attribute set categories (e.g., user, file, site) and iterate through them to get their ID and handle.
```PHP
//use Concrete\Core\Attribute\Key\Category as AttributeKeyCategory;
$categories = AttributeKeyCategory::getList();
foreach ((array) $categories as $category) {
$categoryID = $category->getAttributeKeyCategoryID(); //echo $categoryID;
$categoryHandle = $category->getAttributeKeyCategoryHandle(); //echo $categoryHandle;
}
```
--------------------------------
### Get List of Pages with Pagination (PHP)
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Demonstrates how to paginate through a list of pages using `PageList` and `Pagination`. Includes setting results per page, rendering pagination controls, and accessing pagination details like total pages and current page.
```PHP
$pageList = new PageList();
$pagination = $pageList->getPagination();
$pagination->setMaxPerPage(5);
$pages = $pagination->getCurrentPageResults();
//echo count($pages);
foreach ((array) $pages as $page) {
echo $page->getCollectionID() . '-' . $page->getCollectionName() . '
';
}
// pagination buttons
echo $pagination->renderDefaultView(); // outputs HTML for Bootstrap 3
// pagination functions
$pagination->setCurrentPage(1);
//$pagination->setCurrentPage($_GET['ccm_paging_p'] ?? 1); // in case the result is not generated rightly based on the current page number
echo $pagination->getTotalResults(); // total number of results
echo $pagination->getTotalPages(); // total number of pages
echo $pagination->hasNextPage(); // to determine whether paging is necessary
echo $pagination->hasPreviousPage(); //"
```
--------------------------------
### Hard-code Block with Custom Template
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Illustrates how to hard-code a block in a template, including setting custom controller attributes and rendering with a specific template. It uses the 'autonav' block as a detailed example.
```PHP
$bt = BlockType::getByHandle('block_type_handle'); // block_type_handle: autonav, tag, ...
$bt->controller->block_attribute_handle = 'some_attribute'; // block attribute handles can be retrieved by looking at the related table in database (e.g.: btNavigation, btTags)
// ...
$bt->render($view = 'view'); // $view: template name
// Sample code for autonav
$bt = BlockType::getByHandle('autonav');
$bt->controller->orderBy = 'display_asc';
$bt->controller->displayPages = 'top';
$bt->controller->displaySubPages = 'relevant_breadcrumb';
$bt->controller->displaySubPageLevels = 'all';
$bt->render('templates/breadcrumb');
```
--------------------------------
### Get File List with Pagination
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Retrieves a list of files with support for pagination. You can set the number of items per page and iterate through the results. Links to further documentation for pagination styling are provided.
```PHP
$fileList = new FileList();
$pagination = $fileList->getPagination();
// $pagination->setMaxPerPage(5); // change default max per page value (10)
$files = $pagination->getCurrentPageResults();
//echo count($files);
foreach ((array) $files as $file) {
echo $file->getFileID().'-'.$file->getFileName().'
';
}
```
--------------------------------
### Database Operations with Doctrine DBAL
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Provides examples of common database operations using Concrete CMS's database connection, which leverages Doctrine DBAL. Covers connection, query execution, fetching rows, inserts, updates, and deletes.
```PHP
// database connection
$db = $app->make(\Concrete\Core\Database\Connection\Connection::class);
// debug
$db->debug = true;
// prepare any query
$statement = $db->executeQuery('SELECT * FROM `myTable` WHERE `id`>?;', array(0));
//echo $statement->rowCount(); // number of SELECTed/UPDATEd/DELETEd rows
//echo $statement->getSqlQuery(); // prepared SQL //not working
// iterate through rows
$rows = $statement->fetchAll(); //print_r($rows);
foreach ($rows as $row) {
print_r($row);
}
// OR:
while ($row = $statement->fetch()) {
//print_r($row);
}
// Prepares and executes an SQL query and returns the FIRST row of the result as an associative array.
$row = $db->fetchAssoc('SELECT * FROM `myTable` WHERE `id` = ?;', array(1)); //print_r($row);
// Prepares and executes an SQL query and returns the result as an associative array.
$rows = $db->fetchAll('SELECT `name` FROM `myTable`;'); //print_r($rows);
// Prepares and executes an SQL query and returns the value of a single column of the first row of the result.
$column = $db->fetchColumn('SELECT `name` FROM `myTable` WHERE id = ?;', array($id)); //echo $column;
// INSERT
$statement = $db->executeQuery('INSERT INTO `myTable` (`name`, `url`) VALUES (?, ?);', array('Name 1', 'URL 1'));
//echo $db->lastInsertId(); // last inserted id
//echo $statement->rowCount(); // number of affected rows
// UPDATE
$statement = $db->executeQuery('UPDATE `myTable` SET name = ? WHERE `id` = ?;', array('new name', 1));
//echo $statement->rowCount(); // number of affected rows
// DELETE
$statement = $db->executeQuery('DELETE FROM `myTable` WHERE `id` = ?;', array(1));
//echo $statement->rowCount(); // number of affected rows
// For more check [`HERE`](https://www.doctrine-project.org/api/dbal/2.5/Doctrine/DBAL/Connection.html)
```
--------------------------------
### PHP Navigation Helper Functions
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Utilities for generating navigation links and breadcrumbs, including getting links to collections (pages), trail to a collection, collection URLs, and login/logout links.
```PHP
$nh = $app->make('helper/navigation');
$nh->getLinkToCollection($cObj);
$nh->getTrailToCollection($c);
$nh->getCollectionURL($cObj);
$nh->getLogInOutLink();
```
--------------------------------
### Filter Entries by Attribute
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Demonstrates how to filter a list of entries based on various attributes. It includes examples for filtering by keywords, attribute handles, and specific values, including null values.
```PHP
$entryList->filterByKeywords($keywords = ''); // not working? because if value is null, it needs `keyword` IS NULL check and not `keyword` = '', it works although if $keyword = 'something'
$entryList->filterByAttributeHandle($keywords = ''); // not working? because if value is null, it needs `keyword` IS NULL check and not `keyword` = '', it works although if $keyword = 'something'
$entryList->filterByAttribute($handle = 'attribute_handle', $value = null, $comparison = 'IS'); // when filtering on value = null
$entryList->filterByAttribute($handle = 'attribute_handle', $value = 'something'); // when filtering on value = "something"
$entryList->filterByAttributeHandle($value = 'something'); // when filtering on value = "something", won't work if $value = null
//\concrete\src\Express\EntryList.php
```
--------------------------------
### Get Page Attribute Value (PHP)
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Retrieves the value of a specific page attribute, handling different attribute types like text, images, and option lists. Includes examples for getting image URLs, sizes, and iterating through option lists.
```PHP
// Attribute
$attr = $page->getAttribute('attribute_handle');
// Image/File
$attr = $page->getAttribute('thumbnail');
if ($attr) {
$attrTitle = $attr->getTitle(); //echo $attrTitle;
$attrURL = $attr->getURL(); //echo $attrURL;
$attrDownloadURL = $attr->getDownloadURL(); //echo $attrDownloadURL;
$attrForceDownloadURL = $attr->getForceDownloadURL(); //echo $attrForceDownloadURL;
$attrSize = $attr->getSize(); //echo $attrSize;
$attrExtension = $attr->getExtension(); //echo $attrExtension;
// image thumbnail
$ih = $app->make('helper/image');
$thumbSrc = $ih->getThumbnail($attr, 100, 100)->src; //echo $thumbSrc;
}
// Option List: get option(s):
// A: Single option: cast to `string`
$optionValue = (string) $attr;
// B: Multiple options: cast to `object` and iterate
foreach ((object) $attr as $option) {
$optionValue = $option->getSelectAttributeOptionValue(); //echo $optionValue;
// $optionID = $option->getSelectAttributeOptionID(); //echo $optionID;
// OR
// $optionValue = (string) $option;
}
// Topics
$topics = $page->getAttribute('attribute_handle');
foreach ((object) $topics as $topic) {
echo $topic->getTreeNodeID();
echo $topic->getTreeNodeName();
}
// Date
$date = $page->getAttribute('attribute_handle'); // return php DateTime object
echo $date->format('Y-m-d H:i:s'); // to string
/*
Address
https://documentation.concretecms.org/api/9.2.8/Concrete/Core/Entity/Attribute/Value/Value/AddressValue.html
https://github.com/concretecms/concretecms/issues/7943
*/
$location = $c->getAttribute('attribute_handle');
// print formatted address
echo $location;
// get address values separately
$address1 = $location->getAddress1();
$address2 = $location->getAddress2();
$city = $location->getCity();
$country = $location->getCountry();
$state = $location->getStateProvince();
$postalCode = $location->getPostalCode();
echo $address1, $address2, $city, $country, $state, $postalCode;
```
--------------------------------
### Get List of Entries in an Entity
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Retrieves a list of entries associated with a specific entity. It demonstrates how to fetch entries and access their properties like ID, attribute ID, and creation date.
```PHP
//use Concrete\Core\Express\EntryList;
$entity = Express::getObjectByHandle('entity_handle');
$entryList = new EntryList($entity);
$entries = $entryList->getResults();
//echo count($entities);
foreach ($entries as $entry) {
echo $entry->getId(); // internal ID
echo $entry->getAttributeId();
// OR: echo $entry->getAttribute('attribute_id');
// OR: echo $entry->getAttributeValueObject('attribute_id');
print_r($entry->getDateCreated());
//print_r($entry->getDateCreated()->getTimestamp());
//print_r($entry->getDateCreated()->format(DateTime::ATOM));
}
```
--------------------------------
### PHP: Managing Config via Service Provider (File System)
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Illustrates managing file system configuration through a service provider, including saving, retrieving with a default, and checking for key existence. Notes non-working 'set' and 'clear' methods.
```PHP
$key = 'configNamespace::configGroup.configItem';
$value = '5';
$default = -1;
/** FileSystem */
$configFile = \Core::make('config');
$configFile->save($key, $value);
$configFile->get($key, $default);
$configFile->has($key);
//$configFile->set($key, $value); // not working
//$configFile->clear($key); // not working
```
--------------------------------
### Add Areas to Page Templates
Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md
Provides examples for adding both regular and global areas to page templates in Concrete CMS. It includes options for enabling grid containers, setting column counts, and defining block wrapper HTML.
```PHP
// regular area
$a = new Area("Main");
//$a->enableGridContainer(); //enable grid container in area
//$a->setAreaGridMaximumColumns(12);
//$a->setBlockWrapperStart('