### 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('
'); //output content before each block //$a->setBlockWrapperEnd('
'); //output content after each block //if ($c->isEditMode()); //do something //if ($a->getTotalBlocksInArea($c) > 0); //do something $a->display($c); // global area $a = new GlobalArea("Main"); $a->display(); ``` -------------------------------- ### Get Category or Topic Node by ID or Name Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Provides examples for retrieving a category or a topic node using either their ID or name. It includes the necessary use statements for both types of nodes. ```PHP //use \Concrete\Core\Tree\Node\Type\Category as TreeNodeCategory; // Category $topicCategory = TreeNodeCategory::getByID($catID); $topicCategory = TreeNodeCategory::getNodeByName($catName); //use \Concrete\Core\Tree\Node\Type\Topic as TreeNodeTopic; // Topic (Node) $topicNode = TreeNodeTopic::getByID($nodeID); $topicNode = TreeNodeTopic::getNodeByName($nodeName); ``` -------------------------------- ### Set/Update an Attribute of a Page Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Covers setting or updating page attributes by their handle or ID. It includes examples for single values, multiple values (option lists), topics, and date attributes. ```PHP $page = \Page::getByID(1); // by ID $page->setAttribute('attribute_handle', 'value'); // multiple values (option list) $page->setAttribute('attribute_handle', array('value1', 'value2')); // multiple values (topics) //use Concrete\Core\Entity\Attribute\Value\Value\TopicsValue; //use Concrete\Core\Entity\Attribute\Value\Value\SelectedTopic; $treeNodeIDs = [1, 2, 3]; $topicsValue = new TopicsValue(); foreach ($treeNodeIDs as $treeNodeID) { $topicsValueNode = new SelectedTopic(); $topicsValueNode->setAttributeValue($topicsValue); $topicsValueNode->setTreeNodeID($treeNodeID); $topicsValue->getSelectedTopics()->add($topicsValueNode); } $page->setAttribute('attribute_handle', $topicsValue); // date $page->setAttribute('attribute_handle', new \DateTime()); // current date $page->setAttribute('attribute_handle', new \DateTime('1990-01-12')); // custom date date ``` -------------------------------- ### Get Page Template, Type, and Theme Objects Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Retrieves the associated Page Template, Page Type, and Page Theme objects for a given page, allowing access to their specific properties like ID, name, and handle. ```PHP // Page Template $pTemplate = $page->getPageTemplateObject(); if (is_object($pTemplate)) { $ptID = $pTemplate->getPageTemplateID(); $ptName = $pTemplate->getPageTemplateName(); $ptHandle = $pTemplate->getPageTemplateHandle(); } // Page Type $pType = $page->getPageTypeObject(); if (is_object($pType)) { $ptID = $pType->getPageTypeID(); $ptName = $pType->getPageTypeName(); $ptHandle = $pType->getPageTypeHandle(); $ptTemplate = $pType->getPageTypePageTemplateObjects(); } // Page Theme $pTheme = $page->getCollectionThemeObject(); if (is_object($pTheme)) { $ptID = $pType->getThemeID(); $ptName = $pType->getThemeName(); $ptHandle = $pType->getThemeHandle(); } ``` -------------------------------- ### Get Children of a Topic Tree Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Demonstrates how to get the children (categories and nodes) of a topic tree. It involves getting the root node, populating its children, and then iterating through them to display their IDs and names. ```PHP //use \Concrete\Core\Tree\Type\Topic as TopicTree; $root = $topicTree->getRootTreeNodeObject(); $root->populateChildren(); $topics = $root->getChildNodes(); // iterate foreach ((object) $topics as $topic) { echo $topic->getTreeNodeID(); echo $topic->getTreeNodeName(); } ``` -------------------------------- ### Get File Data (PHP) Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Retrieves various data points for a file in Concrete CMS, including its ID, name, URLs, path, title, description, tags, size, type, and attributes like width and height. ```PHP echo $file->getFileID(); // file ID echo $file->getFileName(); // file name echo $file->getURL(); // direct url echo $file->getDownloadURL(); // tracked url echo $file->getRelativePath(); echo $_SERVER['DOCUMENT_ROOT'] . $file->getRelativePath(); echo $file->getTitle(); echo $file->getDescription(); echo $file->getTags(); // string print_r($file->getTagsList()); // array echo $file->getSize(); echo $file->getFullSize(); echo $file->getExtension(); echo $file->getType(); echo $file->getMimeType(); echo $file->getDisplayType(); echo $file->getGenericTypeText(); echo $file->getAttribute('width'); echo $file->getAttribute('height'); echo $file->getAttribute('duration'); // file version $fileVersion = $file->getApprovedVersion(); ``` -------------------------------- ### Configuration Key Format Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Illustrates the standard format for accessing configuration items, using a namespace, group, and item structure. ```APIDOC configNamespace::configGroup.configItem ``` -------------------------------- ### Get List of Page Attributes (PHP) Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Retrieves a list of attribute keys for which a page has values. It iterates through these keys to get their handles and names. ```PHP // get a list of the attribute keys for which the page has values $attrKeys = $page->getSetCollectionAttributes(); if (count($attrKeys)) { foreach ($attrKeys as $key) { //each $key is an instance of \Concrete\Core\Entity\Attribute\Key\Key echo $attrHandle = $key->getAttributeKeyHandle(); echo $attrName = $key->getAttributeKeyName(); } } ``` -------------------------------- ### Configuration Management Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Manage configuration values, including understanding basic key-value storage, different storage locations (database, filesystem), and various methods for reading and writing configuration values. ```APIDOC Configs: Basics: Key Value Different places for storing data: Database FileSystem Different ways to read and write config values: 1: Using a Package object 2: Using a service provider 3: Using Config ``` -------------------------------- ### Get All Attribute Keys (PHP) Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Retrieves all attribute keys associated with the page category in Concrete CMS. It iterates through the attributes to get their ID, handle, and name. ```PHP $pageCategory = $this->app->make(Concrete\Core\Attribute\Category\PageCategory::class); $attributes = $pageCategory->getList(); foreach ($attributes as $attr) { $attrID = $attr->getAttributeKeyID(); //echo $attrID; $attrHandle = $attr->getAttributeKeyHandle(); //echo $attrHandle; $attrName = $attr->getAttributeKeyName(); //echo $attrName; } ``` -------------------------------- ### Logging to a New Channel Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Demonstrates how to create a logger for a new channel and add messages to it. This allows for more organized logging, with logs accessible at '/dashboard/reports/logs'. ```PHP $logger = $this->app->make(LoggerFactory::class)->createLogger('new_channel'); $logger->addInfo('This is an informative message.'); // see logs at /dashboard/reports/logs ``` -------------------------------- ### Create Custom Helper Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Demonstrates how to create a custom helper class in PHP, bind it within the application, and set up autoloading for its namespace. It also shows how to use the custom helper. ```PHP // Create the helper: \application\src\Html\Service\Talk.php namespace Application\Html\Service; class Talk { public function greet($phrase = 'Hello') { return $phrase; } } // bind it at: \application\bootstrap\app.php $app->bind('helper/talk', function() { return new \Application\Html\Service\Talk(); }); // add path at: \application\bootstrap\autoload.php $classLoader->addPrefix('Application\Html\Service', DIR_APPLICATION . '/' . DIRNAME_CLASSES . '/Html/Service'); // use it like this $th = Core::make('helper/talk'); echo $th->greet('Hi there!'); ``` -------------------------------- ### Get Files in Folder Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Retrieves files that are located within a specific folder. It involves getting a folder node by name and then filtering a file list by that parent folder. The code iterates through the results to display file IDs. ```PHP //use ConcreteCoreTreeNodeTypeFileFolder; //use ConcreteCoreFileFolderItemList; $fileFolder = FileFolder::getNodeByName('Folder Name'); $fileList = new FolderItemList(); if ($fileFolder) { $fileList->filterByParentFolder($fileFolder); $files = $fileList->getResults(); } //echo count($files); foreach ((array) $files as $file) { $file = $file->getTreeNodeFileObject(); echo $file->getFileID(); } ``` -------------------------------- ### Configure Database Connections Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Demonstrates how to configure multiple database connections in Concrete CMS by defining connection details in the `database.php` configuration file. It shows how to set up a default connection and an additional 'pricing' connection, and how to access a specific connection programmatically. ```PHP return array( 'default-connection' => 'concrete', 'connections' => array( 'concrete' => array( 'driver' => 'c5_pdo_mysql', 'server' => 'localhost', 'database' => 'database', 'username' => 'username', 'password' => 'password', 'charset' => 'utf8', ), 'pricing' => array( 'driver' => 'c5_pdo_mysql', 'server' => 'secure-pricing.wherever.com', 'database' => 'pricing_db', 'username' => 'username', 'password' => 'password', 'charset' => 'utf8', ), ), ); $dbPricing = $app->make('database')->connection('pricing'); ``` -------------------------------- ### Add a Page Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Demonstrates how to add a new page to the website. It involves specifying the parent page, page type, and page template, along with basic page content like name and description. ```PHP $parentPage = \Page::getByPath('/blog'); $pageType = \PageType::getByHandle('blog_entry'); // dashboard/pages/types $pageTemplate = \PageTemplate::getByHandle('blog_entry'); // dashboard/pages/templates $page = $parentPage->add( $pageType, array( 'cName' => 'Hello All!', 'cDescription' => 'Just a quick blog post.', 'cHandle ' => 'hello-all', //'cDatePublic' => '2019-01-02 20:21:22', //'cDateCreated' => date('Y-m-d H:i:s'), // updates the posting date of the page to now //'pkgID ' => 1, //'uID ' => 1, ), $pageTemplate ); ``` -------------------------------- ### Add User Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Demonstrates the process of adding a new user by providing an array of user details including username, email, and password. Optional parameters like default language and validation status can also be set. ```PHP $ui = \UserInfo::add(array( 'uName' => 'andrew', 'uEmail' => 'andrew@concrete5.org', 'uPassword' => 'kittens', //'uDefaultLanguage' => '', // an ISO language code for the user's default language //'uIsValidated' => '', // whether the user is validated. 1 for validated, 0 for definitely unvalidated, and -1 for unknown (which is the default on sites that don't employ user validation )); ``` -------------------------------- ### Accessing the Application Instance ($app) Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Demonstrates various methods to obtain the application instance ($app) in Concrete CMS. This includes accessing it within a controller, a custom class, or directly using facade or global functions. It also shows how to create new object instances using the application instance. ```PHP $app = $this->app; ``` ```PHP /** @var \Concrete\Core\Application\Application */ protected $app; public function __construct(\Concrete\Core\Application\Application $app) { $this->app = $app; } public function myMethod() { $app = $this->app; } ``` ```PHP $app = \Concrete\Core\Support\Facade\Application::getFacadeApplication(); ``` ```PHP $app = app(); ``` ```PHP $token = app('token'); ``` -------------------------------- ### Package Management Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Manage packages, including retrieving package information, data, and checking dependencies. ```APIDOC Packages: A Package: Get a package Get a package data Check dependencies ``` -------------------------------- ### PHP Image Helper Methods Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Provides an overview of the methods available in the Image helper class for image manipulation. This includes setting storage locations, JPEG and PNG compression levels, thumbnail formats, and various methods for creating, processing, and outputting thumbnails. ```PHP $ih = $app->make('helper/image'); $ih->getStorageLocation(); $ih->setStorageLocation(StorageLocationInterface $storageLocation); $ih->setJpegCompression($level); $ih->getJpegCompression(); $ih->setPngCompression($level); $ih->getPngCompression(); $ih->setThumbnailsFormat($thumbnailsFormat); $ih->getThumbnailsFormat(); $ih->create($mixed, $savePath, $width, $height, $fit = false, $format = false); $ih->returnThumbnailObjectFromResolver($obj, $maxWidth, $maxHeight, $crop = false); $ih->checkForThumbnailAndCreateIfNecessary($obj, $maxWidth, $maxHeight, $crop = false); $ih->processThumbnail($async, $obj, $maxWidth, $maxHeight, $crop); $ih->getThumbnail($obj, $maxWidth, $maxHeight, $crop = false); $ih->outputThumbnail($mixed, $maxWidth, $maxHeight, $alt = null, $return = false, $crop = false); ``` -------------------------------- ### Get User Info Attribute Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Retrieves a specific attribute from a user info object using its handle. ```PHP $uiAttr = $ui->getAttribute('attribute_handle'); //echo $uiAttr; ``` -------------------------------- ### Get File by ID (PHP) Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Retrieves a file object from Concrete CMS using its unique identifier. ```PHP $file = \File::getByID(1); // by ID ``` -------------------------------- ### Get Default Locale Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Fetches the default locale configured for the site. This is the fallback locale when no specific locale is set. ```PHP // first get $app $site = $app->make('site')->getSite(); $defaultLocale = $site->getDefaultLocale(); $defaultLocaleCode = $defaultLocale->getLocale(); // echo $defaultLocaleCode; // `en_US` ``` -------------------------------- ### Concrete Asset Library File Manager Helpers Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Provides methods to set up form fields for selecting different types of files (images, videos, documents, etc.) using the Asset Library. ```PHP $alh = $app->make('helper/concrete/asset_library'); $alh->file($inputID, $inputName, $chooseText, $preselectedFile = null, $args = []); $alh->image($inputID, $inputName, $chooseText, $preselectedFile = null, $args = []); $alh->video($inputID, $inputName, $chooseText, $preselectedFile = null, $args = []); $alh->text($inputID, $inputName, $chooseText, $preselectedFile = null, $args = []); $alh->audio($inputID, $inputName, $chooseText, $preselectedFile = null, $args = []); $alh->doc($inputID, $inputName, $chooseText, $preselectedFile = null, $args = []); $alh->app($inputID, $inputName, $chooseText, $preselectedFile = null, $args = []); $alh->fileOfType($type, $inputID, $inputName, $chooseText, $preselectedFile = null, $args = []); ``` -------------------------------- ### Create an Express Entry Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Shows how to create a new express entry and set its attributes before saving. ```PHP $entry = Express::buildEntry('entity_handle') ->setAttribute('attribute_handle', 'Andy') ->save(); ``` -------------------------------- ### Get Active Locale Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Retrieves the currently active locale of the site, which is typically used for language and regional settings. ```PHP $activeLocale = \Localization::activeLocale(); echo $activeLocale; // `en_US` ``` -------------------------------- ### Create File Set Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Creates a new file set with a specified name and type. If a file set with the same name already exists, it returns the existing one. ```PHP $fileSet = FileSet::createAndGetSet('My File Set', FileSet::TYPE_PUBLIC); // if the file with provided name exist, it will return the current file set ``` -------------------------------- ### Get File Folder Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Shows how to obtain a file folder object using its ID or by attempting to retrieve it by name. ```PHP $folder = Node::getByID($folderID); // by ID $folder = Node::getNodeByName('My Folder'); // by name, not working ``` -------------------------------- ### Get Area Object of a Page (PHP) Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Retrieves an Area object for a given area name from a page object. ```PHP $area = $c->getArea('Area name'); ``` -------------------------------- ### Copy a Page Source: https://github.com/shahroq/whale_c5_cheat_sheet/blob/master/README.md Illustrates how to duplicate an existing page and place the copy in a specified location. ```PHP $copyTo = \Page::getByPath('/archives'); $page->duplicate($copyTo); ```