### Silverstripe CMS GraphQL Server Getting Started Source: https://docs.silverstripe.org/en/4/developer_guides/graphql This section guides users through setting up their first GraphQL server and building a schema within the Silverstripe CMS environment. ```php addType(TypeCreator::createFromDataObject(MyDataObject::class)); // Add a query $schema->addQuery('myQuery', function() { return 'Hello, GraphQL!'; }); return $schema; ?> ``` -------------------------------- ### PHP: SetUp() for Test Data and Configuration Source: https://docs.silverstripe.org/en/4/developer_guides/testing/unit_testing Demonstrates using the `setUp()` method in PHPUnit for SilverStripe tests. It includes creating multiple data fixtures (pages) and modifying configurations using `Config::modify()->update()`. This setup runs before each test method. ```PHP namespace App\Test; use SilverStripe\Core\Config\Config; use SilverStripe\Dev\SapphireTest; use SilverStripe\Versioned\Versioned; class PageTest extends SapphireTest { protected $usesDatabase = true; protected function setUp(): void { parent::setUp(); // create 100 pages for ($i = 0; $i < 100; $i++) { $page = new Page(['Title' => "Page $i"]); $page->write(); $page->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); } // set custom configuration for the test. Config::modify()->update('Foo', 'bar', 'Hello!'); } public function testMyMethod() { // ... } public function testMySecondMethod() { // ... } } ``` -------------------------------- ### Install Silverstripe with Composer Source: https://docs.silverstripe.org/en/4/index This guide explains how to install the latest version of Silverstripe onto a web server using Composer. It assumes basic knowledge of PHP7 and Composer. ```bash composer create-project silverstripe/installer my-project-directory ``` -------------------------------- ### Silverstripe CMS Testing with Unit and Behavior Tests Source: https://docs.silverstripe.org/en/4/developer_guides Deploy robust applications by bundling Unit and Behavior tests with your application code and modules in Silverstripe CMS. This guide provides reference documentation and testing code examples. ```php objFromFixture(Page::class, 'homePage'); $this->assertEquals('Welcome to the homepage', $page->Title); } } ``` -------------------------------- ### Initialize Code at Document Ready Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/javascript_development Provides an example of how to ensure DOM elements are loaded before interacting with them by using jQuery's document.ready wrapper. ```JavaScript // DOM elements might not be available here $(document).ready(() => { // The DOM is fully loaded here }); ``` -------------------------------- ### Run Local Documentation Linting (Yarn & Composer) Source: https://docs.silverstripe.org/en/4/contributing/documentation This snippet shows the command-line instructions to install dependencies and run the documentation linter locally using Yarn and Composer. It's essential for ensuring code quality before submitting changes. ```bash yarn install composer install yarn lint ``` -------------------------------- ### QUnit Unit Test Example Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/javascript_development A basic unit test example using QUnit, a JavaScript unit testing framework. This test verifies a simple assertion and checks for equality between a string and a variable. ```JavaScript test('a basic test example', () => { ok(true, 'this test is fine'); const value = 'hello'; equals('hello', value, 'We expect value to be hello'); }); ``` -------------------------------- ### Silverstripe CMS v4 Documentation Overview Source: https://docs.silverstripe.org/en/4/developer_guides/model This snippet provides a high-level overview of the Silverstripe CMS v4 documentation structure. It lists the main sections available for developers and users, including getting started, developer guides, model and database information, templates, controllers, forms, configuration, and more. It also highlights the end-of-life status of version 4. ```text Project: /websites/silverstripe_en_4 Content: This app works best with JavaScript enabled. Silverstripe CMS DocumentationCMS Docs Search * V6V5V4V3 __ * __ * Getting Started * Server Requirements * Composer * Environment Management * Directory Structure * Recipes * Lessons * Developer Guides * Model and Databases * Introduction to the Data Model and ORM * Relations between Records * Managing Lists * Data Types, Overloading and Casting * Extending DataObjects * SearchFilter Modifiers * Model-Level Permissions * SQL Queries * Model Validation and Constraints * Versioning * Building Model and Search Interfaces around Scaffolding * Indexes * Managing Records * How To's * Templates and Views * Controllers * Forms * Configuration * Extending Silverstripe CMS * Testing * Debugging * Performance * Security * Email * Integration and Web Services * Search * i18n * Files * Customising the Admin Interface * Execution pipeline * Command Line Interface * Cookies and Sessions * GraphQL * Upgrading * Staying up to date with CMS releases * Upgrading a module * Migrating off CWP CMS recipe * Upgrading to Silverstripe CMS 4 * Upgrading to PHPUnit 9.5 for PHP8 support * Upgrading to GraphQL 4 * Deprecations * Upgrading Fluent * Changelogs * Contributing * Issues and Bug Reports * Contributing Code * Contributing Documentation * Contributing Translations * Coding conventions * Build tooling * Triage and peer review * Release process * Managing security issues * Project Governance * Core committers * Code of conduct * Maintainer guidelines * Request for comment * Major Release Policy * Minor Release Policy * Supported modules * Definition of Public API Version 4 __end of life This version of Silverstripe CMS will not recieve any additional bug fixes or documentation updates. Go to documentation for the most recent stable version. # Model and databases# In Silverstripe CMS, application data will be represented by a DataObject class. A `DataObject` subclass defines the data columns, relationships and properties of a particular data record. For example, Member is a `DataObject` which stores information about a person, CMS user or mail subscriber. ##### __Introduction to the Data Model and ORM Introduction to creating and querying a database records through the ORM (object-relational mapping) ##### __Relations between Records Relate models together using the ORM using has_one, has_many, and many_many. ##### __Managing Lists The SS_List interface allows you to iterate through and manipulate a list of objects. ##### __Data Types, Overloading and Casting Learn how data is stored going in and coming out of the ORM and how to modify it. ##### __Extending DataObjects Modify the data model without using subclasses. ##### __SearchFilter Modifiers Use suffixes on your ORM queries. ##### __Model-Level Permissions Reduce risk by securing models. ##### __SQL Queries Write and modify direct database queries through SQLExpression subclasses. ##### __Model Validation and Constraints Validate your data at the model level ##### __Versioning Add versioning to your database content through the Versioned extension. ##### __Building Model and Search Interfaces around Scaffolding A Model-driven approach to defining your application UI. ##### __Indexes Add Indexes to your Data Model to optimize database queries. ##### __Managing Records Manage your DataObject records ## How to's# ##### __Dynamic Default Fields Learn how to add default values to your models ##### __Grouping DataObject sets Learn how to split the results of a query into subgroups __ Edit on Github ``` -------------------------------- ### Silverstripe CMS Security Best Practices Source: https://docs.silverstripe.org/en/4/developer_guides This guide covers user authentication, the permission system, and how to secure your Silverstripe CMS code against malicious behaviors. It includes reference documentation and security code examples. ```php isLoggedIn() && Security::getCurrentUser()->can('ADMIN')) { // User is an admin } ``` -------------------------------- ### Silverstripe CMS Command Line Interface (CLI) Source: https://docs.silverstripe.org/en/4/developer_guides Automate Silverstripe CMS tasks, run Cron Jobs, or sync with other platforms through the Command Line Interface. This guide provides reference documentation and CLI command examples. ```bash ./vendor/bin/sake dev/build ./vendor/bin/sake flush=all ``` -------------------------------- ### JSpec Shopping Cart Test Example Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/javascript_development An example of a behavior-driven test for a ShoppingCart using JSpec. It demonstrates setting up a test environment with `before_each` and testing the `addProduct` method to ensure products are added correctly. ```JavaScript describe 'ShoppingCart' before_each cart = new ShoppingCart end describe 'addProduct' it 'should add a product' cart.addProduct('cookie') cart.addProduct('icecream') cart.should.have 2, 'products' end end end ``` -------------------------------- ### Silverstripe CMS GraphQL API Source: https://docs.silverstripe.org/en/4/developer_guides This guide covers integrating with and utilizing the GraphQL API in Silverstripe CMS. It includes reference documentation and examples for GraphQL queries and mutations. ```graphql { products { id title price } } ``` -------------------------------- ### PHP: setUpBeforeClass() and tearDownAfterClass() for Suite Setup Source: https://docs.silverstripe.org/en/4/developer_guides/testing/unit_testing Illustrates the use of static `setUpBeforeClass()` and `tearDownAfterClass()` methods in PHPUnit for SilverStripe tests. These methods execute once for the entire test class, allowing for setup and teardown operations that affect all test methods within the class. ```PHP namespace App\Test; use SilverStripe\Dev\SapphireTest; class PageTest extends SapphireTest { public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); // ... } public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); // ... } // ... } ``` -------------------------------- ### Build GraphQL Schema via CI/CD Source: https://docs.silverstripe.org/en/4/developer_guides/graphql/getting_started/deploying_the_schema Utilize a CI/CD pipeline to automate the GraphQL schema build process. This involves updating deployment scripts to execute the `dev/graphql/build` command, ensuring schema files are generated on each server in a multi-server setup. ```bash dev/graphql/build ``` -------------------------------- ### Install Silverstripe CMS with Composer Source: https://docs.silverstripe.org/en/4/getting_started Installs the Silverstripe CMS framework and its dependencies using Composer, a PHP package manager. This command creates a new project in the specified directory. ```bash composer create-project silverstripe/installer my-project ``` -------------------------------- ### Manage SilverStripe Sake Processes Source: https://docs.silverstripe.org/en/4/developer_guides/cli Provides examples of using the `sake` command to start, stop, and manage daemon processes within a SilverStripe application. These commands interact with the process controller defined elsewhere. ```bash sake -start my_process sake -stop my_process ``` -------------------------------- ### Silverstripe CMS Configuration System Source: https://docs.silverstripe.org/en/4/developer_guides Silverstripe CMS offers various methods for storing and modifying application settings, including site-wide settings and a YAML-based configuration system. This guide provides reference documentation and examples. ```yaml # config.yml example SilverStripe\Core\Config\Config: my_setting: 'some_value' ``` -------------------------------- ### Configure Silverstripe GraphQL Schema Source: https://docs.silverstripe.org/en/4/developer_guides/graphql/getting_started/deploying_the_schema This example shows how to add a basic type to your Silverstripe CMS GraphQL schema configuration. It's a foundational step for defining your API structure. ```yaml SilverStripe\GraphQL\SchemaBuilder\SchemaBuilder: # Add a basic type to the schema configuration schema_config: | query { hello: String } ``` -------------------------------- ### Install GraphQL DevTools for SilverStripe Source: https://docs.silverstripe.org/en/4/developer_guides/model/versioning This command installs the `silverstripe/graphql-devtools` package, which provides tools for exploring and interacting with your SilverStripe GraphQL schema directly from your browser, such as GraphiQL. ```bash composer require --dev silverstripe/graphql-devtools dev-master ``` -------------------------------- ### Example HTTPProvider Query Mapping Source: https://docs.silverstripe.org/en/4/developer_guides/graphql/tips_and_tricks An example of JSON content expected at the URL configured for HTTPProvider, mapping identifiers to GraphQL queries. ```json {"someUniqueID":"query{readMembers{Name+Email}}"} ``` -------------------------------- ### Example FileProvider Query Mapping Source: https://docs.silverstripe.org/en/4/developer_guides/graphql/tips_and_tricks An example of a JSON file content used by FileProvider to map unique identifiers to GraphQL queries. ```json {"someUniqueID":"query{validateToken{Valid Message Code}}"} ``` -------------------------------- ### Silverstripe CMS Unit Test Example Source: https://docs.silverstripe.org/en/4/developer_guides/testing/unit_testing Demonstrates a basic unit test for a custom method in a Silverstripe CMS Page model. It includes the model class and the corresponding test class using SapphireTest. ```php namespace { use SilverStripeCMSModelSiteTree; class Page extends SiteTree { public static function myMethod() { return (1 + 1); } } } ``` ```php namespace App\Test; use Page; use SilverStripe\Dev\SapphireTest; class PageTest extends SapphireTest { public function testMyMethod() { $this->assertEquals(2, Page::myMethod()); } } ``` -------------------------------- ### Granular Namespacing Example (Models) Source: https://docs.silverstripe.org/en/4/developer_guides/graphql/getting_started/configuring_your_schema This example demonstrates granular namespacing for GraphQL schema models. The file 'app/_graphql/news-and-blog/models/blog.yml' maps to 'SilverStripe\GraphQL\Schema\Schema.schemas.default.models'. ```yaml # app/_graphql/news-and-blog/models/blog.yml maps to SilverStripe\GraphQL\Schema\Schema.schemas.default.models ``` -------------------------------- ### JavaScript Object Spread Syntax Example Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/reactjs_redux_and_graphql A basic example demonstrating the JavaScript spread syntax for creating new objects with updated properties, equivalent to using `Object.assign()`. ```javascript CopynewProps = { ...oldProps, name: 'New name' }; ``` ```javascript CopynewProps = Object.assign( {}, oldProps, { name: 'New name' } ); ``` -------------------------------- ### Install Silverstripe Module with Composer Source: https://docs.silverstripe.org/en/4/developer_guides/extending/modules Installs the latest stable version of the 'silverstripe/blog' module using Composer. This command fetches the module and its dependencies, integrating it into the project. ```bash composer require silverstripe/blog *@stable ``` -------------------------------- ### Silverstripe CMS Execution Pipeline Overview Source: https://docs.silverstripe.org/en/4/developer_guides An overview of the steps involved in delivering a Silverstripe CMS web page, from request to response. This guide provides reference documentation on the execution flow. ```text Request -> Routing -> Controller -> Action -> Template Rendering -> Response ``` -------------------------------- ### Create New Silverstripe Site Source: https://docs.silverstripe.org/en/4/getting_started/composer Creates a new Silverstripe CMS project using Composer. It downloads the latest stable version of the installer by default. Options like '--prefer-source' or '--prefer-dist' can be used to include development fixtures or for a minimal installation, respectively. You can also specify a particular version to install. ```bash composer create-project silverstripe/installer my-project ``` ```bash composer create-project silverstripe/installer my-project --prefer-source ``` ```bash composer create-project silverstripe/installer ./my-project 4.3.3 ``` -------------------------------- ### Install Sake CLI Wrapper Source: https://docs.silverstripe.org/en/4/developer_guides/cli This command shows how to install the `sake` script, a wrapper for `cli-script.php`, by copying it to the system's binary directory. This process is specific to UNIX-like systems. ```bash cd your-webroot/ sudo ./vendor/bin/sake installsake ``` -------------------------------- ### Add Modules to Silverstripe Project Source: https://docs.silverstripe.org/en/4/getting_started/composer Installs Silverstripe CMS modules into your project using Composer. You can specify the module name and optionally a version constraint to install a specific version or range of versions. For example, 'silverstripe/blog' can be installed with a version constraint like '^2'. ```bash composer require silverstripe/blog ``` ```bash composer require silverstripe/blog ^2 ``` -------------------------------- ### Set Up Custom GraphQL Server (PHP) Source: https://docs.silverstripe.org/en/4/developer_guides/graphql/getting_started/activating_the_server This example demonstrates how to set up a custom GraphQL server in Silverstripe CMS. It involves configuring a new controller instance with a specific schema key and then routing requests to this custom controller. ```php SilverStripe\Core\Injector\Injector: # ... SilverStripe\GraphQL\Controller.myNewSchema: class: SilverStripe\GraphQL\Controller constructor: schemaKey: myNewSchema ``` ```php SilverStripe\Control\Director: rules: 'my-graphql': '%$SilverStripe\GraphQL\Controller.myNewSchema' ``` -------------------------------- ### Create New Project with Silverstripe Installer Source: https://docs.silverstripe.org/en/4/getting_started/recipes This command demonstrates how to create a new Silverstripe CMS project using the `silverstripe/installer` recipe, specifying a version constraint. ```bash composer create-project silverstripe/installer myproject ^4 ``` -------------------------------- ### Silverstripe CMS Controller Functionality Source: https://docs.silverstripe.org/en/4/developer_guides Controllers are the backbone of Silverstripe CMS applications, handling URL routing to your templates. This guide provides reference documentation and code examples for controller implementation. ```php renderWith('Product_show'); } } ``` -------------------------------- ### Install and Run Silverstripe Pattern Library Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/cms_architecture Instructions to install dependencies and run the Silverstripe pattern library locally using Composer and Yarn. It also covers building a static version. ```bash composer install --prefer-source (cd vendor/silverstripe/asset-admin && yarn install) (cd vendor/silverstripe/campaign-admin && yarn install) (cd vendor/silverstripe/cms && yarn install) cd vendor/silverstripe/admin && yarn install && yarn pattern-lib ``` -------------------------------- ### Extending Silverstripe CMS with Extensions and Dependency Injection Source: https://docs.silverstripe.org/en/4/developer_guides Understand how to modify built-in functionality through Extensions, Subclassing, and Dependency Injection in Silverstripe CMS. This guide includes reference documentation and code examples. ```php addMiddleware(new MyCustomMiddleware()); // Pass the request to the application and get the response $response = $app->handle($request); // Output the response $response->output(); ``` -------------------------------- ### Silverstripe CMS Integration and Web Services Source: https://docs.silverstripe.org/en/4/developer_guides Integrate other web services within your Silverstripe CMS application or make your Silverstripe CMS data available. This guide includes reference documentation and examples for API integration. ```php push([ 'id' => $product->ID, 'title' => $product->Title, 'price' => $product->Price->Nice(), ]); } return $this->customise(['data' => $list])->renderWith('JSON'); } ``` -------------------------------- ### GraphQL: Initial Product Query Source: https://docs.silverstripe.org/en/4/developer_guides/graphql/working_with_dataobjects/inheritance An example GraphQL query to read products and their prices. This query assumes a straightforward schema without inheritance complexities. ```GraphQL query { readProducts { nodes { price } } } ``` -------------------------------- ### Handling HTTP Requests with Silverstripe Application Source: https://docs.silverstripe.org/en/4/developer_guides/execution_pipeline/app_object_and_kernel Provides an example of setting up and handling an HTTP request using Silverstripe's HTTPApplication, including middleware. ```php use SilverStripe\Control\HTTPApplication; use SilverStripe\Control\HTTPRequestBuilder; use SilverStripe\Core\CoreKernel; use SilverStripe\Core\Startup\ErrorControlChainMiddleware; require __DIR__ . '/vendor/autoload.php'; // Build request and detect flush $request = HTTPRequestBuilder::createFromEnvironment(); // Default application $kernel = new CoreKernel(BASE_PATH); $app = new HTTPApplication($kernel); $app->addMiddleware(new ErrorControlChainMiddleware($app)); $response = $app->handle($request); $response->output(); ``` -------------------------------- ### Deploy GraphQL Schema Source: https://docs.silverstripe.org/en/4/developer_guides/graphql/getting_started This section provides instructions on how to deploy your GraphQL schema to a test or production environment. It's the final step in making your API accessible. ```markdown ##### __Deploying the schema Deploy your GraphQL schema to a test or production environment ``` -------------------------------- ### Customizing Silverstripe CMS Admin Interface Source: https://docs.silverstripe.org/en/4/developer_guides Extend the admin view to provide custom behavior or new features for CMS and admin users in Silverstripe CMS. This guide includes reference documentation and examples for admin customization. ```php assertTrue(true); } } ``` -------------------------------- ### Run Homepage Controller via Sake Source: https://docs.silverstripe.org/en/4/developer_guides/cli This command uses the `sake` utility to execute the homepage controller, effectively rendering the site's main page from the command line. ```bash sake / ``` -------------------------------- ### Perform GET Request in Silverstripe Source: https://docs.silverstripe.org/en/4/developer_guides/testing/functional_testing Executes a GET request on a specified URL and returns the HTTP response. This action also updates the current page to reflect the response. It's a fundamental part of testing controller logic that requires web requests. ```php $page = $this->get($url); ``` -------------------------------- ### Add Clearer Prerelease Installation Instructions Source: https://docs.silverstripe.org/en/4/Changelogs/4 This commit adds more explicit and clearer instructions for installing Silverstripe CMS prereleases. This aims to improve the user experience for those testing pre-release versions. ```php Add clearer instructions for prerelease installation ``` -------------------------------- ### jQuery.Entwine Highlighter Example Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/javascript_development Demonstrates how to use jQuery.entwine to create a 'Highlighter' behavior for buttons, allowing customization of foreground and background colors. ```JavaScript (function ($) { $(':button').entwine({ Foreground: 'red', Background: 'yellow', highlight() { this.css('background', this.getBackground()); this.css('color', this.getForeground()); } }); }(jQuery)); ``` -------------------------------- ### Initializing and Pushing a Git Repository Source: https://docs.silverstripe.org/en/4/developer_guides/extending/modules These Git commands initialize a new repository in the module's root directory, stage all files, create the initial commit, link it to a remote GitHub repository, and push the changes. ```bash git init git add -A git commit -m 'first commit' git remote add origin git@github.com:my_vendor/nice_feature.g.it git push -u origin master ``` -------------------------------- ### Get a Cookie Value in Silverstripe CMS Source: https://docs.silverstripe.org/en/4/developer_guides/cookies_and_sessions/cookies Provides an example of how to retrieve the value of a specific cookie by its name using the Cookie::get() method. ```php use SilverStripe\Control\Cookie; Cookie::get($name); // Cookie::get('MyApplicationPreference'); // returns 'Yes' ``` -------------------------------- ### Placeholder for Silverstripe History Viewer Frontend Boot File Source: https://docs.silverstripe.org/en/4/developer_guides/model/versioning This JavaScript file, `app/client/src/boot/index.js`, serves as the entry point for the frontend build process in a Silverstripe CMS project. It is intended to be populated with code that initializes the history viewer and other frontend functionalities. ```javascript // We'll populate this file later - for now we just need it to be sure our build setup works. ``` -------------------------------- ### jQuery.Entwine Usage Examples Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/javascript_development Illustrates common usage patterns for jQuery.entwine, including calling methods with default options, setting properties, and retrieving property values. ```JavaScript (function ($) { // call with default options $(':button').entwine().highlight(); // set options for existing and new instances $(':button').entwine().setBackground('green'); // get property $(':button').entwine().getBackground(); }(jQuery)); ``` -------------------------------- ### Configure Database Name Selection - Silverstripe Source: https://docs.silverstripe.org/en/4/getting_started/environment_management The SS_DATABASE_CHOOSE_NAME variable enables automatic database name selection based on the installation folder, simplifying setup and preventing manual configuration errors. ```php ; Automatically choose database name based on folder name ; SS_DATABASE_CHOOSE_NAME=true ; Use grandparent folder for database name ; SS_DATABASE_CHOOSE_NAME=3 ``` -------------------------------- ### Clearer Sysadmin Guidance for Packaging Source: https://docs.silverstripe.org/en/4/changelogs/4 Offers clearer guidance for system administrators regarding the 'packaging' process. This aims to simplify deployment and management tasks. ```php * 2021-06-01 fa3c5e6fe Clearer sysadmin guidance for "packaging" (#9960) (Ingo Schommer) ``` -------------------------------- ### Silverstripe CMS Templating and Theme Development Source: https://docs.silverstripe.org/en/4/developer_guides This guide showcases the Silverstripe CMS template engine and teaches you how to build your own themes. It includes reference documentation and code snippets for creating custom templates. ```html <%-- Example Silverstripe Template --%>

$Title

Price: $Price.Nice% <% if HasCategory %>

Category: $Category.Title

<% end_if %>
``` -------------------------------- ### Writing Silverstripe CMS Functional Tests Source: https://docs.silverstripe.org/en/4/developer_guides/testing Provides an example of how to structure a functional test in Silverstripe CMS. Functional tests are used to test the behavior of controllers and their interactions. ```php get('MyController/myAction'); // Add assertions here to check the response $this->assertEquals(200, $response->getStatusCode()); } } ``` -------------------------------- ### Install Static Publisher with Queue Module Source: https://docs.silverstripe.org/en/4/developer_guides/performance/static_publishing This snippet shows the Composer command to install the 'Static Publisher with Queue' module, which provides the functionality for static publishing in Silverstripe CMS. ```bash composer require silverstripe/static-exporter ``` -------------------------------- ### Custom PHPUnit Configuration for Silverstripe CMS Source: https://docs.silverstripe.org/en/4/developer_guides/testing/unit_testing An example of a custom phpunit.xml file for Silverstripe CMS projects. This configuration specifies the bootstrap file, test suites, and group exclusions. ```xml app/tests sanitychecks ``` -------------------------------- ### Configure Allowed Methods for CORS Source: https://docs.silverstripe.org/en/4/developer_guides/graphql/security_and_best_practices/cors This code example demonstrates how to configure the 'Access-Control-Allow-Methods' header for SilverStripe GraphQL. It specifies the HTTP request methods that the GraphQL server will handle, such as GET, PUT, DELETE, and OPTIONS. ```yaml Allow-Methods: 'GET, PUT, DELETE, OPTIONS' ``` -------------------------------- ### Redux Reducer and Dispatch Example Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/reactjs_redux_and_graphql Provides an example of a Redux reducer function and how to dispatch actions to modify the application state. It includes a simple counter reducer and demonstrates subscribing to state changes. ```JavaScript // reducer function counter(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } const store = createStore(counter); // subscribe to an action store.subscribe(() => { const state = store.g.etState(); // ... do something with the state here }); // Call an action - in this case increment the state from 0 to 1 store.dispatch({ type: 'INCREMENT' }); ``` -------------------------------- ### Silverstripe CMS Disable CSRF Security Token Source: https://docs.silverstripe.org/en/4/developer_guides/forms/form_security Provides an example of how to disable the automatic SecurityID (CSRF protection) for a Silverstripe CMS Form. This should only be done for GET requests that do not modify the database. ```php $form = new Form(/* ... */); $form->disableSecurityToken(); ``` -------------------------------- ### Composer JSON Configuration Example Source: https://docs.silverstripe.org/en/4/getting_started/composer An example of a composer.json file for a Silverstripe CMS project, showing how to define project name, description, required PHP versions, Silverstripe modules, development dependencies, and stability settings. ```json { "name": "silverstripe\/installer", "description": "The Silverstripe Framework Installer", "require": { "php": ">=7.3", "silverstripe\/cms": "^4", "silverstripe\/framework": "^4", "silverstripe-themes\/simple": "^3" }, "require-dev": { "silverstripe\/docsviewer": "^3" }, "minimum-stability": "dev", "prefer-stable": true } ``` -------------------------------- ### Get Overridden Class Instance in PHP Source: https://docs.silverstripe.org/en/4/developer_guides/extending/injector Shows how to retrieve an instance of a class managed by the Injector API in PHP after it has been overridden via configuration. The example retrieves 'MyClass', which is expected to be an instance of 'MyBetterClass'. ```PHP use App\MyClass; use SilverStripe\Core\Injector\Injector; // sets up MyClass as a singleton $object = Injector::inst()->get(MyClass::class); // $object is an instance of MyBetterClass ``` -------------------------------- ### Create a Silverstripe Controller Class Source: https://docs.silverstripe.org/en/4/developer_guides/controllers/introduction This snippet demonstrates how to create a basic Controller class in Silverstripe CMS by subclassing the base `Controller`. It defines allowed actions and includes example methods for `index` and `players`. ```php namespace App\Control; use SilverStripe\Control\Controller; use SilverStripe\Control\HTTPRequest; class TeamController extends Controller { private static $allowed_actions = [ 'players', 'index', ]; public function index(HTTPRequest $request) { // ... } public function players(HTTPRequest $request) { print_r($request->allParams()); } } ``` -------------------------------- ### Get Overridden Class Instance in PHP Source: https://docs.silverstripe.org/en/4/developer_guides/extending/Injector Shows how to retrieve an instance of a class managed by the Injector API in PHP after it has been overridden via configuration. The example retrieves 'MyClass', which is expected to be an instance of 'MyBetterClass'. ```PHP use App\MyClass; use SilverStripe\Core\Injector\Injector; // sets up MyClass as a singleton $object = Injector::inst()->get(MyClass::class); // $object is an instance of MyBetterClass ``` -------------------------------- ### Build GraphQL Schema Source: https://docs.silverstripe.org/en/4/developer_guides/graphql/getting_started This section covers the process of transforming your schema configuration into executable code. It's the step where your API's structure becomes functional. ```markdown ##### __Building the schema Turn your schema configuration into executable code ``` -------------------------------- ### Use jQuery Highlight Plugin Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/javascript_development Demonstrates how to use the 'highlight' jQuery plugin to style elements. It shows examples of applying default colors, custom colors, and setting global default colors for the plugin. ```javascript (function ($) { // Highlight all buttons with default colours jQuery(':button').highlight(); // Highlight all buttons with green background jQuery(':button').highlight({ background: 'green' }); // Set all further highlight() calls to have a green background $.fn.highlight.defaults.background = 'green'; }(jQuery)); ``` -------------------------------- ### Silverstripe CMS Simple Contact Form with Email Submission Source: https://docs.silverstripe.org/en/4/developer_guides/forms Create a straightforward contact form that sends submitted messages via email. This example covers the basic setup of form fields, submission handling, and email dispatch. ```php setRequired(true), EmailField::create('Email', 'Your Email')->setRequired(true), TextareaField::create('Message', 'Message')->setRequired(true) ]); $actions = FieldList::create([ FormAction::create('sendEmail', 'Send Message') ]); $form = Form::create(null, 'ContactForm', $fields, $actions); return $form; } public function sendEmail($data, Form $form) { $email = Email::create(); $email->setTo('admin@example.com'); // Set recipient email $email->setFrom($data['Email']); $email->setSubject('New Contact Form Submission: ' . $data['Name']); $email->setBody($data['Message']); try { $email->send(); $form->sessionMessage('Thank you for your message. We will be in touch soon!', 'good'); } catch (Exception $e) { $form->sessionMessage('There was a problem sending your message. Please try again later.', 'bad'); } return $this->redirectBack(); } ``` -------------------------------- ### Set Up Changelog for Silverstripe Recipe Kitchen Sink Source: https://docs.silverstripe.org/en/4/changelogs/beta/4 This commit sets up the changelog for the silverstripe/recipe-kitchen-sink release. ```bash git commit -m "cfeb879 Set up changelog (Maxime Rainville)" ``` -------------------------------- ### List Child Pages (Combined Modifiers) Source: https://docs.silverstripe.org/en/4/contributing/documentation Provides an example of combining multiple modifiers (`Exclude`, `asList`, `includeFolders`, `reverse`) with the `[CHILDREN]` tag to customize the output format and content of the child page listing. ```markdown [CHILDREN Exclude="How_tos" asList includeFolders reverse] ``` -------------------------------- ### Editing Files Directly on GitHub Source: https://docs.silverstripe.org/en/4/contributing/code For minor fixes like typos, you can edit files directly through the GitHub web interface without needing a local development setup. After editing, GitHub will guide you through creating a pull request. ```git git clone https://github.com/silverstripe/silverstripe-cms.git cd silverstripe-cms # Make your changes git add . git commit -m "Your commit message" git push origin your-branch-name ``` -------------------------------- ### Core Committer Onboarding Process Source: https://docs.silverstripe.org/en/4/changelogs/4 Documents the process for onboarding core committers. This is an internal process documentation aimed at streamlining the contribution workflow. ```php * 2021-08-10 0128bbd80 core committer onboarding process (brynwhyman) ``` -------------------------------- ### Validate Numeric Input with jQuery.metadata() Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/javascript_development This example shows how to use the jQuery.metadata plugin to define and validate numeric input fields. It checks if the input value falls within the specified min and max values defined in the HTML attributes. ```html Copy ``` ```javascript Copy$('.restricted-text').bind('change', function (event) { const value = e.target.value; if (value < $(this).metadata().min || value > $(this).metadata().max) { /* Do something about the value being invalid */ event.preventDefault(); } }); ``` -------------------------------- ### Clearer Sysadmin Guidance for Packaging in SilverStripe Framework Source: https://docs.silverstripe.org/en/4/changelogs/rc/4 Provides clearer guidance for system administrators regarding 'packaging' within the silverstripe/framework, as noted in commit #9960. This aims to simplify the packaging process for users. ```php fa3c5e6fe Clearer sysadmin guidance for "packaging" (#9960) (Ingo Schommer) ``` -------------------------------- ### Documenting Silverstripe jQuery.Entwine with JSDoc Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/javascript_development This example shows how to use JSDoc comments to document a Silverstripe jQuery.Entwine component, including custom events, properties, public methods, and private methods. It illustrates the structure for defining component APIs and their behavior. ```javascript /** * Available Custom Events: * * * @class Main LeftAndMain interface with some control panel and an edit form. * @name ss.LeftAndMain */ $('.LeftAndMain').entwine('ss', ($) => /** @lends ss.LeftAndMain */ ({ /** * Reference to some property * @type Number */ MyProperty: 123, /** * Renders the provided data into an unordered list. * * @param {Object} data * @param {String} status * @return {String} HTML unordered list */ publicMethod(data, status) { return ''; }, /** * Won't show in documentation, but still worth documenting. * * @return {String} Something else. */ _privateMethod() { // ... } }) ); ``` -------------------------------- ### Manual _ss_environment.php to .env Conversion Example Source: https://docs.silverstripe.org/en/4/upgrading/upgrading_project Demonstrates the manual conversion of `_ss_environment.php` definitions to `KEY=VALUE` pairs in a `.env` file. Highlights the replacement of `$_FILE_TO_URL_MAPPING` with `SS_BASE_URL`. ```php // Environment define('SS_ENVIRONMENT_TYPE', 'dev'); define('SS_DEFAULT_ADMIN_USERNAME', 'admin'); define('SS_DEFAULT_ADMIN_PASSWORD', 'password'); $_FILE_TO_URL_MAPPING[__DIR__] = 'http://localhost'; // Database define('SS_DATABASE_CHOOSE_NAME', true); define('SS_DATABASE_CLASS', 'MySQLDatabase'); define('SS_DATABASE_USERNAME', 'root'); define('SS_DATABASE_PASSWORD', ''); define('SS_DATABASE_SERVER', '127.0.0.1'); ``` ```dotenv ## Environment SS_ENVIRONMENT_TYPE="dev" SS_DEFAULT_ADMIN_USERNAME="admin" SS_DEFAULT_ADMIN_PASSWORD="password" SS_BASE_URL="http://localhost/" ## Database SS_DATABASE_CHOOSE_NAME="true" SS_DATABASE_CLASS="MySQLDatabase" SS_DATABASE_USERNAME="root" SS_DATABASE_PASSWORD="" SS_DATABASE_SERVER="127.0.0.1" ``` -------------------------------- ### Create jQuery UI Highlight Widget Source: https://docs.silverstripe.org/en/4/developer_guides/customising_the_admin_interface/javascript_development Implements a jQuery UI widget named 'myHighlight' that extends basic jQuery plugins with more structure for interactive elements. It includes methods for getting and setting blink behavior and initializes element styles. ```javascript (function ($) { $.widget('ui.myHighlight', { getBlink() { return this._getData('blink'); }, setBlink(blink) { this._setData('blink', blink); if (blink) { this.element.wrapInner(''); } else { this.element.html(this.element.children().html()); } }, _init() { // grab the default value and use it this.element.css('background', this.options.background); this.element.css('color', this.options.foreground); this.setBlink(this.options.blink); } }); // For demonstration purposes, this is also possible with jQuery.css() $.ui.myHighlight.getter = 'getBlink'; $.ui.myHighlight.defaults = { foreground: 'red', background: 'yellow', blink: false }; }(jQuery)); ``` -------------------------------- ### Activate Default GraphQL Server Source: https://docs.silverstripe.org/en/4/developer_guides/graphql/getting_started This section explains how to activate the default GraphQL server that is pre-configured with the Silverstripe GraphQL module. It's a crucial first step in setting up your API. ```markdown ##### __Activating the default server Open up the default server that comes pre-configured with the module ```