diff --git a/docs/en/00_Getting_Started/01_Installation/04_Other_installation_Options/Mac_OSX_Homebrew.md b/docs/en/00_Getting_Started/01_Installation/04_Other_installation_Options/Mac_OSX_Homebrew.md index 4b7476230..95fe6af42 100644 --- a/docs/en/00_Getting_Started/01_Installation/04_Other_installation_Options/Mac_OSX_Homebrew.md +++ b/docs/en/00_Getting_Started/01_Installation/04_Other_installation_Options/Mac_OSX_Homebrew.md @@ -79,8 +79,8 @@ since it makes permissions easier to handle when running commands both from the command line and through the web server. Find and adjust the following options, replacing the `` placeholder: - User - Group staff + user + Group staff Now start the web server: diff --git a/docs/en/00_Getting_Started/01_Installation/How_To/Configure_Lighttpd.md b/docs/en/00_Getting_Started/01_Installation/How_To/Configure_Lighttpd.md index 2de07d466..77ac9a127 100644 --- a/docs/en/00_Getting_Started/01_Installation/How_To/Configure_Lighttpd.md +++ b/docs/en/00_Getting_Started/01_Installation/How_To/Configure_Lighttpd.md @@ -3,33 +3,33 @@ 1. Lighttpd works fine so long as you provide a custom config. Add the following to lighttpd.conf **BEFORE** installing Silverstripe. Replace "yoursite.com" and "/home/yoursite/public_html/" below. - + $HTTP["host"] == "yoursite.com" { server.document-root = "/home/yoursite/public_html/" - + # Disable directory listings dir-listing.activate = "disable" - + # Deny access to template files url.access-deny += ( ".ss" ) static-file.exclude-extensions += ( ".ss" ) - + # Deny access to SilverStripe command-line interface $HTTP["url"] =~ "^/vendor/silverstripe/framework/cli-script.php" { url.access-deny = ( "" ) } - + # Disable FastCGI in assets directory (so that PHP files are not executed) $HTTP["url"] =~ "^/assets/" { fastcgi.server = () } - + # Rewrite URLs so they are nicer url.rewrite-once = ( "^/.*\.[A-Za-z0-9]+.*?$" => "$0", "^/(.*?)(\?|$)(.*)" => "/index.php?$3" ) - + # Show SilverStripe error page server.error-handler-404 = "/index.php" } @@ -48,7 +48,7 @@ recommend using subdomains instead if you can, for exampe: site1.yourdomain.com things a lot simpler, as you just use two of the above host example blocks. But if you really must run multiple copies of Silverstripe on the same host, you can use something like this (be warned, it's quite nasty): - + $HTTP["host"] == "yoursite.com" { url.rewrite-once = ( "(?i)(/copy1/.*\.([A-Za-z0-9]+))(.*?)$" => "$0", diff --git a/docs/en/00_Getting_Started/01_Installation/How_To/Configure_Nginx.md b/docs/en/00_Getting_Started/01_Installation/How_To/Configure_Nginx.md index 436bf57e1..fdd45c4c3 100644 --- a/docs/en/00_Getting_Started/01_Installation/How_To/Configure_Nginx.md +++ b/docs/en/00_Getting_Started/01_Installation/How_To/Configure_Nginx.md @@ -21,21 +21,21 @@ But enough of the disclaimer, on to the actual configuration — typically in `n server { listen 80; root /path/to/ss/folder; - + server_name site.com www.site.com; # Defend against SS-2015-013 -- http://www.silverstripe.org/software/download/security-releases/ss-2015-013 if ($http_x_forwarded_host) { return 400; } - + location / { try_files $uri /index.php?$query_string; } - + error_page 404 /assets/error-404.html; error_page 500 /assets/error-500.html; - + location ^~ /assets/ { location ~ /\. { deny all; @@ -43,7 +43,7 @@ But enough of the disclaimer, on to the actual configuration — typically in `n sendfile on; try_files $uri index.php?$query_string; } - + location ~ /framework/.*(main|rpc|tiny_mce_gzip)\.php$ { fastcgi_keep_conn on; fastcgi_pass 127.0.0.1:9000; @@ -51,45 +51,45 @@ But enough of the disclaimer, on to the actual configuration — typically in `n fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } - + location ~ /(mysite|framework|cms)/.*\.(php|php3|php4|php5|phtml|inc)$ { deny all; } - + location ~ /\.. { deny all; } - + location ~ \.ss$ { satisfy any; allow 127.0.0.1; deny all; } - + location ~ web\.config$ { deny all; } - + location ~ \.ya?ml$ { deny all; } - + location ^~ /vendor/ { deny all; } - + location ~* /silverstripe-cache/ { deny all; } - + location ~* composer\.(json|lock)$ { deny all; } - + location ~* /(cms|framework)/silverstripe_version$ { deny all; } - + location ~ \.php$ { fastcgi_keep_conn on; fastcgi_pass 127.0.0.1:9000; diff --git a/docs/en/00_Getting_Started/01_Installation/How_To/MySQL_SSL_Support.md b/docs/en/00_Getting_Started/01_Installation/How_To/MySQL_SSL_Support.md index c47e358a6..8ef127e20 100644 --- a/docs/en/00_Getting_Started/01_Installation/How_To/MySQL_SSL_Support.md +++ b/docs/en/00_Getting_Started/01_Installation/How_To/MySQL_SSL_Support.md @@ -34,11 +34,11 @@ The following commands will work on Linux/Unix based servers. For other servers :::bash - + # Create directory sudo mkdir ssl cd ssl - + # Generate CA key and CA cert sudo openssl genrsa 2048 | sudo tee -a ca-key.pem sudo openssl req -new -x509 -nodes -days 365000 -key ca-key.pem -out ca-cert.pem @@ -47,20 +47,20 @@ The following commands will work on Linux/Unix based servers. For other servers # IMPORTANT: the common name of the certificate should match the domain name of your host! sudo openssl rsa -in server-key.pem -out server-key.pem sudo openssl req -newkey rsa:2048 -days 365000 -nodes -keyout server-key.pem -out server-req.pem - + # Generate and sign SERVER certificate sudo openssl x509 -req -in server-req.pem -days 365000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out server-cert.pem - + # Generate CLIENT key and certificate signing request sudo openssl rsa -in client-key.pem -out client-key.pem sudo openssl req -newkey rsa:2048 -days 365000 -nodes -keyout client-key.pem -out client-req.pem - + # Generate and sign CLIENT certificate sudo openssl x509 -req -in client-req.pem -days 365000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out client-cert.pem - + # Verify validity of generated certificates sudo openssl verify -CAfile ca-cert.pem server-cert.pem client-cert.pem - +
After generating the certificates, make sure to set the correct permissions to prevent unauthorized access to your keys! @@ -128,7 +128,7 @@ On your Silverstripe instance: :::bash # Secure copy over SSH via rsync command. You may use an alternative method if desired. rsync -avP user@db1.example.com:/path/to/client/certs /path/to/secure/folder - + # Depending on your web server configuration, allow web server to read to SSL files sudo chown -R www-data:www-data /path/to/secure/folder sudo chmod 750 /path/to/secure/folder @@ -144,14 +144,14 @@ Add or edit your `_ss_environment.php` configuration file. (See [Environment Man :::php '); - + // These define the paths to the SSL key, certificate, and CA certificate bundle. define('SS_DATABASE_SSL_KEY', '/home/newdrafts/mysqlssltest/client-key.pem'); define('SS_DATABASE_SSL_CERT', '/home/newdrafts/mysqlssltest/client-cert.pem'); @@ -160,10 +160,10 @@ Add or edit your `_ss_environment.php` configuration file. (See [Environment Man // When using SSL connections, you also need to supply a username and password to override the default settings define('SS_DEFAULT_ADMIN_USERNAME', 'username'); define('SS_DEFAULT_ADMIN_PASSWORD', 'password'); - - + + When running the installer, make sure to check on the `Use _ss_environment file for configuration` option under the `Database Configuration` section to use the environment file. ## Conclusion -That's it! We hope that this article was able to help you configure your remote MySQL SSL secure database connection. \ No newline at end of file +That's it! We hope that this article was able to help you configure your remote MySQL SSL secure database connection. diff --git a/docs/en/00_Getting_Started/01_Installation/How_To/Setup_Nginx_and_HHVM.md b/docs/en/00_Getting_Started/01_Installation/How_To/Setup_Nginx_and_HHVM.md index eab1096c4..19b023a95 100644 --- a/docs/en/00_Getting_Started/01_Installation/How_To/Setup_Nginx_and_HHVM.md +++ b/docs/en/00_Getting_Started/01_Installation/How_To/Setup_Nginx_and_HHVM.md @@ -46,14 +46,14 @@ Create `/etc/nginx/silverstripe.conf` and add this configuration: fastcgi_buffer_size 32k; fastcgi_busy_buffers_size 64k; fastcgi_buffers 4 32k; - + location / { try_files $uri /index.php?$query_string; } - + error_page 404 /assets/error-404.html; error_page 500 /assets/error-500.html; - + location ^~ /assets/ { try_files $uri =404; } @@ -99,10 +99,10 @@ e.g. `/etc/nginx/sites-enabled/mysite`: listen 80; root /var/www/mysite; server_name www.mysite.com; - + error_log /var/log/nginx/mysite.error.log; access_log /var/log/nginx/mysite.access.log; - + include /etc/nginx/hhvm.conf; include /etc/nginx/silverstripe.conf; } diff --git a/docs/en/01_Tutorials/01_Building_A_Basic_Site.md b/docs/en/01_Tutorials/01_Building_A_Basic_Site.md index 9a4404a54..bd62a56a5 100644 --- a/docs/en/01_Tutorials/01_Building_A_Basic_Site.md +++ b/docs/en/01_Tutorials/01_Building_A_Basic_Site.md @@ -112,27 +112,27 @@ for a template file in the *simple/templates* folder, with the name `` Open *themes/simple/templates/Page.ss*. It uses standard HTML apart from these exceptions: ```ss - <% base_tag %> +<% base_tag %> ``` The base_tag variable is replaced with the HTML [base element](http://www.w3.org/TR/html401/struct/links.html#h-12.4). This ensures the browser knows where to locate your site's images and css files. ```ss - $Title - $SiteConfig.Title +$Title +$SiteConfig.Title ``` These two variables are found within the html `` tag, and are replaced by the "Page Name" and "Settings -> Site Title" fields in the CMS. ```ss - $MetaTags +$MetaTags ``` The MetaTags variable will add meta tags, which are used by search engines. You can define your meta tags in the tab fields at the bottom of the content editor in the CMS. ```ss - $Layout +$Layout ``` The Layout variable is replaced with the contents of a template file with the same name as the page type we are using. @@ -140,8 +140,8 @@ The Layout variable is replaced with the contents of a template file with the sa Open *themes/simple/templates/Layout/Page.ss*. You will see more HTML and more SilverStripe template replacement tags and variables. ```ss - $Content -``` +$Content +``` The Content variable is replaced with the content of the page currently being viewed. This allows you to make all changes to your site's content in the CMS. @@ -151,7 +151,7 @@ browser and are either prefixed with a dollar sign ($) or placed between SilverStripe template tags: ```ss - <% %> +<% %> ``` **Flushing the cache** @@ -169,8 +169,8 @@ Open up *themes/simple/templates/Includes/Navigation.ss* The Menu for our site is created using a **loop**. Loops allow us to iterate over a data set, and render each item using a sub-template. ```ss - <% loop $Menu(1) %> -``` +<% loop $Menu(1) %> +``` returns a set of first level menu items. We can then use the template variable *$MenuTitle* to show the title of the page we are linking to, *$Link* for the URL of the page, and `$isSection` and `$isCurrent` to help style our menu with CSS (explained in more detail shortly). @@ -179,13 +179,13 @@ returns a set of first level menu items. We can then use the template variable ```ss - <ul> - <% loop $Menu(1) %> - <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> - <a href="$Link" title="$Title.XML">$MenuTitle.XML</a> - </li> - <% end_loop %> - </ul> +<ul> + <% loop $Menu(1) %> + <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> + <a href="$Link" title="$Title.XML">$MenuTitle.XML</a> + </li> + <% end_loop %> +</ul> ``` Here we've created an unordered list called *Menu1*, which *themes/simple/css/layout.css* will style into the menu. @@ -195,8 +195,6 @@ This creates the navigation at the top of the page: ![](../_images/tutorial1_menu.jpg) - - ### Highlighting the current page A useful feature is highlighting the current page the user is looking at. We can do this by using the `is` methods `$isSection` and `$isCurrent`. @@ -204,15 +202,15 @@ A useful feature is highlighting the current page the user is looking at. We can For example, if you were here: "Home > Company > Staff > Bob Smith", you may want to highlight 'Company' to say you are in that section. ```ss - <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> - <a href="$Link" title="$Title.XML">$MenuTitle.XML</a> - </li> +<li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> + <a href="$Link" title="$Title.XML">$MenuTitle.XML</a> +</li> ``` you will then be able to target a section in css (*simple/css/layout.css*), e.g.: ```css - .section { background:#ccc; } +.section { background:#ccc; } ``` ## A second level of navigation @@ -235,16 +233,16 @@ Great, we now have a hierarchical site structure! Let's look at how this is crea Adding a second level menu is very similar to adding the first level menu. Open up */themes/simple/templates/Includes/Sidebar.ss* template and look at the following code: ```ss - <ul> - <% loop $Menu(2) %> - <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> - <a href="$Link" title="Go to the $Title.XML page"> - <span class="arrow">→</span> - <span class="text">$MenuTitle.XML</span> - </a> - </li> - <% end_loop %> - </ul> +<ul> + <% loop $Menu(2) %> + <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> + <a href="$Link" title="Go to the $Title.XML page"> + <span class="arrow">→</span> + <span class="text">$MenuTitle.XML</span> + </a> + </li> + <% end_loop %> +</ul> ``` This should look very familiar. It is the same idea as our first menu, except the loop block now uses *Menu(2)* instead of *Menu(1)*. @@ -257,20 +255,20 @@ Look again in the *Sidebar.ss* file and you will see that the menu is surrounded like this: ```ss - <% if $Menu(2) %> - ... - <ul> - <% loop $Menu(2) %> - <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> - <a href="$Link" title="Go to the $Title.XML page"> - <span class="arrow">→</span> - <span class="text">$MenuTitle.XML</span> - </a> - </li> - <% end_loop %> - </ul> - ... - <% end_if %> +<% if $Menu(2) %> + ... + <ul> + <% loop $Menu(2) %> + <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> + <a href="$Link" title="Go to the $Title.XML page"> + <span class="arrow">→</span> + <span class="text">$MenuTitle.XML</span> + </a> + </li> + <% end_loop %> + </ul> + ... +<% end_if %> ``` The if block only includes the code inside it if the condition is true. In this case, it checks for the existence of @@ -282,11 +280,11 @@ Now that we have two levels of navigation, it would also be useful to include so Open up */themes/simple/templates/Includes/BreadCrumbs.ss* template and look at the following code: ```ss - <% if $Level(2) %> - <div id="Breadcrumbs"> - $Breadcrumbs - </div> - <% end_if %> +<% if $Level(2) %> + <div id="Breadcrumbs"> + $Breadcrumbs + </div> +<% end_if %> ``` Breadcrumbs are only useful on pages that aren't in the top level. We can ensure that we only show them if we aren't in @@ -295,7 +293,7 @@ the top level with another if statement. The *Level* page control allows you to get data from the page's parents, e.g. if you used *Level(1)*, you could use: ```ss - $Level(1).Title +$Level(1).Title ``` to get the top level page title. In this case, we merely use it to check the existence of a second level page: if one exists then we include breadcrumbs. @@ -309,28 +307,27 @@ Feel free to experiment with the if and loop statements. For example, you could The following example runs an if statement and a loop on *Children*, checking to see if any sub-pages exist within each top level navigation item. You will need to come up with your own CSS to correctly style this approach. ```ss - <ul> - <% loop $Menu(1) %> - <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> - <a href="$Link" title="$Title.XML">$MenuTitle.XML</a> - <% if $Children %> - <ul> - <% loop $Children %> - <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> - <a href="$Link" title="Go to the $Title.XML page"> - <span class="arrow">→</span> - <span class="text">$MenuTitle.XML</span> - </a> - </li> - <% end_loop %> - </ul> - <% end_if %> - </li> - <% end_loop %> - </ul> +<ul> + <% loop $Menu(1) %> + <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> + <a href="$Link" title="$Title.XML">$MenuTitle.XML</a> + <% if $Children %> + <ul> + <% loop $Children %> + <li class="<% if $isCurrent %>current<% else_if $isSection %>section<% end_if %>"> + <a href="$Link" title="Go to the $Title.XML page"> + <span class="arrow">→</span> + <span class="text">$MenuTitle.XML</span> + </a> + </li> + <% end_loop %> + </ul> + <% end_if %> + </li> + <% end_loop %> +</ul> ``` - ## Using a different template for the home page So far, a single template layout *Layouts/Page.ss* is being used for the entire site. This is useful for the purpose of this @@ -393,21 +390,21 @@ To create a new template layout, create a copy of *Page.ss* (found in *themes/si First, we don't need the breadcrumbs and the secondary menu for the homepage. Let's remove them: ```ss - <% include SideBar %> +<% include SideBar %> ``` We'll also replace the title text with an image. Find this line: ```ss - <h1>$Title</h1> +<h1>$Title</h1> ``` and replace it with: ```ss - <div id="Banner"> - <img src="http://www.silverstripe.org/assets/SilverStripe-200.png" alt="Homepage image" /> - </div> +<div id="Banner"> + <img src="http://www.silverstripe.org/assets/SilverStripe-200.png" alt="Homepage image" /> +</div> ``` Your Home page should now look like this: diff --git a/docs/en/01_Tutorials/02_Extending_A_Basic_Site.md b/docs/en/01_Tutorials/02_Extending_A_Basic_Site.md index 12451c9f8..6f468567e 100644 --- a/docs/en/01_Tutorials/02_Extending_A_Basic_Site.md +++ b/docs/en/01_Tutorials/02_Extending_A_Basic_Site.md @@ -9,7 +9,6 @@ This tutorial is deprecated, and has been replaced by Lessons 4, 5, and 6 in the ## Overview - In the [first tutorial (Building a basic site)](/tutorials/building_a_basic_site) we learnt how to create a basic site using SilverStripe. This tutorial will build on that, and explore extending SilverStripe by creating our own page types. After doing this we should have a better understanding of how SilverStripe works. ## What are we working towards? @@ -68,24 +67,20 @@ We'll start with the *ArticlePage* page type. First we create the model, a class **mysite/code/ArticlePage.php** ```php - use Page; +class ArticlePage extends Page +{ + +} +``` + +**mysite/code/ArticlePageController.php** - class ArticlePage extends Page - { - - } -``` -**mysite/code/ArticlePageController.php** ```php - use PageController; - - class ArticlePageController extends PageController - { - - } -``` - +class ArticlePageController extends PageController +{ +} +``` Here we've created our data object/controller pair, but we haven't extended them at all. SilverStripe will use the template for the *Page* page type as explained in the first tutorial, so we don't need to specifically create the view for this page type. @@ -95,21 +90,19 @@ Let's create the *ArticleHolder* page type. **mysite/code/ArticleHolder.php** ```php - use Page; - - class ArticleHolder extends Page - { - private static $allowed_children = ['ArticlePage']; - } +class ArticleHolder extends Page +{ + private static $allowed_children = ['ArticlePage']; +} ``` -**mysite/code/ArticleHolderController.php** -```php - use PageController; - class ArticleHolderController extends PageController - { - - } +**mysite/code/ArticleHolderController.php** + +```php +class ArticleHolderController extends PageController +{ + +} ``` Here we have done something interesting: the *$allowed_children* field. This is one of a number of static fields we can define to change the properties of a page type. The *$allowed_children* field is an array of page types that are allowed @@ -132,17 +125,13 @@ the $db array to add extra fields to the database. It would be nice to know when it. Add a *$db* property definition in the *ArticlePage* class: ```php - use Page; - - class ArticlePage extends Page - { - private static $db = [ - 'Date' => 'Date', - 'Author' => 'Text' - ]; - - // ..... - } +class ArticlePage extends Page +{ + private static $db = [ + 'Date' => 'Date', + 'Author' => 'Text' + ]; +} ``` Every entry in the array is a *key => value* pair. The **key** is the name of the field, and the **value** is the type. See ["data types and casting"](/developer_guides/model/data_types_and_casting) for a complete list of types. @@ -157,43 +146,36 @@ When we rebuild the database, we will see that the *ArticlePage* table has been To add our new fields to the CMS we have to override the *getCMSFields()* method, which is called by the CMS when it creates the form to edit a page. Add the method to the *ArticlePage* class. ```php - use Page; - - class ArticlePage extends Page +class ArticlePage extends Page +{ + public function getCMSFields() { - // ... + $fields = parent::getCMSFields(); - public function getCMSFields() - { - $fields = parent::getCMSFields(); - - $dateField = new DateField('Date'); - $dateField->setConfig('showcalendar', true); - $fields->addFieldToTab('Root.Main', $dateField, 'Content'); - $fields->addFieldToTab('Root.Main', new TextField('Author'), 'Content'); - - return $fields; - } + $dateField = new DateField('Date'); + $dateField->setConfig('showcalendar', true); + $fields->addFieldToTab('Root.Main', $dateField, 'Content'); + $fields->addFieldToTab('Root.Main', new TextField('Author'), 'Content'); + + return $fields; } - - // ... - +} ``` Let's walk through this method. ```php - $fields = parent::getCMSFields(); -``` +$fields = parent::getCMSFields(); +``` Firstly, we get the fields from the parent class; we want to add fields, not replace them. The *$fields* variable returned is a [FieldList](api:SilverStripe\Forms\FieldList) object. ```php - $fields->addFieldToTab('Root.Main', new TextField('Author'), 'Content'); - $fields->addFieldToTab('Root.Main', new DateField('Date'), 'Content'); -``` +$fields->addFieldToTab('Root.Main', new TextField('Author'), 'Content'); +$fields->addFieldToTab('Root.Main', new DateField('Date'), 'Content'); +``` We can then add our new fields with *addFieldToTab*. The first argument is the tab on which we want to add the field to: @@ -208,8 +190,8 @@ We have added two fields: A simple [TextField](api:SilverStripe\Forms\TextField) There are many more fields available in the default installation, listed in ["form field types"](/developer_guides/forms/field_types/common_subclasses). ```php - return $fields; -``` +return $fields; +``` Finally, we return the fields to the CMS. If we flush the cache (by adding ?flush=1 at the end of the URL), we will be able to edit the fields in the CMS. @@ -227,51 +209,47 @@ To make the date field a bit more user friendly, you can add a dropdown calendar the date field will have the date format defined by your locale. ```php - use Page; - - class ArticlePage extends Page +class ArticlePage extends Page +{ + public function getCMSFields() { - - // ..... - - public function getCMSFields() - { - $fields = parent::getCMSFields(); + $fields = parent::getCMSFields(); + + $dateField = new DateField('Date', 'Article Date (for example: 20/12/2010)'); + $dateField->setConfig('showcalendar', true); + $dateField->setConfig('dateformat', 'dd/MM/YYYY'); - $dateField = new DateField('Date', 'Article Date (for example: 20/12/2010)'); - $dateField->setConfig('showcalendar', true); - $dateField->setConfig('dateformat', 'dd/MM/YYYY'); - - $fields->addFieldToTab('Root.Main', $dateField, 'Content'); - $fields->addFieldToTab('Root.Main', new TextField('Author', 'Author Name'), 'Content'); + $fields->addFieldToTab('Root.Main', $dateField, 'Content'); + $fields->addFieldToTab('Root.Main', new TextField('Author', 'Author Name'), 'Content'); - return $fields; - } + return $fields; + } +} ``` Let's walk through these changes. ```php - $dateField = new DateField('Date', 'Article Date (for example: 20/12/2010)'); -``` +$dateField = new DateField('Date', 'Article Date (for example: 20/12/2010)'); +``` *$dateField* is declared in order to change the configuration of the DateField. ```php - $dateField->setConfig('showcalendar', true); -``` +$dateField->setConfig('showcalendar', true); +``` By enabling *showCalendar* you show a calendar overlay when clicking on the field. ```php - $dateField->setConfig('dateformat', 'dd/MM/YYYY'); -``` +$dateField->setConfig('dateformat', 'dd/MM/YYYY'); +``` *dateFormat* allows you to specify how you wish the date to be entered and displayed in the CMS field. See the [DBDateField](api:SilverStripe\ORM\FieldType\DBDateField) documentation for more configuration options. ```php - $fields->addFieldToTab('Root.Main', new TextField('Author', 'Author Name'), 'Content'); -``` +$fields->addFieldToTab('Root.Main', new TextField('Author', 'Author Name'), 'Content'); +``` By default the field name *'Date'* or *'Author'* is shown as the title, however this might not be that helpful so to change the title, add the new title as the second argument. @@ -290,17 +268,17 @@ First, the template for displaying a single article: ```ss - <% include SideBar %> - <div class="content-container unit size3of4 lastUnit"> - <article> - <h1>$Title</h1> - <div class="news-details"> - <p>Posted on $Date.Nice by $Author</p> - </div> - <div class="content">$Content</div> - </article> - $Form - </div> +<% include SideBar %> +<div class="content-container unit size3of4 lastUnit"> + <article> + <h1>$Title</h1> + <div class="news-details"> + <p>Posted on $Date.Nice by $Author</p> + </div> + <div class="content">$Content</div> + </article> + $Form +</div> ``` Most of the code is just like the regular Page.ss, we include an informational div with the date and the author of the Article. @@ -323,22 +301,22 @@ We'll now create a template for the article holder. We want our news section to **themes/simple/templates/Layout/ArticleHolder.ss** ```ss - <% include SideBar %> - <div class="content-container unit size3of4 lastUnit"> +<% include SideBar %> +<div class="content-container unit size3of4 lastUnit"> + <article> + <h1>$Title</h1> + $Content + <div class="content">$Content</div> + </article> + <% loop $Children %> <article> - <h1>$Title</h1> - $Content - <div class="content">$Content</div> + <h2><a href="$Link" title="Read more on "{$Title}"">$Title</a></h2> + <p>$Content.FirstParagraph</p> + <a href="$Link" title="Read more on "{$Title}"">Read more >></a> </article> - <% loop $Children %> - <article> - <h2><a href="$Link" title="Read more on "{$Title}"">$Title</a></h2> - <p>$Content.FirstParagraph</p> - <a href="$Link" title="Read more on "{$Title}"">Read more >></a> - </article> - <% end_loop %> - $Form - </div> + <% end_loop %> + $Form +</div> ``` Here we use the page control *Children*. As the name suggests, this control allows you to iterate over the children of a page. In this case, the children are our news articles. The *$Link* variable will give the address of the article which we can use to create a link, and the *FirstParagraph* function of the [DBHTMLText](api:SilverStripe\ORM\FieldType\DBHTMLText) field gives us a nice summary of the article. The function strips all tags from the paragraph extracted. @@ -357,22 +335,21 @@ Cut the code between "loop Children" in *ArticleHolder.ss** and replace it with **themes/simple/templates/Layout/ArticleHolder.ss** ```ss - ... - <% loop $Children %> - <% include ArticleTeaser %> - <% end_loop %> - ... +<% loop $Children %> + <% include ArticleTeaser %> +<% end_loop %> ``` + Paste the code that was in ArticleHolder into a new include file called ArticleTeaser.ss: **themes/simple/templates/Includes/ArticleTeaser.ss** ```ss - <article> - <h2><a href="$Link" title="Read more on "{$Title}"">$Title</a></h2> - <p>$Content.FirstParagraph</p> - <a href="$Link" title="Read more on "{$Title}"">Read more >></a> - </article> +<article> + <h2><a href="$Link" title="Read more on "{$Title}"">$Title</a></h2> + <p>$Content.FirstParagraph</p> + <a href="$Link" title="Read more on "{$Title}"">Read more >></a> +</article> ``` ### Changing the icons of pages in the CMS @@ -381,13 +358,13 @@ Now let's make a purely cosmetic change that nevertheless helps to make the info Add the following field to the *ArticleHolder* and *ArticlePage* classes: ```php - private static $icon = "cms/images/treeicons/news-file.gif"; +private static $icon = "cms/images/treeicons/news-file.gif"; ``` And this one to the *HomePage* class: ```php - private static $icon = "cms/images/treeicons/home-file.png"; +private static $icon = "cms/images/treeicons/home-file.png"; ``` This will change the icons for the pages in the CMS. @@ -405,12 +382,11 @@ It would be nice to greet page visitors with a summary of the latest news when t **mysite/code/HomePage.php** ```php - // ... - public function LatestNews($num=5) - { - $holder = ArticleHolder::get()->First(); - return ($holder) ? ArticlePage::get()->filter('ParentID', $holder->ID)->sort('Date DESC')->limit($num) : false; - } +public function LatestNews($num=5) +{ + $holder = ArticleHolder::get()->First(); + return ($holder) ? ArticlePage::get()->filter('ParentID', $holder->ID)->sort('Date DESC')->limit($num) : false; +} ``` This function simply runs a database query that gets the latest news articles from the database. By default, this is five, but you can change it by passing a number to the function. See the [Data Model and ORM](/developer_guides/model/data_model_and_orm) documentation for details. We can reference this function as a page control in our *HomePage* template: @@ -418,12 +394,12 @@ This function simply runs a database query that gets the latest news articles fr **themes/simple/templates/Layout/Homepage.ss** ```ss - <!-- ... --> - <div class="content">$Content</div> - </article> - <% loop $LatestNews %> - <% include ArticleTeaser %> - <% end_loop %> +<!-- ... --> +<div class="content">$Content</div> +</article> +<% loop $LatestNews %> + <% include ArticleTeaser %> +<% end_loop %> ``` When SilverStripe comes across a variable or page control it doesn't recognize, it first passes control to the controller. If the controller doesn't have a function for the variable or page control, it then passes control to the data object. If it has no matching functions, it then searches its database fields. Failing that it will return nothing. @@ -432,8 +408,6 @@ The controller for a page is only created when page is actually visited, while t ![](../_images/tutorial2_homepage-news.jpg) - - ## Creating a RSS feed An RSS feed is something that no news section should be without. SilverStripe makes it easy to create RSS feeds by providing an [RSSFeed](api:SilverStripe\Control\RSS\RSSFeed) class to do all the hard work for us. Add the following in the *ArticleHolderController* class: @@ -441,15 +415,15 @@ An RSS feed is something that no news section should be without. SilverStripe ma **mysite/code/ArticleHolder.php** ```php - private static $allowed_actions = [ - 'rss' - ]; +private static $allowed_actions = [ + 'rss' +]; - public function rss() - { - $rss = new RSSFeed($this->Children(), $this->Link(), "The coolest news around"); - return $rss->outputToBrowser(); - } +public function rss() +{ + $rss = new RSSFeed($this->Children(), $this->Link(), "The coolest news around"); + return $rss->outputToBrowser(); +} ``` Ensure that when you have input the code to implement an RSS feed; flush the webpage afterwards @@ -466,11 +440,11 @@ Now all we need is to let the user know that our RSS feed exists. Add this funct **mysite/code/ArticleHolder.php** ```php - public function init() - { - RSSFeed::linkToFeed($this->Link() . "rss"); - parent::init(); - } +public function init() +{ + RSSFeed::linkToFeed($this->Link() . "rss"); + parent::init(); +} ``` This automatically generates a link-tag in the header of our template. The *init* function is then called on the parent class to ensure any initialization the parent would have done if we hadn't overridden the *init* function is still called. Depending on your browser, you can see the RSS feed link in the address bar. @@ -482,25 +456,21 @@ Now that we have a complete news section, let's take a look at the staff section **mysite/code/StaffHolder.php** ```php - use Page; - - class StaffHolder extends Page - { - private static $db = []; - private static $has_one = []; - private static $allowed_children = [StaffPage::class]; - } +class StaffHolder extends Page +{ + private static $db = []; + private static $has_one = []; + private static $allowed_children = [StaffPage::class]; +} ``` **mysite/code/StaffHolderController.php** ```php - use PageController; - - class StaffHolderController extends PageController - { - - } +class StaffHolderController extends PageController +{ + +} ``` Nothing here should be new. The *StaffPage* page type is more interesting though. Each staff member has a portrait image. We want to make a permanent connection between this image and the specific *StaffPage* (otherwise we could simply insert an image in the *$Content* field). @@ -508,37 +478,35 @@ Nothing here should be new. The *StaffPage* page type is more interesting though **mysite/code/StaffPage.php** ```php - use SilverStripe\AssetAdmin\Forms\UploadField; - use SilverStripe\Assets\Image; +use SilverStripe\AssetAdmin\Forms\UploadField; +use SilverStripe\Assets\Image; - class StaffPage extends Page +class StaffPage extends Page +{ + private static $db = []; + + private static $has_one = [ + 'Photo' => Image::class + ]; + + public function getCMSFields() { - private static $db = []; - - private static $has_one = [ - 'Photo' => Image::class - ]; + $fields = parent::getCMSFields(); - public function getCMSFields() - { - $fields = parent::getCMSFields(); - - $fields->addFieldToTab("Root.Images", new UploadField('Photo')); - - return $fields; - } + $fields->addFieldToTab("Root.Images", new UploadField('Photo')); + + return $fields; } +} ``` **mysite/code/StaffPageController.php** ```php - use PageController; - - class StaffPageController extends PageController - { - - } +class StaffPageController extends PageController +{ + +} ``` Instead of adding our *Image* as a field in *$db*, we have used the *$has_one* array. This is because an *Image* is not a simple database field like all the fields we have seen so far, but has its own database table. By using the *$has_one* array, we create a relationship between the *StaffPage* table and the *Image* table by storing the id of the respective *Image* in the *StaffPage* table. @@ -562,24 +530,23 @@ The staff section templates aren't too difficult to create, thanks to the utilit **themes/simple/templates/Layout/StaffHolder.ss** ```ss - <% include SideBar %> - <div class="content-container unit size3of4 lastUnit"> +<% include SideBar %> +<div class="content-container unit size3of4 lastUnit"> + <article> + <h1>$Title</h1> + $Content + <div class="content">$Content</div> + </article> + <% loop $Children %> <article> - <h1>$Title</h1> - $Content - <div class="content">$Content</div> + <h2><a href="$Link" title="Read more on "{$Title}"">$Title</a></h2> + $Photo.ScaleWidth(150) + <p>$Content.FirstParagraph</p> + <a href="$Link" title="Read more on "{$Title}"">Read more >></a> </article> - <% loop $Children %> - <article> - <h2><a href="$Link" title="Read more on "{$Title}"">$Title</a></h2> - $Photo.ScaleWidth(150) - <p>$Content.FirstParagraph</p> - <a href="$Link" title="Read more on "{$Title}"">Read more >></a> - </article> - <% end_loop %> - $Form - </div> - + <% end_loop %> + $Form +</div> ``` This template is very similar to the *ArticleHolder* template. The *ScaleWidth* method of the [Image](api:SilverStripe\Assets\Image) class @@ -593,16 +560,16 @@ The *StaffPage* template is also very straight forward. **themes/simple/templates/Layout/StaffPage.ss** ```ss - <% include SideBar %> - <div class="content-container unit size3of4 lastUnit"> - <article> - <h1>$Title</h1> - <div class="content"> - $Photo.ScaleWidth(433) - $Content</div> - </article> - $Form - </div> +<% include SideBar %> +<div class="content-container unit size3of4 lastUnit"> + <article> + <h1>$Title</h1> + <div class="content"> + $Photo.ScaleWidth(433) + $Content</div> + </article> + $Form +</div> ``` Here we use the *ScaleWidth* method to get a different sized image from the same source image. You should now have diff --git a/docs/en/01_Tutorials/04_Site_Search.md b/docs/en/01_Tutorials/04_Site_Search.md index 6d3f87537..0a127ab54 100644 --- a/docs/en/01_Tutorials/04_Site_Search.md +++ b/docs/en/01_Tutorials/04_Site_Search.md @@ -19,8 +19,8 @@ To enable the search engine you need to include the following code in your `mysi This will enable fulltext search on page content as well as names of all files in the `/assets` folder. ```php - FulltextSearchable::enable(); -``` +FulltextSearchable::enable(); +``` After including that in your `_config.php` you will need to rebuild the database by visiting [http://localhost/your_site_name/dev/build](http://localhost/your_site_name/dev/build) in your web browser (replace localhost/your_site_name with a domain if applicable). This will add fulltext search columns. @@ -36,14 +36,13 @@ To add the search form, we can add `$SearchForm` anywhere in our templates. In t **themes/simple/templates/Includes/Header.ss** ```ss - ... - <% if $SearchForm %> - <span class="search-dropdown-icon">L</span> - <div class="search-bar"> - $SearchForm - </div> - <% end_if %> - <% include Navigation %> +<% if $SearchForm %> + <span class="search-dropdown-icon">L</span> + <div class="search-bar"> + $SearchForm + </div> +<% end_if %> +<% include Navigation %> ``` This displays as: @@ -58,23 +57,20 @@ is applied via `FulltextSearchable::enable()` **cms/code/search/ContentControllerSearchExtension.php** ```php - use SilverStripe\Core\Extension; +use SilverStripe\Core\Extension; - class ContentControllerSearchExtension extends Extension +class ContentControllerSearchExtension extends Extension +{ + public function results($data, $form, $request) { - ... - - public function results($data, $form, $request) - { - $data = [ - 'Results' => $form->getResults(), - 'Query' => $form->getSearchQuery(), - 'Title' => _t('SearchForm.SearchResults', 'Search Results') - ]; - return $this->owner->customise($data)->renderWith(['Page_results', 'Page']); - } + $data = [ + 'Results' => $form->getResults(), + 'Query' => $form->getSearchQuery(), + 'Title' => _t('SearchForm.SearchResults', 'Search Results') + ]; + return $this->owner->customise($data)->renderWith(['Page_results', 'Page']); } - +} ``` The code populates an array with the data we wish to pass to the template - the search results, query and title of the page. The final line is a little more complicated. @@ -105,56 +101,56 @@ class. *themes/simple/templates/Layout/Page_results.ss* ```ss - <div id="Content" class="searchResults"> - <h1>$Title</h1> +<div id="Content" class="searchResults"> + <h1>$Title</h1> + + <% if $Query %> + <p class="searchQuery"><strong>You searched for "{$Query}"</strong></p> + <% end_if %> - <% if $Query %> - <p class="searchQuery"><strong>You searched for "{$Query}"</strong></p> - <% end_if %> + <% if $Results %> + <ul id="SearchResults"> + <% loop $Results %> + <li> + <a class="searchResultHeader" href="$Link"> + <% if $MenuTitle %> + $MenuTitle + <% else %> + $Title + <% end_if %> + </a> + <p>$Content.LimitWordCountXML</p> + <a class="readMoreLink" href="$Link" + title="Read more about "{$Title}"" + >Read more about "{$Title}"...</a> + </li> + <% end_loop %> + </ul> + <% else %> + <p>Sorry, your search query did not return any results.</p> + <% end_if %> - <% if $Results %> - <ul id="SearchResults"> - <% loop $Results %> - <li> - <a class="searchResultHeader" href="$Link"> - <% if $MenuTitle %> - $MenuTitle - <% else %> - $Title - <% end_if %> - </a> - <p>$Content.LimitWordCountXML</p> - <a class="readMoreLink" href="$Link" - title="Read more about "{$Title}"" - >Read more about "{$Title}"...</a> - </li> + <% if $Results.MoreThanOnePage %> + <div id="PageNumbers"> + <% if $Results.NotLastPage %> + <a class="next" href="$Results.NextLink" title="View the next page">Next</a> + <% end_if %> + <% if $Results.NotFirstPage %> + <a class="prev" href="$Results.PrevLink" title="View the previous page">Prev</a> + <% end_if %> + <span> + <% loop $Results.Pages %> + <% if $CurrentBool %> + $PageNum + <% else %> + <a href="$Link" title="View page number $PageNum">$PageNum</a> + <% end_if %> <% end_loop %> - </ul> - <% else %> - <p>Sorry, your search query did not return any results.</p> - <% end_if %> - - <% if $Results.MoreThanOnePage %> - <div id="PageNumbers"> - <% if $Results.NotLastPage %> - <a class="next" href="$Results.NextLink" title="View the next page">Next</a> - <% end_if %> - <% if $Results.NotFirstPage %> - <a class="prev" href="$Results.PrevLink" title="View the previous page">Prev</a> - <% end_if %> - <span> - <% loop $Results.Pages %> - <% if $CurrentBool %> - $PageNum - <% else %> - <a href="$Link" title="View page number $PageNum">$PageNum</a> - <% end_if %> - <% end_loop %> - </span> - <p>Page $Results.CurrentPage of $Results.TotalPages</p> - </div> - <% end_if %> + </span> + <p>Page $Results.CurrentPage of $Results.TotalPages</p> </div> + <% end_if %> +</div> ``` Then finally add ?flush=1 to the URL and you should see the new template. diff --git a/docs/en/02_Developer_Guides/00_Model/01_Data_Model_and_ORM.md b/docs/en/02_Developer_Guides/00_Model/01_Data_Model_and_ORM.md index b5ccc89ea..23e0b44d4 100644 --- a/docs/en/02_Developer_Guides/00_Model/01_Data_Model_and_ORM.md +++ b/docs/en/02_Developer_Guides/00_Model/01_Data_Model_and_ORM.md @@ -20,19 +20,17 @@ Let's look at a simple example: **mysite/code/Player.php** ```php - use SilverStripe\ORM\DataObject; - - class Player extends DataObject - { - - private static $db = [ - 'PlayerNumber' => 'Int', - 'FirstName' => 'Varchar(255)', - 'LastName' => 'Text', - 'Birthday' => 'Date' - ]; - } +use SilverStripe\ORM\DataObject; +class Player extends DataObject +{ + private static $db = [ + 'PlayerNumber' => 'Int', + 'FirstName' => 'Varchar(255)', + 'LastName' => 'Text', + 'Birthday' => 'Date' + ]; +} ``` This `Player` class definition will create a database table `Player` with columns for `PlayerNumber`, `FirstName` and @@ -78,49 +76,49 @@ automatically set on the `DataObject`. **mysite/code/Player.php** ```php - use SilverStripe\ORM\DataObject; - - class Player extends DataObject - { - - private static $db = [ - 'PlayerNumber' => 'Int', - 'FirstName' => 'Varchar(255)', - 'LastName' => 'Text', - 'Birthday' => 'Date' - ]; - } +use SilverStripe\ORM\DataObject; +class Player extends DataObject +{ + private static $db = [ + 'PlayerNumber' => 'Int', + 'FirstName' => 'Varchar(255)', + 'LastName' => 'Text', + 'Birthday' => 'Date' + ]; +} ``` Generates the following `SQL`. - CREATE TABLE `Player` ( - `ID` int(11) NOT NULL AUTO_INCREMENT, - `ClassName` enum('Player') DEFAULT 'Player', - `LastEdited` datetime DEFAULT NULL, - `Created` datetime DEFAULT NULL, - `PlayerNumber` int(11) NOT NULL DEFAULT '0', - `FirstName` varchar(255) DEFAULT NULL, - `LastName` mediumtext, - `Birthday` datetime DEFAULT NULL, - - PRIMARY KEY (`ID`), - KEY `ClassName` (`ClassName`) - ); +```sql +CREATE TABLE `Player` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `ClassName` enum('Player') DEFAULT 'Player', + `LastEdited` datetime DEFAULT NULL, + `Created` datetime DEFAULT NULL, + `PlayerNumber` int(11) NOT NULL DEFAULT '0', + `FirstName` varchar(255) DEFAULT NULL, + `LastName` mediumtext, + `Birthday` datetime DEFAULT NULL, + + PRIMARY KEY (`ID`), + KEY `ClassName` (`ClassName`) +); +``` ## Creating Data Records A new instance of a [DataObject](api:SilverStripe\ORM\DataObject) can be created using the `new` syntax. - + ```php - $player = new Player(); +$player = new Player(); ``` Or, a better way is to use the `create` method. ```php - $player = Player::create(); +$player = Player::create(); ``` <div class="notice" markdown='1'> @@ -132,22 +130,22 @@ Database columns and properties can be set as class properties on the object. Th of the values through a custom `__set()` method. ```php - $player->FirstName = "Sam"; - $player->PlayerNumber = 07; +$player->FirstName = "Sam"; +$player->PlayerNumber = 07; ``` To save the `DataObject` to the database, use the `write()` method. The first time `write()` is called, an `ID` will be set. - + ```php - $player->write(); +$player->write(); ``` For convenience, the `write()` method returns the record's ID. This is particularly useful when creating new records. ```php - $player = Player::create(); - $id = $player->write(); +$player = Player::create(); +$id = $player->write(); ``` ## Querying Data @@ -156,28 +154,28 @@ With the `Player` class defined we can query our data using the `ORM` or Object- shortcuts and methods for fetching, sorting and filtering data from our database. ```php - $players = Player::get(); - // returns a `DataList` containing all the `Player` objects. +$players = Player::get(); +// returns a `DataList` containing all the `Player` objects. - $player = Player::get()->byID(2); - // returns a single `Player` object instance that has the ID of 2. +$player = Player::get()->byID(2); +// returns a single `Player` object instance that has the ID of 2. - echo $player->ID; - // returns the players 'ID' column value +echo $player->ID; +// returns the players 'ID' column value - echo $player->dbObject('LastEdited')->Ago(); - // calls the `Ago` method on the `LastEdited` property. +echo $player->dbObject('LastEdited')->Ago(); +// calls the `Ago` method on the `LastEdited` property. ``` The `ORM` uses a "fluent" syntax, where you specify a query by chaining together different methods. Two common methods are `filter()` and `sort()`: ```php - $members = Player::get()->filter([ - 'FirstName' => 'Sam' - ])->sort('Surname'); +$members = Player::get()->filter([ + 'FirstName' => 'Sam' +])->sort('Surname'); - // returns a `DataList` containing all the `Player` records that have the `FirstName` of 'Sam' +// returns a `DataList` containing all the `Player` records that have the `FirstName` of 'Sam' ``` @@ -193,50 +191,48 @@ It's smart enough to generate a single efficient query at the last moment in tim result set in PHP. In `MySQL` the query generated by the ORM may look something like this ```php - $players = Player::get()->filter([ - 'FirstName' => 'Sam' - ]); +$players = Player::get()->filter([ + 'FirstName' => 'Sam' +]); - $players = $players->sort('Surname'); - - // executes the following single query - // SELECT * FROM Player WHERE FirstName = 'Sam' ORDER BY Surname +$players = $players->sort('Surname'); +// executes the following single query +// SELECT * FROM Player WHERE FirstName = 'Sam' ORDER BY Surname ``` This also means that getting the count of a list of objects will be done with a single, efficient query. ```php - $players = Player::get()->filter([ - 'FirstName' => 'Sam' - ])->sort('Surname'); - - // This will create an single SELECT COUNT query - // SELECT COUNT(*) FROM Player WHERE FirstName = 'Sam' - echo $players->Count(); +$players = Player::get()->filter([ + 'FirstName' => 'Sam' +])->sort('Surname'); +// This will create an single SELECT COUNT query +// SELECT COUNT(*) FROM Player WHERE FirstName = 'Sam' +echo $players->Count(); ``` ## Looping over a list of objects `get()` returns a `DataList` instance. You can loop over `DataList` instances in both PHP and templates. - -```php - $players = Player::get(); - foreach($players as $player) { - echo $player->FirstName; - } +```php +$players = Player::get(); + +foreach($players as $player) { + echo $player->FirstName; +} ``` Notice that we can step into the loop safely without having to check if `$players` exists. The `get()` call is robust, and will at worst return an empty `DataList` object. If you do want to check if the query returned any records, you can use the `exists()` method, e.g. ```php - $players = Player::get(); +$players = Player::get(); - if($players->exists()) { - // do something here - } +if($players->exists()) { + // do something here +} ``` See the [Lists](lists) documentation for more information on dealing with [SS_List](api:SilverStripe\ORM\SS_List) instances. @@ -247,16 +243,16 @@ There are a couple of ways of getting a single DataObject from the ORM. If you k can use `byID($id)`: ```php - $player = Player::get()->byID(5); +$player = Player::get()->byID(5); ``` `get()` returns a [DataList](api:SilverStripe\ORM\DataList) instance. You can use operations on that to get back a single record. ```php - $players = Player::get(); +$players = Player::get(); - $first = $players->first(); - $last = $players->last(); +$first = $players->first(); +$last = $players->last(); ``` ## Sorting @@ -264,38 +260,37 @@ can use `byID($id)`: If would like to sort the list by `FirstName` in a ascending way (from A to Z). ```php - // Sort can either be Ascending (ASC) or Descending (DESC) - $players = Player::get()->sort('FirstName', 'ASC'); + // Sort can either be Ascending (ASC) or Descending (DESC) +$players = Player::get()->sort('FirstName', 'ASC'); - // Ascending is implied - $players = Player::get()->sort('FirstName'); + // Ascending is implied +$players = Player::get()->sort('FirstName'); ``` To reverse the sort ```php - $players = Player::get()->sort('FirstName', 'DESC'); +$players = Player::get()->sort('FirstName', 'DESC'); - // or.. - $players = Player::get()->sort('FirstName', 'ASC')->reverse(); +// or.. +$players = Player::get()->sort('FirstName', 'ASC')->reverse(); ``` However you might have several entries with the same `FirstName` and would like to sort them by `FirstName` and `LastName` ```php - $players = Players::get()->sort([ - 'FirstName' => 'ASC', - 'LastName'=>'ASC' - ]); - +$players = Players::get()->sort([ + 'FirstName' => 'ASC', + 'LastName'=>'ASC' +]); ``` You can also sort randomly. Using the `DB` class, you can get the random sort method per database type. ```php - $random = DB::get_conn()->random(); - $players = Player::get()->sort($random) +$random = DB::get_conn()->random(); +$players = Player::get()->sort($random) ``` ## Filtering Results @@ -303,10 +298,9 @@ You can also sort randomly. Using the `DB` class, you can get the random sort me The `filter()` method filters the list of objects that gets returned. ```php - $players = Player::get()->filter([ - 'FirstName' => 'Sam' - ]); - +$players = Player::get()->filter([ + 'FirstName' => 'Sam' +]); ``` Each element of the array specifies a filter. You can specify as many filters as you like, and they **all** must be @@ -318,41 +312,38 @@ value that you want to filter to. So, this would return only those players called "Sam Minnée". ```php - $players = Player::get()->filter([ - 'FirstName' => 'Sam', - 'LastName' => 'Minnée', - ]); - - // SELECT * FROM Player WHERE FirstName = 'Sam' AND LastName = 'Minnée' +$players = Player::get()->filter([ + 'FirstName' => 'Sam', + 'LastName' => 'Minnée', +]); +// SELECT * FROM Player WHERE FirstName = 'Sam' AND LastName = 'Minnée' ``` There is also a shorthand way of getting Players with the FirstName of Sam. ```php - $players = Player::get()->filter('FirstName', 'Sam'); +$players = Player::get()->filter('FirstName', 'Sam'); ``` Or if you want to find both Sam and Sig. ```php - $players = Player::get()->filter( - 'FirstName', ['Sam', 'Sig'] - ); - - // SELECT * FROM Player WHERE FirstName IN ('Sam', 'Sig') +$players = Player::get()->filter( + 'FirstName', ['Sam', 'Sig'] +); +// SELECT * FROM Player WHERE FirstName IN ('Sam', 'Sig') ``` You can use [SearchFilters](searchfilters) to add additional behavior to your `filter` command rather than an exact match. ```php - $players = Player::get()->filter([ - 'FirstName:StartsWith' => 'S' - 'PlayerNumber:GreaterThan' => '10' - ]); - +$players = Player::get()->filter([ + 'FirstName:StartsWith' => 'S', + 'PlayerNumber:GreaterThan' => '10', +]); ``` ### filterAny @@ -360,38 +351,35 @@ exact match. Use the `filterAny()` method to match multiple criteria non-exclusively (with an "OR" disjunctive), ```php - $players = Player::get()->filterAny([ - 'FirstName' => 'Sam', - 'Age' => 17, - ]); - - // SELECT * FROM Player WHERE ("FirstName" = 'Sam' OR "Age" = '17') +$players = Player::get()->filterAny([ + 'FirstName' => 'Sam', + 'Age' => 17, +]); +// SELECT * FROM Player WHERE ("FirstName" = 'Sam' OR "Age" = '17') ``` You can combine both conjunctive ("AND") and disjunctive ("OR") statements. ```php - $players = Player::get() - ->filter([ - 'LastName' => 'Minnée' - ]) - ->filterAny([ - 'FirstName' => 'Sam', - 'Age' => 17, - ]); - // SELECT * FROM Player WHERE ("LastName" = 'Minnée' AND ("FirstName" = 'Sam' OR "Age" = '17')) - +$players = Player::get() + ->filter([ + 'LastName' => 'Minnée', + ]) + ->filterAny([ + 'FirstName' => 'Sam', + 'Age' => 17, + ]); +// SELECT * FROM Player WHERE ("LastName" = 'Minnée' AND ("FirstName" = 'Sam' OR "Age" = '17')) ``` You can use [SearchFilters](searchfilters) to add additional behavior to your `filterAny` command. ```php - $players = Player::get()->filterAny([ - 'FirstName:StartsWith' => 'S' - 'PlayerNumber:GreaterThan' => '10' - ]); - +$players = Player::get()->filterAny([ + 'FirstName:StartsWith' => 'S', + 'PlayerNumber:GreaterThan' => '10', +]); ``` ### Filtering by null values @@ -405,30 +393,28 @@ For instance, the below code will select only values that do not match the given ```php - $players = Player::get()->filter('FirstName:not', 'Sam'); - // ... WHERE "FirstName" != 'Sam' OR "FirstName" IS NULL - // Returns rows with any value (even null) other than Sam +$players = Player::get()->filter('FirstName:not', 'Sam'); +// ... WHERE "FirstName" != 'Sam' OR "FirstName" IS NULL +// Returns rows with any value (even null) other than Sam ``` If null values should be excluded, include the null in your check. ```php - $players = Player::get()->filter('FirstName:not', ['Sam', null]); - // ... WHERE "FirstName" != 'Sam' AND "FirstName" IS NOT NULL - // Only returns non-null values for "FirstName" that aren't Sam. - // Strictly the IS NOT NULL isn't necessary, but is included for explicitness - +$players = Player::get()->filter('FirstName:not', ['Sam', null]); +// ... WHERE "FirstName" != 'Sam' AND "FirstName" IS NOT NULL +// Only returns non-null values for "FirstName" that aren't Sam. +// Strictly the IS NOT NULL isn't necessary, but is included for explicitness ``` It is also often useful to filter by all rows with either empty or null for a given field. ```php - $players = Player::get()->filter('FirstName', [null, '']); - // ... WHERE "FirstName" == '' OR "FirstName" IS NULL - // Returns rows with FirstName which is either empty or null - +$players = Player::get()->filter('FirstName', [null, '']); +// ... WHERE "FirstName" == '' OR "FirstName" IS NULL +// Returns rows with FirstName which is either empty or null ``` ### Filtering by aggregates @@ -436,17 +422,17 @@ It is also often useful to filter by all rows with either empty or null for a gi You can use aggregate expressions in your filters, as well. ```php - // get the teams that have more than 10 players - $teams = Team::get()->filter('Players.Count():GreaterThan', 10); +// get the teams that have more than 10 players +$teams = Team::get()->filter('Players.Count():GreaterThan', 10); - // get the teams with at least one player who has scored 5 or more points - $teams = Team::get()->filter('Players.Min(PointsScored):GreaterThanOrEqual', 5); +// get the teams with at least one player who has scored 5 or more points +$teams = Team::get()->filter('Players.Min(PointsScored):GreaterThanOrEqual', 5); - // get the teams with players who are averaging more than 15 points - $teams = Team::get()->filter('Players.Avg(PointsScored):GreaterThan', 15); +// get the teams with players who are averaging more than 15 points +$teams = Team::get()->filter('Players.Avg(PointsScored):GreaterThan', 15); - // get the teams whose players have scored less than 300 points combined - $teams = Team::get()->filter('Players.Sum(PointsScored):LessThan', 300); +// get the teams whose players have scored less than 300 points combined +$teams = Team::get()->filter('Players.Sum(PointsScored):LessThan', 300); ``` ### filterByCallback @@ -466,9 +452,9 @@ for each record, if the callback returns true, this record will be added to the The below example will get all `Players` aged over 10. ```php - $players = Player::get()->filterByCallback(function($item, $list) { - return ($item->Age() > 10); - }); +$players = Player::get()->filterByCallback(function($item, $list) { + return ($item->Age() > 10); +}); ``` ### Exclude @@ -476,59 +462,56 @@ The below example will get all `Players` aged over 10. The `exclude()` method is the opposite to the filter in that it removes entries from a list. ```php - $players = Player::get()->exclude('FirstName', 'Sam'); +$players = Player::get()->exclude('FirstName', 'Sam'); - // SELECT * FROM Player WHERE FirstName != 'Sam' +// SELECT * FROM Player WHERE FirstName != 'Sam' ``` Remove both Sam and Sig.. ```php - $players = Player::get()->exclude( - 'FirstName', ['Sam','Sig'] - ); - +$players = Player::get()->exclude( + 'FirstName', ['Sam','Sig'] +); ``` `Exclude` follows the same pattern as filter, so for removing only Sam Minnée from the list: ```php - $players = Player::get()->exclude(array( - 'FirstName' => 'Sam', - 'Surname' => 'Minnée', - )); - - // SELECT * FROM Player WHERE (FirstName != 'Sam' OR LastName != 'Minnée') +$players = Player::get()->exclude(array( + 'FirstName' => 'Sam', + 'Surname' => 'Minnée', +)); + +// SELECT * FROM Player WHERE (FirstName != 'Sam' OR LastName != 'Minnée') ``` - + Removing players with *either* the first name of Sam or the last name of Minnée requires multiple `->exclude` calls: ```php - $players = Player::get()->exclude('FirstName', 'Sam')->exclude('Surname', 'Minnée'); - - // SELECT * FROM Player WHERE FirstName != 'Sam' AND LastName != 'Minnée' +$players = Player::get()->exclude('FirstName', 'Sam')->exclude('Surname', 'Minnée'); + +// SELECT * FROM Player WHERE FirstName != 'Sam' AND LastName != 'Minnée' ``` And removing Sig and Sam with that are either age 17 or 43. ```php - $players = Player::get()->exclude([ - 'FirstName' => ['Sam', 'Sig'], - 'Age' => [17, 43] - ]); - - // SELECT * FROM Player WHERE ("FirstName" NOT IN ('Sam','Sig) OR "Age" NOT IN ('17', '43')); +$players = Player::get()->exclude([ + 'FirstName' => ['Sam', 'Sig'], + 'Age' => [17, 43] +]); +// SELECT * FROM Player WHERE ("FirstName" NOT IN ('Sam','Sig) OR "Age" NOT IN ('17', '43')); ``` You can use [SearchFilters](searchfilters) to add additional behavior to your `exclude` command. ```php - $players = Player::get()->exclude([ - 'FirstName:EndsWith' => 'S' - 'PlayerNumber:LessThanOrEqual' => '10' - ]); - +$players = Player::get()->exclude([ + 'FirstName:EndsWith' => 'S', + 'PlayerNumber:LessThanOrEqual' => '10' +]); ``` ### Subtract @@ -536,19 +519,19 @@ You can use [SearchFilters](searchfilters) to add additional behavior to your `e You can subtract entries from a [DataList](api:SilverStripe\ORM\DataList) by passing in another DataList to `subtract()` ```php - $sam = Player::get()->filter('FirstName', 'Sam'); - $players = Player::get(); +$sam = Player::get()->filter('FirstName', 'Sam'); +$players = Player::get(); - $noSams = $players->subtract($sam); +$noSams = $players->subtract($sam); ``` Though for the above example it would probably be easier to use `filter()` and `exclude()`. A better use case could be when you want to find all the members that does not exist in a Group. ```php - // ... Finding all members that does not belong to $group. - use SilverStripe\Security\Member; - $otherMembers = Member::get()->subtract($group->Members()); +// ... Finding all members that does not belong to $group. +use SilverStripe\Security\Member; +$otherMembers = Member::get()->subtract($group->Members()); ``` ### Limit @@ -556,8 +539,8 @@ when you want to find all the members that does not exist in a Group. You can limit the amount of records returned in a DataList by using the `limit()` method. ```php - use SilverStripe\Security\Member; - $members = Member::get()->limit(5); +use SilverStripe\Security\Member; +$members = Member::get()->limit(5); ``` `limit()` accepts two arguments, the first being the amount of results you want returned, with an optional second @@ -565,8 +548,8 @@ parameter to specify the offset, which allows you to tell the system where to st offset, if not provided as an argument, will default to 0. ```php - // Return 10 members with an offset of 4 (starting from the 5th result). - $members = Member::get()->sort('Surname')->limit(10, 4); +// Return 10 members with an offset of 4 (starting from the 5th result). +$members = Member::get()->sort('Surname')->limit(10, 4); ``` <div class="alert"> @@ -583,13 +566,13 @@ For instance, the below model will be stored in the table name `BannerImage` ```php - namespace SilverStripe\BannerManager; - use SilverStripe\ORM\DataObject; +namespace SilverStripe\BannerManager; +use SilverStripe\ORM\DataObject; - class BannerImage extends \DataObject - { - private static $table_name = 'BannerImage'; - } +class BannerImage extends DataObject +{ + private static $table_name = 'BannerImage'; +} ``` Note that any model class which does not explicitly declare a `table_name` config option will have a name @@ -620,17 +603,17 @@ table and column. ```php - use SilverStripe\ORM\Queries\SQLSelect; - use SilverStripe\ORM\DataObject; - - public function countDuplicates($model, $fieldToCheck) - { - $table = DataObject::getSchema()->tableForField($model, $field); - $query = new SQLSelect(); - $query->setFrom("\"{$table}\""); - $query->setWhere(["\"{$table}\".\"{$field}\"" => $model->$fieldToCheck]); - return $query->count(); - } +use SilverStripe\ORM\Queries\SQLSelect; +use SilverStripe\ORM\DataObject; + +public function countDuplicates($model, $fieldToCheck) +{ + $table = DataObject::getSchema()->tableForField($model, $field); + $query = new SQLSelect(); + $query->setFrom("\"{$table}\""); + $query->setWhere(["\"{$table}\".\"{$field}\"" => $model->$fieldToCheck]); + return $query->count(); +} ``` ### Raw SQL @@ -649,8 +632,8 @@ you need it to, you may also consider extending the ORM with new data types or f You can specify a WHERE clause fragment (that will be combined with other filters using AND) with the `where()` method: -```php - $members = Member::get()->where("\"FirstName\" = 'Sam'") +```php +$members = Member::get()->where("\"FirstName\" = 'Sam'") ``` #### Joining Tables @@ -662,12 +645,12 @@ You can specify a join with the `innerJoin` and `leftJoin` methods. Both of the * An optional alias. ```php - // Without an alias - $members = Member::get() - ->leftJoin("Group_Members", "\"Group_Members\".\"MemberID\" = \"Member\".\"ID\""); +// Without an alias +$members = Member::get() + ->leftJoin("Group_Members", "\"Group_Members\".\"MemberID\" = \"Member\".\"ID\""); - $members = Member::get() - ->innerJoin("Group_Members", "\"Rel\".\"MemberID\" = \"Member\".\"ID\"", "Rel"); +$members = Member::get() + ->innerJoin("Group_Members", "\"Rel\".\"MemberID\" = \"Member\".\"ID\"", "Rel"); ``` <div class="alert" markdown="1"> @@ -681,16 +664,15 @@ Define the default values for all the `$db` fields. This example sets the "Statu whenever a new object is created. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Player extends DataObject - { - - private static $defaults = [ - "Status" => 'Active', - ]; - } +class Player extends DataObject +{ + private static $defaults = [ + "Status" => 'Active', + ]; +} ``` <div class="notice" markdown='1'> @@ -700,7 +682,6 @@ Note: Alternatively you can set defaults directly in the database-schema (rather ## Subclasses - Inheritance is supported in the data model: separate tables will be linked together, the data spread across these tables. The mapping and saving logic is handled by SilverStripe, you don't need to worry about writing SQL most of the time. @@ -708,47 +689,43 @@ time. For example, suppose we have the following set of classes: ```php - use SilverStripe\CMS\Model\SiteTree; - use Page; +use SilverStripe\CMS\Model\SiteTree; - class Page extends SiteTree - { - - } - class NewsPage extends Page - { - - private static $db = [ - 'Summary' => 'Text' - ]; - } +class Page extends SiteTree +{ +} +class NewsPage extends Page +{ + private static $db = [ + 'Summary' => 'Text' + ]; +} ``` The data for the following classes would be stored across the following tables: ```yml - - SilverStripe\CMS\Model\SiteTree: - - ID: Int - - ClassName: Enum('SiteTree', 'Page', 'NewsPage') - - Created: Datetime - - LastEdited: Datetime - - Title: Varchar - - Content: Text - NewsPage: - - ID: Int - - Summary: Text +SilverStripe\CMS\Model\SiteTree: + ID: Int + ClassName: Enum('SiteTree', 'Page', 'NewsPage') + Created: Datetime + LastEdited: Datetime + Title: Varchar + Content: Text +NewsPage: + ID: Int + Summary: Text ``` Accessing the data is transparent to the developer. ```php - $news = NewsPage::get(); +$news = NewsPage::get(); - foreach($news as $article) { - echo $article->Title; - } +foreach($news as $article) { + echo $article->Title; +} ``` The way the ORM stores the data is this: diff --git a/docs/en/02_Developer_Guides/00_Model/02_Relations.md b/docs/en/02_Developer_Guides/00_Model/02_Relations.md index 9c70e1f56..7397c127b 100644 --- a/docs/en/02_Developer_Guides/00_Model/02_Relations.md +++ b/docs/en/02_Developer_Guides/00_Model/02_Relations.md @@ -16,27 +16,24 @@ A 1-to-1 relation creates a database-column called "`<relationship-name>`ID", in "TeamID" on the "Player"-table. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Team extends DataObject - { +class Team extends DataObject +{ + private static $db = [ + 'Title' => 'Varchar' + ]; - private static $db = [ - 'Title' => 'Varchar' - ]; - - private static $has_many = [ - 'Players' => 'Player' - ]; - } - class Player extends DataObject - { - - private static $has_one = [ + private static $has_many = [ + 'Players' => 'Player' + ]; +} +class Player extends DataObject +{ + private static $has_one = [ "Team" => "Team", - ]; - } - + ]; +} ``` This defines a relationship called `Team` which links to a `Team` class. The `ORM` handles navigating the relationship @@ -45,24 +42,23 @@ and provides a short syntax for accessing the related object. At the database level, the `has_one` creates a `TeamID` field on `Player`. A `has_many` field does not impose any database changes. It merely injects a new method into the class to access the related records (in this case, `Players()`) ```php - $player = Player::get()->byId(1); +$player = Player::get()->byId(1); - $team = $player->Team(); - // returns a 'Team' instance. +$team = $player->Team(); +// returns a 'Team' instance. - echo $player->Team()->Title; - // returns the 'Title' column on the 'Team' or `getTitle` if it exists. +echo $player->Team()->Title; +// returns the 'Title' column on the 'Team' or `getTitle` if it exists. ``` The relationship can also be navigated in [templates](../templates). - -```ss - <% with $Player %> - <% if $Team %> - Plays for $Team.Title - <% end_if %> - <% end_with %> +```ss +<% with $Player %> + <% if $Team %> + Plays for $Team.Title + <% end_if %> +<% end_with %> ``` ## Polymorphic has_one @@ -77,31 +73,30 @@ To specify that a has_one relation is polymorphic set the type to 'DataObject'. Ideally, the associated has_many (or belongs_to) should be specified with dot notation. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Player extends DataObject - { - private static $has_many = [ - "Fans" => "Fan.FanOf" - ]; - } - class Team extends DataObject - { - private static $has_many = [ - "Fans" => "Fan.FanOf" - ]; - } +class Player extends DataObject +{ + private static $has_many = [ + "Fans" => "Fan.FanOf" + ]; +} +class Team extends DataObject +{ + private static $has_many = [ + "Fans" => "Fan.FanOf" + ]; +} - // Type of object returned by $fan->FanOf() will vary - class Fan extends DataObject - { - - // Generates columns FanOfID and FanOfClass - private static $has_one = [ - "FanOf" => "DataObject" - ]; - } +// Type of object returned by $fan->FanOf() will vary +class Fan extends DataObject +{ + // Generates columns FanOfID and FanOfClass + private static $has_one = [ + "FanOf" => "DataObject" + ]; +} ``` <div class="warning" markdown='1'> @@ -122,68 +117,63 @@ available on both ends. </div> ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Team extends DataObject - { +class Team extends DataObject +{ + private static $db = [ + 'Title' => 'Varchar' + ]; - private static $db = [ - 'Title' => 'Varchar' - ]; + private static $has_many = [ + 'Players' => 'Player' + ]; +} +class Player extends DataObject +{ - private static $has_many = [ - 'Players' => 'Player' - ]; - } - class Player extends DataObject - { - - private static $has_one = [ + private static $has_one = [ "Team" => "Team", - ]; - } - + ]; +} ``` Much like the `has_one` relationship, `has_many` can be navigated through the `ORM` as well. The only difference being you will get an instance of [HasManyList](api:SilverStripe\ORM\HasManyList) rather than the object. ```php - $team = Team::get()->first(); +$team = Team::get()->first(); - echo $team->Players(); - // [HasManyList] +echo $team->Players(); +// [HasManyList] - echo $team->Players()->Count(); - // returns '14'; +echo $team->Players()->Count(); +// returns '14'; - foreach($team->Players() as $player) { - echo $player->FirstName; - } +foreach($team->Players() as $player) { + echo $player->FirstName; +} ``` To specify multiple `$has_many` to the same object you can use dot notation to distinguish them like below: ```php - use SilverStripe\ORM\DataObject; - - class Person extends DataObject - { - - private static $has_many = [ - "Managing" => "Company.Manager", - "Cleaning" => "Company.Cleaner", - ]; - } - class Company extends DataObject - { - - private static $has_one = [ - "Manager" => "Person", - "Cleaner" => "Person" - ]; - } +use SilverStripe\ORM\DataObject; +class Person extends DataObject +{ + private static $has_many = [ + "Managing" => "Company.Manager", + "Cleaning" => "Company.Cleaner", + ]; +} +class Company extends DataObject +{ + private static $has_one = [ + "Manager" => "Person", + "Cleaner" => "Person" + ]; +} ``` Multiple `$has_one` relationships are okay if they aren't linking to the same object type. Otherwise, they have to be @@ -192,12 +182,12 @@ named. If you're using the default scaffolded form fields with multiple `has_one` relationships, you will end up with a CMS field for each relation. If you don't want these you can remove them by their IDs: ```php - public function getCMSFields() - { - $fields = parent::getCMSFields(); - $fields->removeByName(array('ManagerID', 'CleanerID')); - return $fields; - } +public function getCMSFields() +{ + $fields = parent::getCMSFields(); + $fields->removeByName(array('ManagerID', 'CleanerID')); + return $fields; +} ``` ## belongs_to @@ -211,23 +201,22 @@ Similarly with `$has_many`, dot notation can be used to explicitly specify the ` This is not mandatory unless the relationship would be otherwise ambiguous. ```php - use SilverStripe\ORM\DataObject; - - class Team extends DataObject - { - - private static $has_one = [ - 'Coach' => 'Coach' - ]; - } - class Coach extends DataObject - { - - private static $belongs_to = [ - 'Team' => 'Team.Coach' - ]; - } +use SilverStripe\ORM\DataObject; +class Team extends DataObject +{ + + private static $has_one = [ + 'Coach' => 'Coach' + ]; +} +class Coach extends DataObject +{ + + private static $belongs_to = [ + 'Team' => 'Team.Coach' + ]; +} ``` ## many_many @@ -246,10 +235,10 @@ The only difference being you will get an instance of [ManyManyList](api:SilverS [ManyManyThroughList](api:SilverStripe\ORM\ManyManyThroughList) rather than the object. ```php - $team = Team::get()->byId(1); +$team = Team::get()->byId(1); - $supporters = $team->Supporters(); - // returns a 'ManyManyList' instance. +$supporters = $team->Supporters(); +// returns a 'ManyManyList' instance. ``` ### Automatic many_many table @@ -261,28 +250,28 @@ be created with a pair of ID fields. Extra fields on the mapping table can be created by declaring a `many_many_extraFields` config to add extra columns. - ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Team extends DataObject - { - private static $many_many = [ +class Team extends DataObject +{ + private static $many_many = [ "Supporters" => "Supporter", - ]; - private static $many_many_extraFields = [ + ]; + + private static $many_many_extraFields = [ 'Supporters' => [ 'Ranking' => 'Int' ] - ]; - } - class Supporter extends DataObject - { + ]; +} - private static $belongs_many_many = [ +class Supporter extends DataObject +{ + private static $belongs_many_many = [ "Supports" => "Team", - ]; - } + ]; +} ``` ### many_many through relationship joined on a separate DataObject @@ -308,44 +297,43 @@ or child record. The syntax for `belongs_many_many` is unchanged. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Team extends DataObject - { - private static $many_many = [ +class Team extends DataObject +{ + private static $many_many = [ "Supporters" => [ - 'through' => 'TeamSupporter', - 'from' => 'Team', - 'to' => 'Supporter', + 'through' => 'TeamSupporter', + 'from' => 'Team', + 'to' => 'Supporter', ] - ]; - } - class Supporter extends DataObject - { - private static $belongs_many_many = [ + ]; +} +class Supporter extends DataObject +{ + private static $belongs_many_many = [ "Supports" => "Team", - ]; - } - class TeamSupporter extends DataObject - { - private static $db = [ + ]; +} +class TeamSupporter extends DataObject +{ + private static $db = [ 'Ranking' => 'Int', - ]; - - private static $has_one = [ + ]; + + private static $has_one = [ 'Team' => 'Team', - 'Supporter' => 'Supporter' - ]; - } + 'Supporter' => 'Supporter', + ]; +} ``` In order to filter on the join table during queries, you can use the class name of the joining table for any sql conditions. - ```php - $team = Team::get()->byId(1); - $supporters = $team->Supporters()->where(['"TeamSupporter"."Ranking"' => 1]); +$team = Team::get()->byId(1); +$supporters = $team->Supporters()->where(['"TeamSupporter"."Ranking"' => 1]); ``` Note: ->filter() currently does not support joined fields natively due to the fact that the @@ -356,14 +344,13 @@ query for the join table is isolated from the outer query controlled by DataList The relationship can also be navigated in [templates](../templates). The joined record can be accessed via `Join` or `TeamSupporter` property (many_many through only) - -```ss - <% with $Supporter %> - <% loop $Supports %> - Supports $Title <% if $TeamSupporter %>(rank $TeamSupporter.Ranking)<% end_if %> - <% end_if %> - <% end_with %> +```ss +<% with $Supporter %> + <% loop $Supports %> + Supports $Title <% if $TeamSupporter %>(rank $TeamSupporter.Ranking)<% end_if %> + <% end_if %> +<% end_with %> ``` You can also use `$Join` in place of the join class alias (`$TeamSupporter`), if your template @@ -379,25 +366,24 @@ distinguish them like below: ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Category extends DataObject - { - - private static $many_many = [ - 'Products' => 'Product', - 'FeaturedProducts' => 'Product' - ]; - } - class Product extends DataObject - { - - private static $belongs_many_many = [ - 'Categories' => 'Category.Products', - 'FeaturedInCategories' => 'Category.FeaturedProducts' - ]; - } +class Category extends DataObject +{ + + private static $many_many = [ + 'Products' => 'Product', + 'FeaturedProducts' => 'Product' + ]; +} +class Product extends DataObject +{ + private static $belongs_many_many = [ + 'Categories' => 'Category.Products', + 'FeaturedInCategories' => 'Category.FeaturedProducts' + ]; +} ``` If you're unsure about whether an object should take on `many_many` or `belongs_many_many`, @@ -441,15 +427,15 @@ encapsulated by [HasManyList](api:SilverStripe\ORM\HasManyList) and [ManyManyLis and `remove()` method. ```php - $team = Team::get()->byId(1); +$team = Team::get()->byId(1); - // create a new supporter - $supporter = new Supporter(); - $supporter->Name = "Foo"; - $supporter->write(); +// create a new supporter +$supporter = new Supporter(); +$supporter->Name = "Foo"; +$supporter->write(); - // add the supporter. - $team->Supporters()->add($supporter); +// add the supporter. +$team->Supporters()->add($supporter); ``` ## Custom Relations @@ -460,20 +446,19 @@ You can use the ORM to get a filtered result list without writing any SQL. For e See [DataObject::$has_many](api:SilverStripe\ORM\DataObject::$has_many) for more info on the described relations. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Team extends DataObject - { - - private static $has_many = [ +class Team extends DataObject +{ + private static $has_many = [ "Players" => "Player" - ]; + ]; - public function ActivePlayers() - { - return $this->Players()->filter('Status', 'Active'); - } + public function ActivePlayers() + { + return $this->Players()->filter('Status', 'Active'); } +} ``` diff --git a/docs/en/02_Developer_Guides/00_Model/03_Lists.md b/docs/en/02_Developer_Guides/00_Model/03_Lists.md index 3462bb1d6..71db5466c 100644 --- a/docs/en/02_Developer_Guides/00_Model/03_Lists.md +++ b/docs/en/02_Developer_Guides/00_Model/03_Lists.md @@ -12,34 +12,33 @@ modify. [SS_List](api:SilverStripe\ORM\SS_List) implements `IteratorAggregate`, allowing you to loop over the instance. ```php - use SilverStripe\Security\Member; - - $members = Member::get(); +use SilverStripe\Security\Member; - foreach($members as $member) { - echo $member->Name; - } +$members = Member::get(); + +foreach($members as $member) { + echo $member->Name; +} ``` Or in the template engine: ```ss - - <% loop $Members %> - <!-- --> - <% end_loop %> +<% loop $Members %> + <!-- --> +<% end_loop %> ``` ## Finding an item by value. ```php - // $list->find($key, $value); +// $list->find($key, $value); - // - $members = Member::get(); +// +$members = Member::get(); - echo $members->find('ID', 4)->FirstName; - // returns 'Sam' +echo $members->find('ID', 4)->FirstName; +// returns 'Sam' ``` ## Maps @@ -47,36 +46,34 @@ Or in the template engine: A map is an array where the array indexes contain data as well as the values. You can build a map from any list ```php - $members = Member::get()->map('ID', 'FirstName'); - - // $members = array( - // 1 => 'Sam' - // 2 => 'Sig' - // 3 => 'Will' - // ); +$members = Member::get()->map('ID', 'FirstName'); +// $members = array( +// 1 => 'Sam' +// 2 => 'Sig' +// 3 => 'Will' +// ); ``` This functionality is provided by the [Map](api:SilverStripe\ORM\Map) class, which can be used to build a map around any `SS_List`. ```php - $members = Member::get(); - $map = new Map($members, 'ID', 'FirstName'); +$members = Member::get(); +$map = new Map($members, 'ID', 'FirstName'); ``` ## Column ```php - $members = Member::get(); +$members = Member::get(); - echo $members->column('Email'); - - // returns array( - // 'sam@silverstripe.com', - // 'sig@silverstripe.com', - // 'will@silverstripe.com' - // ); +echo $members->column('Email'); +// returns array( +// 'sam@silverstripe.com', +// 'sig@silverstripe.com', +// 'will@silverstripe.com' +// ); ``` ## ArrayList @@ -84,16 +81,15 @@ This functionality is provided by the [Map](api:SilverStripe\ORM\Map) class, whi [ArrayList](api:SilverStripe\ORM\ArrayList) exists to wrap a standard PHP array in the same API as a database backed list. ```php - $sam = Member::get()->byId(5); - $sig = Member::get()->byId(6); +$sam = Member::get()->byId(5); +$sig = Member::get()->byId(6); - $list = new ArrayList(); - $list->push($sam); - $list->push($sig); - - echo $list->Count(); - // returns '2' +$list = new ArrayList(); +$list->push($sam); +$list->push($sig); +echo $list->Count(); +// returns '2' ``` ## API Documentation diff --git a/docs/en/02_Developer_Guides/00_Model/04_Data_Types_and_Casting.md b/docs/en/02_Developer_Guides/00_Model/04_Data_Types_and_Casting.md index 05b3066e2..bdbc5d0e5 100644 --- a/docs/en/02_Developer_Guides/00_Model/04_Data_Types_and_Casting.md +++ b/docs/en/02_Developer_Guides/00_Model/04_Data_Types_and_Casting.md @@ -14,19 +14,17 @@ In the `Player` example, we have four database columns each with a different dat **mysite/code/Player.php** ```php - use SilverStripe\ORM\DataObject; - - class Player extends DataObject - { - - private static $db = [ - 'PlayerNumber' => 'Int', - 'FirstName' => 'Varchar(255)', - 'LastName' => 'Text', - 'Birthday' => 'Date' - ]; - } +use SilverStripe\ORM\DataObject; +class Player extends DataObject +{ + private static $db = [ + 'PlayerNumber' => 'Int', + 'FirstName' => 'Varchar(255)', + 'LastName' => 'Text', + 'Birthday' => 'Date' + ]; +} ``` ## Available Types @@ -55,22 +53,20 @@ For complex default values for newly instantiated objects see [Dynamic Default V For simple values you can make use of the `$defaults` array. For example: ```php - use SilverStripe\ORM\DataObject; - - class Car extends DataObject - { - - private static $db = [ - 'Wheels' => 'Int', - 'Condition' => 'Enum(array("New","Fair","Junk"))' - ]; - - private static $defaults = [ - 'Wheels' => 4, - 'Condition' => 'New' - ]; - } +use SilverStripe\ORM\DataObject; +class Car extends DataObject +{ + private static $db = [ + 'Wheels' => 'Int', + 'Condition' => 'Enum(array("New","Fair","Junk"))' + ]; + + private static $defaults = [ + 'Wheels' => 4, + 'Condition' => 'New' + ]; +} ``` ### Default values for new database columns @@ -88,18 +84,16 @@ For enum values, it's the second parameter. For example: ```php - use SilverStripe\ORM\DataObject; - - class Car extends DataObject - { - - private static $db = [ - 'Wheels' => 'Int(4)', - 'Condition' => 'Enum(array("New","Fair","Junk"), "New")', - 'Make' => 'Varchar(["default" => "Honda"]), - ); - } +use SilverStripe\ORM\DataObject; +class Car extends DataObject +{ + private static $db = [ + 'Wheels' => 'Int(4)', + 'Condition' => 'Enum(array("New","Fair","Junk"), "New")', + 'Make' => 'Varchar(["default" => "Honda"]), + ); +} ``` ## Formatting Output @@ -111,36 +105,33 @@ If this case, we'll create a new method for our `Player` that returns the full n object we can control the formatting and it allows us to call methods defined from `Varchar` as `LimitCharacters`. **mysite/code/Player.php** - + ```php - use SilverStripe\ORM\FieldType\DBField; - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\FieldType\DBField; +use SilverStripe\ORM\DataObject; - class Player extends DataObject +class Player extends DataObject +{ + public function getName() { - - .. - - public function getName() - { - return DBField::create_field('Varchar', $this->FirstName . ' '. $this->LastName); - } + return DBField::create_field('Varchar', $this->FirstName . ' '. $this->LastName); } +} ``` Then we can refer to a new `Name` column on our `Player` instances. In templates we don't need to use the `get` prefix. ```php - $player = Player::get()->byId(1); +$player = Player::get()->byId(1); - echo $player->Name; - // returns "Sam Minnée" +echo $player->Name; +// returns "Sam Minnée" - echo $player->getName(); - // returns "Sam Minnée"; +echo $player->getName(); +// returns "Sam Minnée"; - echo $player->getName()->LimitCharacters(2); - // returns "Sa.." +echo $player->getName()->LimitCharacters(2); +// returns "Sa.." ``` ## Casting @@ -148,21 +139,19 @@ Then we can refer to a new `Name` column on our `Player` instances. In templates Rather than manually returning objects from your custom functions. You can use the `$casting` property. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Player extends DataObject - { - - private static $casting = [ +class Player extends DataObject +{ + private static $casting = [ "Name" => 'Varchar', - ]; + ]; - public function getName() - { - return $this->FirstName . ' '. $this->LastName; - } + public function getName() + { + return $this->FirstName . ' '. $this->LastName; } - +} ``` The properties on any SilverStripe object can be type casted automatically, by transforming its scalar value into an @@ -173,16 +162,16 @@ On the most basic level, the class can be used as simple conversion class from o number. ```php - use SilverStripe\ORM\FieldType\DBField; - DBField::create_field('Double', 1.23456)->Round(2); // results in 1.23 +use SilverStripe\ORM\FieldType\DBField; +DBField::create_field('Double', 1.23456)->Round(2); // results in 1.23 ``` Of course that's much more verbose than the equivalent PHP call. The power of [DBField](api:SilverStripe\ORM\FieldType\DBField) comes with its more sophisticated helpers, like showing the time difference to the current date: ```php - use SilverStripe\ORM\FieldType\DBField; - DBField::create_field('Date', '1982-01-01')->TimeDiff(); // shows "30 years ago" +use SilverStripe\ORM\FieldType\DBField; +DBField::create_field('Date', '1982-01-01')->TimeDiff(); // shows "30 years ago" ``` ## Casting ViewableData @@ -191,27 +180,26 @@ Most objects in SilverStripe extend from [ViewableData](api:SilverStripe\View\Vi context. Through a `$casting` array, arbitrary properties and getters can be casted: ```php - use SilverStripe\View\ViewableData; +use SilverStripe\View\ViewableData; - class MyObject extends ViewableData +class MyObject extends ViewableData +{ + + private static $casting = [ + 'MyDate' => 'Date' + ]; + + public function getMyDate() { - - private static $casting = [ - 'MyDate' => 'Date' - ]; - - public function getMyDate() - { - return '1982-01-01'; - } + return '1982-01-01'; } +} - $obj = new MyObject; - $obj->getMyDate(); // returns string - $obj->MyDate; // returns string - $obj->obj('MyDate'); // returns object - $obj->obj('MyDate')->InPast(); // returns boolean - +$obj = new MyObject; +$obj->getMyDate(); // returns string +$obj->MyDate; // returns string +$obj->obj('MyDate'); // returns object +$obj->obj('MyDate')->InPast(); // returns boolean ``` ## Casting HTML Text @@ -233,20 +221,19 @@ The following example will use the result of `getStatus` instead of the 'Status' database column using `dbObject`. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Player extends DataObject - { - - private static $db = [ +class Player extends DataObject +{ + private static $db = [ "Status" => "Enum(array('Active', 'Injured', 'Retired'))" - ]; - - public function getStatus() - { - return (!$this->obj("Birthday")->InPast()) ? "Unborn" : $this->dbObject('Status')->Value(); - } - + ]; + + public function getStatus() + { + return (!$this->obj("Birthday")->InPast()) ? "Unborn" : $this->dbObject('Status')->Value(); + } +} ``` ## API Documentation diff --git a/docs/en/02_Developer_Guides/00_Model/05_Extending_DataObjects.md b/docs/en/02_Developer_Guides/00_Model/05_Extending_DataObjects.md index 0d60a1898..b35da9a15 100644 --- a/docs/en/02_Developer_Guides/00_Model/05_Extending_DataObjects.md +++ b/docs/en/02_Developer_Guides/00_Model/05_Extending_DataObjects.md @@ -19,39 +19,38 @@ a `ModelAdmin` record. Example: Disallow creation of new players if the currently logged-in player is not a team-manager. ```php - use SilverStripe\Security\Security; - use SilverStripe\ORM\DataObject; +use SilverStripe\Security\Security; +use SilverStripe\ORM\DataObject; - class Player extends DataObject - { - - private static $has_many = [ - "Teams"=>"Team" - ]; +class Player extends DataObject +{ + private static $has_many = [ + "Teams" => "Team", + ]; - public function onBeforeWrite() - { + public function onBeforeWrite() + { // check on first write action, aka "database row creation" (ID-property is not set) if(!$this->isInDb()) { - $currentPlayer = Security::getCurrentUser(); - - if(!$currentPlayer->IsTeamManager()) { - user_error('Player-creation not allowed', E_USER_ERROR); - exit(); - } + $currentPlayer = Security::getCurrentUser(); + + if(!$currentPlayer->IsTeamManager()) { + user_error('Player-creation not allowed', E_USER_ERROR); + exit(); + } } - + // check on every write action if(!$this->record['TeamID']) { user_error('Cannot save player without a valid team', E_USER_ERROR); exit(); } - + // CAUTION: You are required to call the parent-function, otherwise // SilverStripe will not execute the request. parent::onBeforeWrite(); - } } +} ``` @@ -63,28 +62,27 @@ Example: Checking for a specific [permission](permissions) to delete this type o member is logged in who belongs to a group containing the permission "PLAYER_DELETE". ```php - use SilverStripe\Security\Permission; - use SilverStripe\Security\Security; - use SilverStripe\ORM\DataObject; +use SilverStripe\Security\Permission; +use SilverStripe\Security\Security; +use SilverStripe\ORM\DataObject; - class Player extends DataObject - { - - private static $has_many = [ +class Player extends DataObject +{ + + private static $has_many = [ "Teams" => "Team" - ]; + ]; - public function onBeforeDelete() - { + public function onBeforeDelete() + { if(!Permission::check('PLAYER_DELETE')) { - Security::permissionFailure($this); - exit(); + Security::permissionFailure($this); + exit(); } - + parent::onBeforeDelete(); - } } - +} ``` <div class="notice" markdown='1'> diff --git a/docs/en/02_Developer_Guides/00_Model/06_SearchFilters.md b/docs/en/02_Developer_Guides/00_Model/06_SearchFilters.md index 53ab2a6bf..0599e9709 100644 --- a/docs/en/02_Developer_Guides/00_Model/06_SearchFilters.md +++ b/docs/en/02_Developer_Guides/00_Model/06_SearchFilters.md @@ -15,20 +15,19 @@ you can put on field names to change this behavior. These are represented as `Se * [LessThanOrEqualFilter](api:SilverStripe\ORM\Filters\LessThanOrEqualFilter) An example of a `SearchFilter` in use: - + ```php - // fetch any player that starts with a S - $players = Player::get()->filter([ - 'FirstName:StartsWith' => 'S', - 'PlayerNumber:GreaterThan' => '10' - ]); - - // to fetch any player that's name contains the letter 'z' - $players = Player::get()->filterAny([ - 'FirstName:PartialMatch' => 'z', - 'LastName:PartialMatch' => 'z' - ]); +// fetch any player that starts with a S +$players = Player::get()->filter([ + 'FirstName:StartsWith' => 'S', + 'PlayerNumber:GreaterThan' => '10' +]); +// to fetch any player that's name contains the letter 'z' +$players = Player::get()->filterAny([ + 'FirstName:PartialMatch' => 'z', + 'LastName:PartialMatch' => 'z' +]); ``` Developers can define their own [SearchFilter](api:SilverStripe\ORM\Filters\SearchFilter) if needing to extend the ORM filter and exclude behaviors. @@ -44,24 +43,22 @@ config: ```yaml - - SilverStripe\Core\Injector\Injector: - DataListFilter.CustomMatch: - class: MyVendor\Search\CustomMatchFilter +SilverStripe\Core\Injector\Injector: + DataListFilter.CustomMatch: + class: MyVendor\Search\CustomMatchFilter ``` The following is a query which will return everyone whose first name starts with "S", either lowercase or uppercase: ```php - $players = Player::get()->filter([ - 'FirstName:StartsWith:nocase' => 'S' - ]); - - // use :not to perform a converse operation to filter anything but a 'W' - $players = Player::get()->filter([ - 'FirstName:StartsWith:not' => 'W' - ]); +$players = Player::get()->filter([ + 'FirstName:StartsWith:nocase' => 'S' +]); +// use :not to perform a converse operation to filter anything but a 'W' +$players = Player::get()->filter([ + 'FirstName:StartsWith:not' => 'W' +]); ``` ## API Documentation diff --git a/docs/en/02_Developer_Guides/00_Model/07_Permissions.md b/docs/en/02_Developer_Guides/00_Model/07_Permissions.md index 21ec3a66d..0311ae912 100644 --- a/docs/en/02_Developer_Guides/00_Model/07_Permissions.md +++ b/docs/en/02_Developer_Guides/00_Model/07_Permissions.md @@ -17,32 +17,31 @@ code. </div> ```php - use SilverStripe\Security\Permission; - use SilverStripe\ORM\DataObject; +use SilverStripe\Security\Permission; +use SilverStripe\ORM\DataObject; - class MyDataObject extends DataObject +class MyDataObject extends DataObject +{ + public function canView($member = null) { - - public function canView($member = null) - { - return Permission::check('CMS_ACCESS_CMSMain', 'any', $member); - } - - public function canEdit($member = null) - { - return Permission::check('CMS_ACCESS_CMSMain', 'any', $member); - } - - public function canDelete($member = null) - { - return Permission::check('CMS_ACCESS_CMSMain', 'any', $member); - } - - public function canCreate($member = null) - { - return Permission::check('CMS_ACCESS_CMSMain', 'any', $member); - } + return Permission::check('CMS_ACCESS_CMSMain', 'any', $member); } + + public function canEdit($member = null) + { + return Permission::check('CMS_ACCESS_CMSMain', 'any', $member); + } + + public function canDelete($member = null) + { + return Permission::check('CMS_ACCESS_CMSMain', 'any', $member); + } + + public function canCreate($member = null) + { + return Permission::check('CMS_ACCESS_CMSMain', 'any', $member); + } +} ``` <div class="alert" markdown="1"> diff --git a/docs/en/02_Developer_Guides/00_Model/08_SQL_Select.md b/docs/en/02_Developer_Guides/00_Model/08_SQL_Select.md index 7e2be7e0c..887b283dc 100644 --- a/docs/en/02_Developer_Guides/00_Model/08_SQL_Select.md +++ b/docs/en/02_Developer_Guides/00_Model/08_SQL_Select.md @@ -19,19 +19,19 @@ For example, if you want to run a simple `COUNT` SQL statement, the following three statements are functionally equivalent: ```php - use SilverStripe\ORM\DB; - use SilverStripe\ORM\Queries\SQLSelect; - use SilverStripe\Security\Member; +use SilverStripe\ORM\DB; +use SilverStripe\ORM\Queries\SQLSelect; +use SilverStripe\Security\Member; - // Through raw SQL. - $count = DB::query('SELECT COUNT(*) FROM "Member"')->value(); +// Through raw SQL. +$count = DB::query('SELECT COUNT(*) FROM "Member"')->value(); - // Through SQLSelect abstraction layer. - $query = new SQLSelect(); - $count = $query->setFrom('Member')->setSelect('COUNT(*)')->value(); +// Through SQLSelect abstraction layer. +$query = new SQLSelect(); +$count = $query->setFrom('Member')->setSelect('COUNT(*)')->value(); - // Through the ORM. - $count = Member::get()->count(); +// Through the ORM. +$count = Member::get()->count(); ``` If you do use raw SQL, you'll run the risk of breaking @@ -62,30 +62,28 @@ conditional filters, grouping, limiting, and sorting. E.g. ```php - - $sqlQuery = new SQLSelect(); - $sqlQuery->setFrom('Player'); - $sqlQuery->selectField('FieldName', 'Name'); - $sqlQuery->selectField('YEAR("Birthday")', 'Birthyear'); - $sqlQuery->addLeftJoin('Team','"Player"."TeamID" = "Team"."ID"'); - $sqlQuery->addWhere(['YEAR("Birthday") = ?' => 1982]); - // $sqlQuery->setOrderBy(...); - // $sqlQuery->setGroupBy(...); - // $sqlQuery->setHaving(...); - // $sqlQuery->setLimit(...); - // $sqlQuery->setDistinct(true); - - // Get the raw SQL (optional) and parameters - $rawSQL = $sqlQuery->sql($parameters); - - // Execute and return a Query object - $result = $sqlQuery->execute(); +$sqlQuery = new SQLSelect(); +$sqlQuery->setFrom('Player'); +$sqlQuery->selectField('FieldName', 'Name'); +$sqlQuery->selectField('YEAR("Birthday")', 'Birthyear'); +$sqlQuery->addLeftJoin('Team','"Player"."TeamID" = "Team"."ID"'); +$sqlQuery->addWhere(['YEAR("Birthday") = ?' => 1982]); +// $sqlQuery->setOrderBy(...); +// $sqlQuery->setGroupBy(...); +// $sqlQuery->setHaving(...); +// $sqlQuery->setLimit(...); +// $sqlQuery->setDistinct(true); - // Iterate over results - foreach($result as $row) { - echo $row['BirthYear']; - } +// Get the raw SQL (optional) and parameters +$rawSQL = $sqlQuery->sql($parameters); +// Execute and return a Query object +$result = $sqlQuery->execute(); + +// Iterate over results +foreach($result as $row) { + echo $row['BirthYear']; +} ``` The result of `SQLSelect::execute()` is an array lightly wrapped in a database-specific subclass of [Query](api:SilverStripe\ORM\Connect\Query). @@ -100,35 +98,31 @@ object instead. For example, creating a `SQLDelete` object ```php - use SilverStripe\ORM\Queries\SQLDelete; - - $query = SQLDelete::create() - ->setFrom('"SiteTree"') - ->setWhere(['"SiteTree"."ShowInMenus"' => 0]); - $query->execute(); +use SilverStripe\ORM\Queries\SQLDelete; +$query = SQLDelete::create() + ->setFrom('"SiteTree"') + ->setWhere(['"SiteTree"."ShowInMenus"' => 0]); +$query->execute(); ``` Alternatively, turning an existing `SQLSelect` into a delete ```php - use SilverStripe\ORM\Queries\SQLSelect; - - $query = SQLSelect::create() - ->setFrom('"SiteTree"') - ->setWhere(['"SiteTree"."ShowInMenus"' => 0]) - ->toDelete(); - $query->execute(); +use SilverStripe\ORM\Queries\SQLSelect; +$query = SQLSelect::create() + ->setFrom('"SiteTree"') + ->setWhere(['"SiteTree"."ShowInMenus"' => 0]) + ->toDelete(); +$query->execute(); ``` Directly querying the database ```php - use SilverStripe\ORM\DB; - - DB::prepared_query('DELETE FROM "SiteTree" WHERE "SiteTree"."ShowInMenus" = ?', [0]); - +use SilverStripe\ORM\DB; +DB::prepared_query('DELETE FROM "SiteTree" WHERE "SiteTree"."ShowInMenus" = ?', [0]); ``` ### INSERT/UPDATE @@ -176,32 +170,31 @@ SQLInsert also includes the following api methods: E.g. ```php - use SilverStripe\ORM\Queries\SQLUpdate; +use SilverStripe\ORM\Queries\SQLUpdate; - $update = SQLUpdate::create('"SiteTree"')->addWhere(['ID' => 3]); +$update = SQLUpdate::create('"SiteTree"')->addWhere(['ID' => 3]); - // assigning a list of items - $update->addAssignments([ - '"Title"' => 'Our Products', - '"MenuTitle"' => 'Products' - ]); +// assigning a list of items +$update->addAssignments([ + '"Title"' => 'Our Products', + '"MenuTitle"' => 'Products' +]); - // Assigning a single value - $update->assign('"MenuTitle"', 'Products'); +// Assigning a single value +$update->assign('"MenuTitle"', 'Products'); - // Assigning a value using parameterised expression - $title = 'Products'; - $update->assign('"MenuTitle"', [ - 'CASE WHEN LENGTH("MenuTitle") > LENGTH(?) THEN "MenuTitle" ELSE ? END' => - [$title, $title] - ]); +// Assigning a value using parameterised expression +$title = 'Products'; +$update->assign('"MenuTitle"', [ + 'CASE WHEN LENGTH("MenuTitle") > LENGTH(?) THEN "MenuTitle" ELSE ? END' => + [$title, $title] +]); - // Assigning a value using a pure SQL expression - $update->assignSQL('"Date"', 'NOW()'); - - // Perform the update - $update->execute(); +// Assigning a value using a pure SQL expression +$update->assignSQL('"Date"', 'NOW()'); +// Perform the update +$update->execute(); ``` In addition to assigning values, the SQLInsert object also supports multi-row @@ -211,28 +204,27 @@ these are translated internally as multiple single row inserts. For example, ```php - use SilverStripe\ORM\Queries\SQLInsert; +use SilverStripe\ORM\Queries\SQLInsert; - $insert = SQLInsert::create('"SiteTree"'); +$insert = SQLInsert::create('"SiteTree"'); - // Add multiple rows in a single call. Note that column names do not need - // to be symmetric - $insert->addRows([ - ['"Title"' => 'Home', '"Content"' => '<p>This is our home page</p>'], - ['"Title"' => 'About Us', '"ClassName"' => 'AboutPage'] - ]); +// Add multiple rows in a single call. Note that column names do not need +// to be symmetric +$insert->addRows([ + ['"Title"' => 'Home', '"Content"' => '<p>This is our home page</p>'], + ['"Title"' => 'About Us', '"ClassName"' => 'AboutPage'] +]); - // Adjust an assignment on the last row - $insert->assign('"Content"', '<p>This is about us</p>'); +// Adjust an assignment on the last row +$insert->assign('"Content"', '<p>This is about us</p>'); - // Add another row - $insert->addRow(['"Title"' => 'Contact Us']); +// Add another row +$insert->addRow(['"Title"' => 'Contact Us']); - $columns = $insert->getColumns(); - // $columns will be array('"Title"', '"Content"', '"ClassName"'); - - $insert->execute(); +$columns = $insert->getColumns(); +// $columns will be array('"Title"', '"Content"', '"ClassName"'); +$insert->execute(); ``` ### Value Checks @@ -243,21 +235,20 @@ e.g. when you want a single column rather than a full-blown object representatio Example: Get the count from a relationship. ```php - use SilverStripe\ORM\Queries\SQLSelect; - - $sqlQuery = new SQLSelect(); - $sqlQuery->setFrom('Player'); - $sqlQuery->addSelect('COUNT("Player"."ID")'); - $sqlQuery->addWhere(['"Team"."ID"' => 99]); - $sqlQuery->addLeftJoin('Team', '"Team"."ID" = "Player"."TeamID"'); - $count = $sqlQuery->execute()->value(); +use SilverStripe\ORM\Queries\SQLSelect; +$sqlQuery = new SQLSelect(); +$sqlQuery->setFrom('Player'); +$sqlQuery->addSelect('COUNT("Player"."ID")'); +$sqlQuery->addWhere(['"Team"."ID"' => 99]); +$sqlQuery->addLeftJoin('Team', '"Team"."ID" = "Player"."TeamID"'); +$count = $sqlQuery->execute()->value(); ``` Note that in the ORM, this call would be executed in an efficient manner as well: ```php - $count = $myTeam->Players()->count(); +$count = $myTeam->Players()->count(); ``` ### Mapping @@ -268,15 +259,15 @@ This can be useful for creating dropdowns. Example: Show player names with their birth year, but set their birth dates as values. ```php - use SilverStripe\ORM\Queries\SQLSelect; - use SilverStripe\Forms\DropdownField; - - $sqlQuery = new SQLSelect(); - $sqlQuery->setFrom('Player'); - $sqlQuery->setSelect('Birthdate'); - $sqlQuery->selectField('CONCAT("Name", ' - ', YEAR("Birthdate")', 'NameWithBirthyear'); - $map = $sqlQuery->execute()->map(); - $field = new DropdownField('Birthdates', 'Birthdates', $map); +use SilverStripe\ORM\Queries\SQLSelect; +use SilverStripe\Forms\DropdownField; + +$sqlQuery = new SQLSelect(); +$sqlQuery->setFrom('Player'); +$sqlQuery->setSelect('Birthdate'); +$sqlQuery->selectField('CONCAT("Name", ' - ', YEAR("Birthdate")', 'NameWithBirthyear'); +$map = $sqlQuery->execute()->map(); +$field = new DropdownField('Birthdates', 'Birthdates', $map); ``` Note that going through SQLSelect is just necessary here @@ -284,21 +275,20 @@ because of the custom SQL value transformation (`YEAR()`). An alternative approach would be a custom getter in the object definition. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Player extends DataObject - { - private static $db = [ - 'Name' => 'Varchar', - 'Birthdate' => 'Date' - ]; - function getNameWithBirthyear() { - return date('y', $this->Birthdate); - } +class Player extends DataObject +{ + private static $db = [ + 'Name' => 'Varchar', + 'Birthdate' => 'Date' + ]; + function getNameWithBirthyear() { + return date('y', $this->Birthdate); } - $players = Player::get(); - $map = $players->map('Name', 'NameWithBirthyear'); - +} +$players = Player::get(); +$map = $players->map('Name', 'NameWithBirthyear'); ``` ## Related diff --git a/docs/en/02_Developer_Guides/00_Model/09_Validation.md b/docs/en/02_Developer_Guides/00_Model/09_Validation.md index acd23b752..6441b9631 100644 --- a/docs/en/02_Developer_Guides/00_Model/09_Validation.md +++ b/docs/en/02_Developer_Guides/00_Model/09_Validation.md @@ -22,28 +22,27 @@ write, and respond appropriately if it isn't. The return value of `validate()` is a [ValidationResult](api:SilverStripe\ORM\ValidationResult) object. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyObject extends DataObject +class MyObject extends DataObject +{ + + private static $db = [ + 'Country' => 'Varchar', + 'Postcode' => 'Varchar' + ]; + + public function validate() { + $result = parent::validate(); - private static $db = [ - 'Country' => 'Varchar', - 'Postcode' => 'Varchar' - ]; - - public function validate() - { - $result = parent::validate(); - - if($this->Country == 'DE' && $this->Postcode && strlen($this->Postcode) != 5) { - $result->error('Need five digits for German postcodes'); - } - - return $result; + if($this->Country == 'DE' && $this->Postcode && strlen($this->Postcode) != 5) { + $result->error('Need five digits for German postcodes'); } - } + return $result; + } +} ``` ## API Documentation diff --git a/docs/en/02_Developer_Guides/00_Model/10_Versioning.md b/docs/en/02_Developer_Guides/00_Model/10_Versioning.md index b55eb32bf..f802ee854 100644 --- a/docs/en/02_Developer_Guides/00_Model/10_Versioning.md +++ b/docs/en/02_Developer_Guides/00_Model/10_Versioning.md @@ -202,7 +202,7 @@ rather than modifying the existing one. In order to get a list of all versions for a specific record, we need to generate specialized [Versioned_Version](api:SilverStripe\Versioned\Versioned_Version) objects, which expose the same database information as a `DataObject`, but also include information about when and how a record was published. - + ```php $record = MyRecord::get()->byID(99); // stage doesn't matter here $versions = $record->allVersions(); diff --git a/docs/en/02_Developer_Guides/00_Model/11_Scaffolding.md b/docs/en/02_Developer_Guides/00_Model/11_Scaffolding.md index e8dd3e0ff..d6561aef0 100644 --- a/docs/en/02_Developer_Guides/00_Model/11_Scaffolding.md +++ b/docs/en/02_Developer_Guides/00_Model/11_Scaffolding.md @@ -13,46 +13,44 @@ customise those fields as required. An example is `DataObject`, SilverStripe will automatically create your CMS interface so you can modify what you need. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyDataObject extends DataObject +class MyDataObject extends DataObject +{ + + private static $db = [ + 'IsActive' => 'Boolean', + 'Title' => 'Varchar', + 'Content' => 'Text' + ]; + + public function getCMSFields() { + // parent::getCMSFields() does all the hard work and creates the fields for Title, IsActive and Content. + $fields = parent::getCMSFields(); + $fields->dataFieldByName('IsActive')->setTitle('Is active?'); - private static $db = [ - 'IsActive' => 'Boolean', - 'Title' => 'Varchar', - 'Content' => 'Text' - ]; - - public function getCMSFields() - { - // parent::getCMSFields() does all the hard work and creates the fields for Title, IsActive and Content. - $fields = parent::getCMSFields(); - $fields->dataFieldByName('IsActive')->setTitle('Is active?'); - - return $fields; - } + return $fields; } - +} ``` To fully customise your form fields, start with an empty FieldList. ```php +public function getCMSFields() +{ + $fields = FieldList::create( + TabSet::create("Root.Main", + CheckboxSetField::create('IsActive','Is active?'), + TextField::create('Title'), + TextareaField::create('Content') + ->setRows(5) + ) + ); - public function getCMSFields() - { - $fields = FieldList::create( - TabSet::create("Root.Main", - CheckboxSetField::create('IsActive','Is active?'), - TextField::create('Title'), - TextareaField::create('Content') - ->setRows(5) - ) - ); - - return $fields; - } + return $fields; +} ``` You can also alter the fields of built-in and module `DataObject` classes through your own @@ -64,17 +62,16 @@ The `$searchable_fields` property uses a mixed array format that can be used to system. The default is a set of array values listing the fields. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyDataObject extends DataObject - { - - private static $searchable_fields = [ - 'Name', - 'ProductCode' - ]; - } +class MyDataObject extends DataObject +{ + private static $searchable_fields = [ + 'Name', + 'ProductCode' + ]; +} ``` Searchable fields will be appear in the search interface with a default form field (usually a [TextField](api:SilverStripe\Forms\TextField)) and a @@ -82,76 +79,73 @@ default search filter assigned (usually an [ExactMatchFilter](api:SilverStripe\O additional information on `$searchable_fields`: ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyDataObject extends DataObject - { - - private static $searchable_fields = [ - 'Name' => 'PartialMatchFilter', - 'ProductCode' => 'NumericField' - ]; - } +class MyDataObject extends DataObject +{ + private static $searchable_fields = [ + 'Name' => 'PartialMatchFilter', + 'ProductCode' => 'NumericField' + ]; +} ``` If you assign a single string value, you can set it to be either a [FormField](api:SilverStripe\Forms\FormField) or [SearchFilter](api:SilverStripe\ORM\Filters\SearchFilter). To specify both, you can assign an array: ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyDataObject extends DataObject - { - - private static $searchable_fields = [ - 'Name' => [ - 'field' => 'TextField', - 'filter' => 'PartialMatchFilter', - ], - 'ProductCode' => [ - 'title' => 'Product code #', - 'field' => 'NumericField', - 'filter' => 'PartialMatchFilter', - ], - ]; - } +class MyDataObject extends DataObject +{ + private static $searchable_fields = [ + 'Name' => [ + 'field' => 'TextField', + 'filter' => 'PartialMatchFilter', + ], + 'ProductCode' => [ + 'title' => 'Product code #', + 'field' => 'NumericField', + 'filter' => 'PartialMatchFilter', + ], + ]; +} ``` To include relations (`$has_one`, `$has_many` and `$many_many`) in your search, you can use a dot-notation. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Team extends DataObject - { - - private static $db = [ +class Team extends DataObject +{ + private static $db = [ 'Title' => 'Varchar' - ]; + ]; - private static $many_many = [ + private static $many_many = [ 'Players' => 'Player' - ]; + ]; - private static $searchable_fields = [ - 'Title', - 'Players.Name', - ]; - } - class Player extends DataObject - { - - private static $db = [ + private static $searchable_fields = [ + 'Title', + 'Players.Name', + ]; +} + +class Player extends DataObject +{ + private static $db = [ 'Name' => 'Varchar', - 'Birthday' => 'Date' - ]; + 'Birthday' => 'Date', + ]; - private static $belongs_many_many = [ + private static $belongs_many_many = [ 'Teams' => 'Team' - ]; - } + ]; +} ``` @@ -161,79 +155,75 @@ Summary fields can be used to show a quick overview of the data for a specific [ is their display as table columns, e.g. in the search results of a [ModelAdmin](api:SilverStripe\Admin\ModelAdmin) CMS interface. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyDataObject extends DataObject - { - - private static $db = [ +class MyDataObject extends DataObject +{ + private static $db = [ 'Name' => 'Text', 'OtherProperty' => 'Text', 'ProductCode' => 'Int', - ]; + ]; - private static $summary_fields = [ + private static $summary_fields = [ 'Name', - 'ProductCode' - ]; - } - + 'ProductCode', + ]; +} ``` To include relations or field manipulations in your summaries, you can use a dot-notation. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class OtherObject extends DataObject - { - - private static $db = [ - 'Title' => 'Varchar' - ]; - } - class MyDataObject extends DataObject - { - - private static $db = [ +class OtherObject extends DataObject +{ + private static $db = [ + 'Title' => 'Varchar', + ]; +} + +class MyDataObject extends DataObject +{ + private static $db = [ 'Name' => 'Text', - 'Description' => 'HTMLText' - ]; + 'Description' => 'HTMLText', + ]; - private static $has_one = [ - 'OtherObject' => 'OtherObject' - ]; + private static $has_one = [ + 'OtherObject' => 'OtherObject', + ]; - private static $summary_fields = [ + private static $summary_fields = [ 'Name' => 'Name', 'Description.Summary' => 'Description (summary)', - 'OtherObject.Title' => 'Other Object Title' - ]; - } + 'OtherObject.Title' => 'Other Object Title', + ]; +} ``` Non-textual elements (such as images and their manipulations) can also be used in summaries. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyDataObject extends DataObject - { +class MyDataObject extends DataObject +{ + private static $db = [ + 'Name' => 'Text', + ]; - private static $db = [ - 'Name' => 'Text' - ]; + private static $has_one = [ + 'HeroImage' => 'Image', + ]; - private static $has_one = [ - 'HeroImage' => 'Image' - ]; - - private static $summary_fields = [ + private static $summary_fields = [ 'Name' => 'Name', - 'HeroImage.CMSThumbnail' => 'Hero Image' - ]; - } + 'HeroImage.CMSThumbnail' => 'Hero Image', + ]; +} ``` diff --git a/docs/en/02_Developer_Guides/00_Model/12_Indexes.md b/docs/en/02_Developer_Guides/00_Model/12_Indexes.md index e517e74f9..6d686a26d 100644 --- a/docs/en/02_Developer_Guides/00_Model/12_Indexes.md +++ b/docs/en/02_Developer_Guides/00_Model/12_Indexes.md @@ -25,20 +25,19 @@ Indexes are represented on a `DataObject` through the `DataObject::$indexes` arr descriptor. There are several supported notations: ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyObject extends DataObject - { - - private static $indexes = [ - '<column-name>' => true, - '<index-name>' => [ - 'type' => '<type>', - 'columns' => ['<column-name>', '<other-column-name>'], - ], - '<index-name>' => ['<column-name>', '<other-column-name>'], - ]; - } +class MyObject extends DataObject +{ + private static $indexes = [ + '<column-name>' => true, + '<index-name>' => [ + 'type' => '<type>', + 'columns' => ['<column-name>', '<other-column-name>'], + ], + '<index-name>' => ['<column-name>', '<other-column-name>'], + ]; +} ``` The `<column-name>` is used to put a standard non-unique index on the column specified. For complex or large tables @@ -55,20 +54,19 @@ support the following: **mysite/code/MyTestObject.php** ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyTestObject extends DataObject - { +class MyTestObject extends DataObject +{ + private static $db = [ + 'MyField' => 'Varchar', + 'MyOtherField' => 'Varchar', + ]; - private static $db = [ - 'MyField' => 'Varchar', - 'MyOtherField' => 'Varchar', - ]; - - private static $indexes = [ - 'MyIndexName' => ['MyField', 'MyOtherField'], - ]; - } + private static $indexes = [ + 'MyIndexName' => ['MyField', 'MyOtherField'], + ]; +} ``` <div class="alert" markdown="1"> diff --git a/docs/en/02_Developer_Guides/00_Model/How_Tos/Dynamic_Default_Fields.md b/docs/en/02_Developer_Guides/00_Model/How_Tos/Dynamic_Default_Fields.md index bd4709a3e..c91c26b3f 100644 --- a/docs/en/02_Developer_Guides/00_Model/How_Tos/Dynamic_Default_Fields.md +++ b/docs/en/02_Developer_Guides/00_Model/How_Tos/Dynamic_Default_Fields.md @@ -10,30 +10,31 @@ object! A simple example is to set a field to the current date and time: ```php - /** - * Sets the Date field to the current date. - */ - public function populateDefaults() - { - $this->Date = date('Y-m-d'); - parent::populateDefaults(); - } +/** + * Sets the Date field to the current date. + */ +public function populateDefaults() +{ + $this->Date = date('Y-m-d'); + parent::populateDefaults(); +} ``` + It's also possible to get the data from any other source, or another object, just by using the usual data retrieval methods. For example: ```php - /** - * This method combines the Title of the parent object with the Title of this - * object in the FullTitle field. - */ - public function populateDefaults() - { - if($parent = $this->Parent()) { - $this->FullTitle = $parent->Title . ': ' . $this->Title; - } else { - $this->FullTitle = $this->Title; - } - parent::populateDefaults(); +/** + * This method combines the Title of the parent object with the Title of this + * object in the FullTitle field. + */ +public function populateDefaults() +{ + if($parent = $this->Parent()) { + $this->FullTitle = $parent->Title . ': ' . $this->Title; + } else { + $this->FullTitle = $this->Title; } -``` \ No newline at end of file + parent::populateDefaults(); +} +``` diff --git a/docs/en/02_Developer_Guides/00_Model/How_Tos/Grouping_DataObject_Sets.md b/docs/en/02_Developer_Guides/00_Model/How_Tos/Grouping_DataObject_Sets.md index 09a2f56d7..59ea486b5 100644 --- a/docs/en/02_Developer_Guides/00_Model/How_Tos/Grouping_DataObject_Sets.md +++ b/docs/en/02_Developer_Guides/00_Model/How_Tos/Grouping_DataObject_Sets.md @@ -35,48 +35,43 @@ along with a method that returns the first letter of the title. This will be used both for grouping and for the title in the template. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Module extends DataObject +class Module extends DataObject +{ + private static $db = [ + 'Title' => 'Text' + ]; + + /** + * Returns the first letter of the module title, used for grouping. + * @return string + */ + public function getTitleFirstLetter() { - private static $db = [ - 'Title' => 'Text' - ]; - - /** - * Returns the first letter of the module title, used for grouping. - * @return string - */ - public function getTitleFirstLetter() - { - return $this->Title[0]; - } + return $this->Title[0]; } - +} ``` The next step is to create a method or variable that will contain/return all the objects, sorted by title. For this example this will be a method on the `Page` class. ```php - use SilverStripe\CMS\Model\SiteTree; - use SilverStripe\ORM\GroupedList; +use SilverStripe\CMS\Model\SiteTree; +use SilverStripe\ORM\GroupedList; - class Page extends SiteTree +class Page extends SiteTree +{ + /** + * Returns all modules, sorted by their title. + * @return GroupedList + */ + public function getGroupedModules() { - - // ... - - /** - * Returns all modules, sorted by their title. - * @return GroupedList - */ - public function getGroupedModules() - { - return GroupedList::create(Module::get()->sort('Title')); - } - + return GroupedList::create(Module::get()->sort('Title')); } +} ``` The final step is to render this into a template. The `GroupedBy()` method breaks up the set into @@ -84,16 +79,16 @@ a number of sets, grouped by the field that is passed as the parameter. In this case, the `getTitleFirstLetter()` method defined earlier is used to break them up. ```ss - <%-- Modules list grouped by TitleFirstLetter --%> - <h2>Modules</h2> - <% loop $GroupedModules.GroupedBy(TitleFirstLetter) %> - <h3>$TitleFirstLetter</h3> - <ul> - <% loop $Children %> - <li>$Title</li> - <% end_loop %> - </ul> - <% end_loop %> +<%-- Modules list grouped by TitleFirstLetter --%> +<h2>Modules</h2> +<% loop $GroupedModules.GroupedBy(TitleFirstLetter) %> + <h3>$TitleFirstLetter</h3> + <ul> + <% loop $Children %> + <li>$Title</li> + <% end_loop %> + </ul> +<% end_loop %> ``` ## Grouping Sets By Month @@ -109,63 +104,55 @@ which is automatically set when the record is first written to the database. This will have a method which returns the month it was posted in: ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Module extends DataObject +class Module extends DataObject +{ + /** + * Returns the month name this news item was posted in. + * @return string + */ + public function getMonthCreated() { - - // ... - - /** - * Returns the month name this news item was posted in. - * @return string - */ - public function getMonthCreated() - { - return date('F', strtotime($this->Created)); - } - + return date('F', strtotime($this->Created)); } +} ``` The next step is to create a method that will return all records that exist, sorted by month name from January to December. This can be accomplshed by sorting by the `Created` field: ```php - use SilverStripe\CMS\Model\SiteTree; - use SilverStripe\ORM\GroupedList; +use SilverStripe\CMS\Model\SiteTree; +use SilverStripe\ORM\GroupedList; - class Page extends SiteTree +class Page extends SiteTree +{ + /** + * Returns all news items, sorted by the month they were posted + * @return GroupedList + */ + public function getGroupedModulesByDate() { - - // ... - - /** - * Returns all news items, sorted by the month they were posted - * @return GroupedList - */ - public function getGroupedModulesByDate() - { - return GroupedList::create(Module::get()->sort('Created')); - } - + return GroupedList::create(Module::get()->sort('Created')); } +} ``` The final step is the render this into the template using the [GroupedList::GroupedBy()](api:SilverStripe\ORM\GroupedList::GroupedBy()) method. ```ss - // Modules list grouped by the Month Posted - <h2>Modules</h2> - <% loop $GroupedModulesByDate.GroupedBy(MonthCreated) %> - <h3>$MonthCreated</h3> - <ul> - <% loop $Children %> - <li>$Title ($Created.Nice)</li> - <% end_loop %> - </ul> - <% end_loop %> +// Modules list grouped by the Month Posted +<h2>Modules</h2> +<% loop $GroupedModulesByDate.GroupedBy(MonthCreated) %> + <h3>$MonthCreated</h3> + <ul> + <% loop $Children %> + <li>$Title ($Created.Nice)</li> + <% end_loop %> + </ul> +<% end_loop %> ``` + ## Related * [Howto: "Pagination"](/developer_guides/templates/how_tos/pagination) - diff --git a/docs/en/02_Developer_Guides/01_Templates/01_Syntax.md b/docs/en/02_Developer_Guides/01_Templates/01_Syntax.md index 63195ccde..e7cd93381 100644 --- a/docs/en/02_Developer_Guides/01_Templates/01_Syntax.md +++ b/docs/en/02_Developer_Guides/01_Templates/01_Syntax.md @@ -12,33 +12,32 @@ An example of a SilverStripe template is below: **mysite/templates/Page.ss** ```ss +<html> + <head> + <% base_tag %> + <title>$Title + <% require themedCSS("screen") %> + + +
+

Bob's Chicken Shack

+
- - - <% base_tag %> - $Title - <% require themedCSS("screen") %> - - -
-

Bob's Chicken Shack

-
+ <% with $CurrentMember %> +

Welcome $FirstName $Surname.

+ <% end_with %> - <% with $CurrentMember %> -

Welcome $FirstName $Surname.

- <% end_with %> + <% if $Dishes %> +
    + <% loop $Dishes %> +
  • $Title ($Price.Nice)
  • + <% end_loop %> +
+ <% end_if %> - <% if $Dishes %> -
    - <% loop $Dishes %> -
  • $Title ($Price.Nice)
  • - <% end_loop %> -
- <% end_if %> - - <% include Footer %> - - + <% include Footer %> + + ```
@@ -69,8 +68,7 @@ Variables are placeholders that will be replaced with data from the [DataModel]( alphabetic character or underscore, with subsequent characters being alphanumeric or underscore: ```ss - - $Title +$Title ``` This inserts the value of the Title database field of the page being displayed in place of `$Title`. @@ -78,10 +76,9 @@ This inserts the value of the Title database field of the page being displayed i Variables can be chained together, and include arguments. ```ss - - $Foo - $Foo(param) - $Foo.Bar +$Foo +$Foo(param) +$Foo.Bar ``` These variables will call a method / field on the object and insert the returned value as a string into the template. @@ -104,17 +101,16 @@ Variables can come from your database fields, or custom methods you define on yo **mysite/code/Page.php** ```php - public function UsersIpAddress() - { - return $this->getRequest()->getIP(); - } +public function UsersIpAddress() +{ + return $this->getRequest()->getIP(); +} ``` **mysite/code/Page.ss** ```html - -

You are coming from $UsersIpAddress.

+

You are coming from $UsersIpAddress.

```
@@ -129,12 +125,11 @@ record and any subclasses of those two. **mysite/code/Layout/Page.ss** ```ss +$Title +// returns the page `Title` property - $Title - // returns the page `Title` property - - $Content - // returns the page `Content` property +$Content +// returns the page `Content` property ``` ## Conditional Logic @@ -142,19 +137,17 @@ record and any subclasses of those two. The simplest conditional block is to check for the presence of a value (does not equal 0, null, false). ```ss - - <% if $CurrentMember %> -

You are logged in as $CurrentMember.FirstName $CurrentMember.Surname.

- <% end_if %> +<% if $CurrentMember %> +

You are logged in as $CurrentMember.FirstName $CurrentMember.Surname.

+<% end_if %> ``` A conditional can also check for a value other than falsy. ```ss - - <% if $MyDinner == "kipper" %> - Yummy, kipper for tea. - <% end_if %> +<% if $MyDinner == "kipper" %> + Yummy, kipper for tea. +<% end_if %> ```
@@ -164,25 +157,23 @@ When inside template tags variables should have a '$' prefix, and literals shoul Conditionals can also provide the `else` case. ```ss - - <% if $MyDinner == "kipper" %> - Yummy, kipper for tea - <% else %> - I wish I could have kipper :-( - <% end_if %> +<% if $MyDinner == "kipper" %> + Yummy, kipper for tea +<% else %> + I wish I could have kipper :-( +<% end_if %> ``` `else_if` commands can be used to handle multiple `if` statements. ```ss - - <% if $MyDinner == "quiche" %> - Real men don't eat quiche - <% else_if $MyDinner == $YourDinner %> - We both have good taste - <% else %> - Can I have some of your chips? - <% end_if %> +<% if $MyDinner == "quiche" %> + Real men don't eat quiche +<% else_if $MyDinner == $YourDinner %> + We both have good taste +<% else %> + Can I have some of your chips? +<% end_if %> ``` ### Negation @@ -190,10 +181,9 @@ Conditionals can also provide the `else` case. The inverse of `<% if %>` is `<% if not %>`. ```ss - - <% if not $DinnerInOven %> - I'm going out for dinner tonight. - <% end_if %> +<% if not $DinnerInOven %> + I'm going out for dinner tonight. +<% end_if %> ``` ### Boolean Logic @@ -203,19 +193,17 @@ Multiple checks can be done using `||`, `or`, `&&` or `and`. If *either* of the conditions is true. ```ss - - <% if $MyDinner == "kipper" || $MyDinner == "salmon" %> - yummy, fish for tea - <% end_if %> +<% if $MyDinner == "kipper" || $MyDinner == "salmon" %> + yummy, fish for tea +<% end_if %> ``` If *both* of the conditions are true. ```ss - - <% if $MyDinner == "quiche" && $YourDinner == "kipper" %> - Lets swap dinners - <% end_if %> +<% if $MyDinner == "quiche" && $YourDinner == "kipper" %> + Lets swap dinners +<% end_if %> ``` ### Inequalities @@ -223,10 +211,9 @@ If *both* of the conditions are true. You can use inequalities like `<`, `<=`, `>`, `>=` to compare numbers. ```ss - - <% if $Number >= "5" && $Number <= "10" %> - Number between 5 and 10 - <% end_if %> +<% if $Number >= "5" && $Number <= "10" %> + Number between 5 and 10 +<% end_if %> ``` ## Includes @@ -236,37 +223,33 @@ will be searched for using the same filename look-up rules as a regular template an additional `Includes` directory will be inserted into the resolved path just prior to the filename. ```ss - - <% include SideBar %> - <% include MyNamespace/SideBar %> +<% include SideBar %> +<% include MyNamespace/SideBar %> ``` When using subfolders in your template structure (e.g. to fit with namespaces in your PHP class structure), the `Includes/` folder needs to be innermost. ```ss - - <% include MyNamespace/SideBar %> +<% include MyNamespace/SideBar %> ``` The `include` tag can be particularly helpful for nested functionality and breaking large templates up. In this example, the include only happens if the user is logged in. ```ss - - <% if $CurrentMember %> - <% include MembersOnlyInclude %> - <% end_if %> +<% if $CurrentMember %> + <% include MembersOnlyInclude %> +<% end_if %> ``` Includes can't directly access the parent scope when the include is included. However you can pass arguments to the include. ```ss - - <% with $CurrentMember %> - <% include MemberDetails Top=$Top, Name=$Name %> - <% end_with %> +<% with $CurrentMember %> + <% include MemberDetails Top=$Top, Name=$Name %> +<% end_with %> ``` ## Looping Over Lists @@ -275,14 +258,12 @@ The `<% loop %>` tag is used to iterate or loop over a collection of items such collection. ```ss - -

Children of $Title

- -
    - <% loop $Children %> -
  • $Title
  • - <% end_loop %> -
+

Children of $Title

+
    + <% loop $Children %> +
  • $Title
  • + <% end_loop %> +
``` This snippet loops over the children of a page, and generates an unordered list showing the `Title` property from each @@ -304,56 +285,51 @@ templates can call [DataList](api:SilverStripe\ORM\DataList) methods. Sorting the list by a given field. ```ss - -
    - <% loop $Children.Sort(Title, ASC) %> -
  • $Title
  • - <% end_loop %> -
+
    + <% loop $Children.Sort(Title, ASC) %> +
  • $Title
  • + <% end_loop %> +
``` Limiting the number of items displayed. ```ss - -
    - <% loop $Children.Limit(10) %> -
  • $Title
  • - <% end_loop %> -
+
    + <% loop $Children.Limit(10) %> +
  • $Title
  • + <% end_loop %> +
``` Reversing the loop. ```ss - -
    - <% loop $Children.Reverse %> -
  • $Title
  • - <% end_loop %> -
+
    + <% loop $Children.Reverse %> +
  • $Title
  • + <% end_loop %> +
``` Filtering the loop. ```ss - -
    - <% loop $Children.Filter('School', 'College') %> -
  • $Title
  • - <% end_loop %> -
+
    + <% loop $Children.Filter('School', 'College') %> +
  • $Title
  • + <% end_loop %> +
``` Methods can also be chained. ```ss - -
    - <% loop $Children.Filter('School', 'College').Sort(Score, DESC) %> -
  • $Title
  • - <% end_loop %> -
+
    + <% loop $Children.Filter('School', 'College').Sort(Score, DESC) %> +
  • $Title
  • + <% end_loop %> +
``` ### Position Indicators @@ -372,16 +348,15 @@ iteration. * `$TotalItems`: Number of items in the list (integer). ```ss +
    + <% loop $Children.Reverse %> + <% if First %> +
  • My Favourite
  • + <% end_if %> -
      - <% loop $Children.Reverse %> - <% if First %> -
    • My Favourite
    • - <% end_if %> - -
    • Child $Pos of $TotalItems - $Title
    • - <% end_loop %> -
    +
  • Child $Pos of $TotalItems - $Title
  • + <% end_loop %> +
```
@@ -394,20 +369,19 @@ pagination. $Modulus and $MultipleOf can help to build column and grid layouts. ```ss +// returns an int +$Modulus(value, offset) - // returns an int - $Modulus(value, offset) +// returns a boolean. +$MultipleOf(factor, offset) - // returns a boolean. - $MultipleOf(factor, offset) +<% loop $Children %> +
+ ... +
+<% end_loop %> - <% loop $Children %> -
- ... -
- <% end_loop %> - - // returns
,
, +// returns
,
, ```
@@ -419,12 +393,11 @@ $MultipleOf(value, offset) can also be utilized to build column and grid layouts after every 3rd item. ```ss - - <% loop $Children %> - <% if $MultipleOf(3) %> -
- <% end_if %> - <% end_loop %> +<% loop $Children %> + <% if $MultipleOf(3) %> +
+ <% end_if %> +<% end_loop %> ``` ### Escaping @@ -432,25 +405,22 @@ after every 3rd item. Sometimes you will have template tags which need to roll into one another. Use `{}` to contain variables. ```ss - - $Foopx // will returns "" (as it looks for a `Foopx` value) - {$Foo}px // returns "3px" (CORRECT) +$Foopx // will returns "" (as it looks for a `Foopx` value) +{$Foo}px // returns "3px" (CORRECT) ``` Or when having a `$` sign in front of the variable such as displaying money. ```ss - - $$Foo // returns "" - ${$Foo} // returns "$3" +$$Foo // returns "" +${$Foo} // returns "$3" ``` You can also use a backslash to escape the name of the variable, such as: ```ss - - $Foo // returns "3" - \$Foo // returns "$Foo" +$Foo // returns "3" +\$Foo // returns "$Foo" ```
@@ -480,16 +450,15 @@ classes of the current scope object, and any [Extension](api:SilverStripe\Core\E When in a particular scope, `$Up` takes the scope back to the previous level. ```ss +

Children of '$Title'

-

Children of '$Title'

+<% loop $Children %> +

Page '$Title' is a child of '$Up.Title'

<% loop $Children %> -

Page '$Title' is a child of '$Up.Title'

- - <% loop $Children %> -

Page '$Title' is a grandchild of '$Up.Up.Title'

- <% end_loop %> +

Page '$Title' is a grandchild of '$Up.Up.Title'

<% end_loop %> +<% end_loop %> ``` Given the following structure, it will output the text. @@ -513,12 +482,11 @@ Additional selectors implicitely change the scope so you need to put additional
```ss - -

Children of '$Title'

- <% loop $Children.Sort('Title').First %> - <%-- We have two additional selectors in the loop expression so... --%> -

Page '$Title' is a child of '$Up.Up.Up.Title'

- <% end_loop %> +

Children of '$Title'

+<% loop $Children.Sort('Title').First %> + <%-- We have two additional selectors in the loop expression so... --%> +

Page '$Title' is a child of '$Up.Up.Up.Title'

+<% end_loop %> ``` #### Top @@ -527,16 +495,15 @@ While `$Up` provides us a way to go up one level of scope, `$Top` is a shortcut page. The previous example could be rewritten to use the following syntax. ```ss +

Children of '$Title'

-

Children of '$Title'

+<% loop $Children %> +

Page '$Title' is a child of '$Top.Title'

<% loop $Children %> -

Page '$Title' is a child of '$Top.Title'

- - <% loop $Children %> -

Page '$Title' is a grandchild of '$Top.Title'

- <% end_loop %> +

Page '$Title' is a grandchild of '$Top.Title'

<% end_loop %> +<% end_loop %> ``` ### With @@ -544,17 +511,15 @@ page. The previous example could be rewritten to use the following syntax. The `<% with %>` tag lets you change into a new scope. Consider the following example: ```ss - - <% with $CurrentMember %> - Hello, $FirstName, welcome back. Your current balance is $Balance. - <% end_with %> +<% with $CurrentMember %> + Hello, $FirstName, welcome back. Your current balance is $Balance. +<% end_with %> ``` This is functionalty the same as the following: ```ss - - Hello, $CurrentMember.FirstName, welcome back. Your current balance is $CurrentMember.Balance +Hello, $CurrentMember.FirstName, welcome back. Your current balance is $CurrentMember.Balance ``` Notice that the first example is much tidier, as it removes the repeated use of the `$CurrentMember` accessor. @@ -568,8 +533,7 @@ refer directly to properties and methods of the [Member](api:SilverStripe\Securi `$Me` outputs the current object in scope. This will call the `forTemplate` of the object. ```ss - - $Me +$Me ``` ## Comments @@ -577,16 +541,14 @@ refer directly to properties and methods of the [Member](api:SilverStripe\Securi Using standard HTML comments is supported. These comments will be included in the published site. ```ss - - $EditForm +$EditForm ``` However you can also use special SilverStripe comments which will be stripped out of the published site. This is useful for adding notes for other developers but for things you don't want published in the public html. ```ss - - $EditForm <%-- Some hidden comment about the form --%> +$EditForm <%-- Some hidden comment about the form --%> ``` ## Related diff --git a/docs/en/02_Developer_Guides/01_Templates/02_Common_Variables.md b/docs/en/02_Developer_Guides/01_Templates/02_Common_Variables.md index c1ac8ce94..076336c20 100644 --- a/docs/en/02_Developer_Guides/01_Templates/02_Common_Variables.md +++ b/docs/en/02_Developer_Guides/01_Templates/02_Common_Variables.md @@ -31,12 +31,11 @@ functionality may not be included. ## Base Tag ```ss + + <% base_tag %> - - <% base_tag %> - - .. - + .. + ``` The `<% base_tag %>` placeholder is replaced with the HTML base element. Relative links within a document (such as ` is nearly always required or assumed by SilverStripe to exist ## CurrentMember -Returns the currently logged in [Member](api:SilverStripe\Security\Member) instance, if there is one logged in.```ss +Returns the currently logged in [Member](api:SilverStripe\Security\Member) instance, if there is one logged in. - <% if $CurrentMember %> - Welcome Back, $CurrentMember.FirstName - <% end_if %> +```ss +<% if $CurrentMember %> + Welcome Back, $CurrentMember.FirstName +<% end_if %> ``` ## Title and Menu Title ```ss - - $Title - $MenuTitle +$Title +$MenuTitle ``` Most objects within SilverStripe will respond to `$Title` (i.e they should have a `Title` database field or at least a @@ -79,8 +78,7 @@ If `MenuTitle` is left blank by the CMS author, it'll just default to the value ## Page Content ```ss - - $Content +$Content ``` It returns the database content of the `Content` property. With the CMS Module, this is the value of the WYSIWYG editor @@ -103,8 +101,7 @@ web pages. You'll need to install it via `composer`.
```ss - - $SiteConfig.Title +$SiteConfig.Title ``` The [SiteConfig](../configuration/siteconfig) object allows content authors to modify global data in the CMS, rather @@ -127,31 +124,29 @@ If you don’t want to include the title tag use `$MetaTags(false)`. By default `$MetaTags` renders: ```ss - - Title of the Page - - +Title of the Page + + ``` -`$MetaTags(false)` will render```ss +`$MetaTags(false)` will render - - +```ss + + ``` If using `$MetaTags(false)` we can provide a more custom `title`. ```ss - - $MetaTags(false) - $Title - Bob's Fantasy Football +$MetaTags(false) +$Title - Bob's Fantasy Football ``` ## Links ```ss - - .. +.. ``` All objects that could be accessible in SilverStripe should define a `Link` method and an `AbsoluteLink` method. Link @@ -159,20 +154,18 @@ returns the relative URL for the object and `AbsoluteLink` outputs your full web link. ```ss +$Link + - $Link - - - $AbsoluteLink - +$AbsoluteLink + ``` ### Linking Modes ```ss - - $isSection - $isCurrent +$isSection +$isCurrent ``` When looping over a list of `SiteTree` instances through a `<% loop $Menu %>` or `<% loop $Children %>`, `$isSection` and `$isCurrent` @@ -181,19 +174,17 @@ will return true or false based on page being looped over relative to the curren For instance, to only show the menu item linked if it's the current one: ```ss - - <% if $isCurrent %> - $Title - <% else %> - $Title - <% end_if %> +<% if $isCurrent %> + $Title +<% else %> + $Title +<% end_if %> ``` An example for checking for `current` or `section` is as follows: ```ss - - $MenuTitle +$MenuTitle ``` **Additional Utility Method** @@ -201,10 +192,9 @@ An example for checking for `current` or `section` is as follows: * `$InSection(page-url)`: This if block will pass if we're currently on the page-url page or one of its children. ```ss - - <% if $InSection(about-us) %> -

You are viewing the about us section

- <% end_if %> +<% if $InSection(about-us) %> +

You are viewing the about us section

+<% end_if %> ``` ### URLSegment @@ -214,12 +204,11 @@ This returns the part of the URL of the page you're currently on. For example on It can be used within templates to generate anchors or other CSS classes. ```ss +
-
+
-
- - + ``` ## ClassName @@ -229,19 +218,17 @@ handy for a number of uses. A common use case is to add to your `` tag to behavior based on the page type used: ```ss + - - - + ``` ## Children Loops ```ss +<% loop $Children %> - <% loop $Children %> - - <% end_loop %> +<% end_loop %> ``` Will loop over all Children records of the current object context. Children are pages that sit under the current page in @@ -255,10 +242,9 @@ context. ### ChildrenOf ```ss +<% loop $ChildrenOf() %> - <% loop $ChildrenOf() %> - - <% end_loop %> +<% end_loop %> ``` Will create a list of the children of the given page, as identified by its `URLSegment` value. This can come in handy @@ -273,19 +259,17 @@ This option will be honored by `<% loop $Children %>` and `<% loop $Menu %>` how preference, `AllChildren` does not filter by `ShowInMenus`. ```ss - - <% loop $AllChildren %> - ... - <% end_loop %> +<% loop $AllChildren %> + ... +<% end_loop %> ``` ### Menu Loops ```ss - - <% loop $Menu(1) %> - ... - <% end_loop %> +<% loop $Menu(1) %> + ... +<% end_loop %> ``` `$Menu(1)` returns the top-level menu of the website. You can also create a sub-menu using `$Menu(2)`, and so forth. @@ -297,10 +281,9 @@ Pages with the `ShowInMenus` property set to `false` will be filtered out. ## Access to a specific Page ```ss - - <% with $Page(my-page) %> - $Title - <% end_with %> +<% with $Page(my-page) %> + $Title +<% end_with %> ``` Page will return a single page from site, looking it up by URL. @@ -310,10 +293,9 @@ Page will return a single page from site, looking it up by URL. ### Level ```ss - - <% with $Level(1) %> - $Title - <% end_with %> +<% with $Level(1) %> + $Title +<% end_with %> ``` Will return a page in the current path, at the level specified by the numbers. It is based on the current page context, @@ -328,14 +310,13 @@ For example, imagine you're on the "bob marley" page, which is three levels in: ### Parent ```ss + - - - $Parent.Title - +$Parent.Title + - $Parent.Parent.Title - +$Parent.Parent.Title + ``` ## Navigating Scope @@ -351,20 +332,18 @@ While you can achieve breadcrumbs through the `$Level()` control manually `$Breadcrumbs` variable. ```ss - - $Breadcrumbs +$Breadcrumbs ``` By default, it uses the template defined in `templates/BreadcrumbsTemplate.ss` of the `silverstripe/cms` module. ```ss - - <% if $Pages %> - <% loop $Pages %> - <% if $Last %>$Title.XML<% else %>$MenuTitle.XML »<% end_if %> - <% end_loop %> - <% end_if %> +<% if $Pages %> + <% loop $Pages %> + <% if $Last %>$Title.XML<% else %>$MenuTitle.XML »<% end_if %> + <% end_loop %> +<% end_if %> ```
@@ -376,8 +355,7 @@ To customise the markup that the `$Breadcrumbs` generates, copy `templates/Bread ## Forms ```ss - - $Form +$Form ``` A page will normally contain some content and potentially a form of some kind. For example, the log-in page has a the diff --git a/docs/en/02_Developer_Guides/01_Templates/03_Requirements.md b/docs/en/02_Developer_Guides/01_Templates/03_Requirements.md index 7bde9ec2c..f7c8687ec 100644 --- a/docs/en/02_Developer_Guides/01_Templates/03_Requirements.md +++ b/docs/en/02_Developer_Guides/01_Templates/03_Requirements.md @@ -16,10 +16,9 @@ The `Requirements` class can work with arbitrary file paths. **/templates/SomeTemplate.ss** ```ss - - <% require css("/css/some_file.css") %> - <% require themedCSS("some_themed_file") %> - <% require javascript("/javascript/some_file.js") %> +<% require css("/css/some_file.css") %> +<% require themedCSS("some_themed_file") %> +<% require javascript("/javascript/some_file.js") %> ```
diff --git a/docs/en/02_Developer_Guides/01_Templates/05_Template_Inheritance.md b/docs/en/02_Developer_Guides/01_Templates/05_Template_Inheritance.md index 6197574b1..2ef9e8124 100644 --- a/docs/en/02_Developer_Guides/01_Templates/05_Template_Inheritance.md +++ b/docs/en/02_Developer_Guides/01_Templates/05_Template_Inheritance.md @@ -15,12 +15,12 @@ Instead of editing that file to provide a custom template for your application, name in the `mysite/templates/email` folder or in the `themes/your_theme/templates/email` folder if you're using themes. **mysite/templates/email/GenericEmail.ss** - -```ss - $Body -

Thanks from Bob's Fantasy Football League.

+```ss +$Body +

Thanks from Bob's Fantasy Football League.

``` + All emails going out of our application will have the footer `Thanks from Bob's Fantasy Football Leaguee` added.
@@ -102,32 +102,37 @@ footer and navigation will remain the same and we don't want to replicate this w `$Layout` function allows us to define the child template area which can be overridden. **mysite/templates/Page.ss** + ```ss - - - .. - - - - <% include Header %> - <% include Navigation %> + + + .. + - $Layout + + <% include Header %> + <% include Navigation %> - <% include Footer %> - -`` -**mysite/templates/Layout/Page.ss** -```ss -

You are on a $Title page

+ $Layout - $Content + <% include Footer %> + ``` -**mysite/templates/Layout/HomePage.ss** -```ss -

This is the homepage!

- Hi! +**mysite/templates/Layout/Page.ss** + +```ss +

You are on a $Title page

+ +$Content +``` + +**mysite/templates/Layout/HomePage.ss** + +```ss +

This is the homepage!

+ +Hi! ``` If your classes have in a namespace, the Layout folder will be a found inside of the appropriate namespace folder. diff --git a/docs/en/02_Developer_Guides/01_Templates/07_Caching.md b/docs/en/02_Developer_Guides/01_Templates/07_Caching.md index 3104f2652..a9e28fb94 100644 --- a/docs/en/02_Developer_Guides/01_Templates/07_Caching.md +++ b/docs/en/02_Developer_Guides/01_Templates/07_Caching.md @@ -9,22 +9,21 @@ All functions that provide data to templates must have no side effects, as the v example, this controller method will not behave as you might imagine. ```php - private $counter = 0; +private $counter = 0; - public function Counter() - { - $this->counter += 1; +public function Counter() +{ + $this->counter += 1; - return $this->counter; - } + return $this->counter; +} ``` ```ss +$Counter, $Counter, $Counter - $Counter, $Counter, $Counter - - // returns 1, 1, 1 +// returns 1, 1, 1 ``` When we render `$Counter` to the template we would expect the value to increase and output `1, 2, 3`. However, as @@ -37,10 +36,9 @@ Partial caching is a feature that allows the caching of just a portion of a page from the database to display, the contents of the area are fetched from a [cache backend](../performance/caching). ```ss - - <% cached 'MyCachedContent', LastEdited %> - $Title - <% end_cached %> +<% cached 'MyCachedContent', LastEdited %> + $Title +<% end_cached %> ``` diff --git a/docs/en/02_Developer_Guides/01_Templates/08_Translations.md b/docs/en/02_Developer_Guides/01_Templates/08_Translations.md index 498d8612f..daf917b2f 100644 --- a/docs/en/02_Developer_Guides/01_Templates/08_Translations.md +++ b/docs/en/02_Developer_Guides/01_Templates/08_Translations.md @@ -5,11 +5,13 @@ summary: Definition of the syntax for writing i18n compatible templates. Translations are easy to use with a template, and give access to SilverStripe's translation facilities. Here is an example: -```ss - <%t Foo.BAR 'Bar' %> - <%t Member.WELCOME 'Welcome {name} to {site}' name=$Member.Name site="Foobar.com" %> +```ss +<%t Foo.BAR 'Bar' %> + +<%t Member.WELCOME 'Welcome {name} to {site}' name=$Member.Name site="Foobar.com" %> ``` + `Member.WELCOME` is an identifier in the translation system, for which different translations may be available. This string may include named placeholders, in braces. diff --git a/docs/en/02_Developer_Guides/01_Templates/09_Casting.md b/docs/en/02_Developer_Guides/01_Templates/09_Casting.md index 9f5db2717..36cac3350 100644 --- a/docs/en/02_Developer_Guides/01_Templates/09_Casting.md +++ b/docs/en/02_Developer_Guides/01_Templates/09_Casting.md @@ -13,27 +13,25 @@ output the result of the [DBHtmlText::FirstParagraph()](api:SilverStripe\ORM\Fie **mysite/code/Page.ss** ```ss +$Content.FirstParagraph + - $Content.FirstParagraph - - - $LastEdited.Format("d/m/Y") - +$LastEdited.Format("d/m/Y") + ``` Any public method from the object in scope can be called within the template. If that method returns another `ViewableData` instance, you can chain the method calls. ```ss +$Content.FirstParagraph.NoHTML + - $Content.FirstParagraph.NoHTML - +

Copyright {$Now.Year}

+ -

Copyright {$Now.Year}

- - -
- +
+ ```
@@ -47,24 +45,25 @@ When rendering an object to the template such as `$Me` the `forTemplate` method provide default template for an object. **mysite/code/Page.php** + ```php - use SilverStripe\CMS\Model\SiteTree; +use SilverStripe\CMS\Model\SiteTree; - class Page extends SiteTree +class Page extends SiteTree +{ + + public function forTemplate() { - - public function forTemplate() - { - return "Page: ". $this->Title; - } + return "Page: ". $this->Title; } +} ``` **mysite/templates/Page.ss** -```ss - $Me - +```ss +$Me + ``` ## Casting @@ -74,21 +73,20 @@ content that method sends back, or, provide a type in the `$casting` array for t to a template, SilverStripe will ensure that the object is wrapped in the correct type and values are safely escaped. ```php - use SilverStripe\CMS\Model\SiteTree; +use SilverStripe\CMS\Model\SiteTree; - class Page extends SiteTree +class Page extends SiteTree +{ + + private static $casting = [ + 'MyCustomMethod' => 'HTMLText' + ]; + + public function MyCustomMethod() { - - private static $casting = [ - 'MyCustomMethod' => 'HTMLText' - ]; - - public function MyCustomMethod() - { - return "

This is my header

"; - } + return "

This is my header

"; } - +} ``` When calling `$MyCustomMethod` SilverStripe now has the context that this method will contain HTML and escape the data diff --git a/docs/en/02_Developer_Guides/01_Templates/How_Tos/01_Navigation_Menu.md b/docs/en/02_Developer_Guides/01_Templates/How_Tos/01_Navigation_Menu.md index 4dc53b965..db43e9ad7 100644 --- a/docs/en/02_Developer_Guides/01_Templates/How_Tos/01_Navigation_Menu.md +++ b/docs/en/02_Developer_Guides/01_Templates/How_Tos/01_Navigation_Menu.md @@ -8,26 +8,26 @@ top level menu with a nested second level using the `Menu` loop and a `Children` **mysite/templates/Page.ss** ```ss -
    - <% loop $Menu(1) %> -
  • - - $MenuTitle - +
      + <% loop $Menu(1) %> +
    • + + $MenuTitle + - <% if $isSection %> - <% if $Children %> -
        - <% loop $Children %> -
      • $MenuTitle
      • - <% end_loop %> -
      - <% end_if %> - <% end_if %> -
    • - <% end_loop %> -
    -``` + <% if $isSection %> + <% if $Children %> +
      + <% loop $Children %> +
    • $MenuTitle
    • + <% end_loop %> +
    + <% end_if %> + <% end_if %> +
  • + <% end_loop %> +
+```w ## Related * [Template Syntax](../syntax) diff --git a/docs/en/02_Developer_Guides/01_Templates/How_Tos/02_Pagination.md b/docs/en/02_Developer_Guides/01_Templates/How_Tos/02_Pagination.md index 681a995c0..7dae00134 100644 --- a/docs/en/02_Developer_Guides/01_Templates/How_Tos/02_Pagination.md +++ b/docs/en/02_Developer_Guides/01_Templates/How_Tos/02_Pagination.md @@ -11,17 +11,17 @@ The `PaginatedList` will automatically set up query limits and read the request **mysite/code/Page.php** ```php - use SilverStripe\ORM\PaginatedList; +use SilverStripe\ORM\PaginatedList; - /** - * Returns a paginated list of all pages in the site. - */ - public function PaginatedPages() - { - $list = Page::get(); +/** + * Returns a paginated list of all pages in the site. + */ +public function PaginatedPages() +{ + $list = Page::get(); - return new PaginatedList($list, $this->getRequest()); - } + return new PaginatedList($list, $this->getRequest()); +} ```
@@ -37,11 +37,11 @@ The first step is to simply list the objects in the template: **mysite/templates/Page.ss** ```ss -
    - <% loop $PaginatedPages %> -
  • $Title
  • - <% end_loop %> -
+
    + <% loop $PaginatedPages %> +
  • $Title
  • + <% end_loop %> +
``` By default this will display 10 pages at a time. The next step is to add pagination controls below this so the user can switch between pages: @@ -49,25 +49,25 @@ switch between pages: **mysite/templates/Page.ss** ```ss - <% if $PaginatedPages.MoreThanOnePage %> - <% if $PaginatedPages.NotFirstPage %> - - <% end_if %> - <% loop $PaginatedPages.Pages %> - <% if $CurrentBool %> - $PageNum - <% else %> - <% if $Link %> - $PageNum - <% else %> - ... - <% end_if %> - <% end_if %> - <% end_loop %> - <% if $PaginatedPages.NotLastPage %> - - <% end_if %> - <% end_if %> +<% if $PaginatedPages.MoreThanOnePage %> + <% if $PaginatedPages.NotFirstPage %> + + <% end_if %> + <% loop $PaginatedPages.Pages %> + <% if $CurrentBool %> + $PageNum + <% else %> + <% if $Link %> + $PageNum + <% else %> + ... + <% end_if %> + <% end_if %> + <% end_loop %> + <% if $PaginatedPages.NotLastPage %> + + <% end_if %> +<% end_if %> ``` If there is more than one page, this block will render a set of pagination controls in the form @@ -81,19 +81,19 @@ will break the pagination. You can disable automatic limiting using the [Paginat when using custom lists. ```php - use SilverStripe\ORM\PaginatedList; - - $myPreLimitedList = Page::get()->limit(10); +use SilverStripe\ORM\PaginatedList; - $pages = new PaginatedList($myPreLimitedList, $this->getRequest()); - $pages->setLimitItems(false); +$myPreLimitedList = Page::get()->limit(10); + +$pages = new PaginatedList($myPreLimitedList, $this->getRequest()); +$pages->setLimitItems(false); ``` ## Setting the limit of items ```php - $pages = new PaginatedList(Page::get(), $this->getRequest()); - $pages->setPageLength(25); +$pages = new PaginatedList(Page::get(), $this->getRequest()); +$pages->setPageLength(25); ``` If you set this limit to 0 it will disable paging entirely, effectively causing it to appear as a single page diff --git a/docs/en/02_Developer_Guides/01_Templates/How_Tos/03_Disable_Anchor_Links.md b/docs/en/02_Developer_Guides/01_Templates/How_Tos/03_Disable_Anchor_Links.md index 54af5a052..8d630be69 100644 --- a/docs/en/02_Developer_Guides/01_Templates/How_Tos/03_Disable_Anchor_Links.md +++ b/docs/en/02_Developer_Guides/01_Templates/How_Tos/03_Disable_Anchor_Links.md @@ -6,10 +6,10 @@ Anchor links are links with a "#" in them. A frequent use-case is to use anchor the current page. For example, we might have this in our template: ```ss - + ``` Things get tricky because of we have set our `` tag to point to the root of the site. So, when you click the @@ -20,10 +20,10 @@ doesn't specify a URL before the anchor, prefixing the URL of the current page. would be created in the final HTML ```ss - + ``` There are cases where this can be unhelpful. HTML anchors created from Ajax responses are the most common. In these @@ -40,14 +40,14 @@ SilverStripe\View\SSViewer: Or, a better way is to call this just for the rendering phase of this particular file: ```php - use SilverStripe\View\SSViewer; - - public function RenderCustomTemplate() - { - SSViewer::setRewriteHashLinks(false); - $html = $this->renderWith('MyCustomTemplate'); - SSViewer::setRewriteHashLinks(true); +use SilverStripe\View\SSViewer; - return $html; - } -``` +public function RenderCustomTemplate() +{ + SSViewer::setRewriteHashLinks(false); + $html = $this->renderWith('MyCustomTemplate'); + SSViewer::setRewriteHashLinks(true); + + return $html; +} +``` diff --git a/docs/en/02_Developer_Guides/02_Controllers/01_Introduction.md b/docs/en/02_Developer_Guides/02_Controllers/01_Introduction.md index 2b8b8d9ba..a0e01f942 100644 --- a/docs/en/02_Developer_Guides/02_Controllers/01_Introduction.md +++ b/docs/en/02_Developer_Guides/02_Controllers/01_Introduction.md @@ -9,27 +9,26 @@ subclass the base `Controller` class. **mysite/code/controllers/TeamController.php** ```php - use SilverStripe\Control\Controller; +use SilverStripe\Control\Controller; - class TeamController extends Controller - { - - private static $allowed_actions = [ - 'players', - 'index' - ]; +class TeamController extends Controller +{ - public function index(HTTPRequest $request) - { - // .. - } - - public function players(HTTPRequest $request) - { - print_r($request->allParams()); - } + private static $allowed_actions = [ + 'players', + 'index' + ]; + + public function index(HTTPRequest $request) + { + // .. } + public function players(HTTPRequest $request) + { + print_r($request->allParams()); + } +} ``` ## Routing @@ -50,14 +49,13 @@ Make sure that after you have modified the `routes.yml` file, that you clear you **mysite/_config/routes.yml** ```yml - - --- - Name: mysiteroutes - After: framework/routes#coreroutes - --- - SilverStripe\Control\Director: - rules: - 'teams//$Action/$ID/$Name': 'TeamController' +--- +Name: mysiteroutes +After: framework/routes#coreroutes +--- +SilverStripe\Control\Director: + rules: + 'teams//$Action/$ID/$Name': 'TeamController' ``` For more information about creating custom routes, see the [Routing](routing) documentation. @@ -81,63 +79,62 @@ Action methods can return one of four main things: **mysite/code/controllers/TeamController.php** ```php - /** - * Return some additional data to the current response that is waiting to go out, this makes $Title set to - * 'MyTeamName' and continues on with generating the response. - */ - public function index(HTTPRequest $request) - { - return [ - 'Title' => 'My Team Name' - ]; - } +/** + * Return some additional data to the current response that is waiting to go out, this makes $Title set to + * 'MyTeamName' and continues on with generating the response. + */ +public function index(HTTPRequest $request) +{ + return [ + 'Title' => 'My Team Name' + ]; +} - /** - * We can manually create a response and return that to ignore any previous data. - */ - public function someaction(HTTPRequest $request) - { - $this->setResponse(new HTTPResponse()); - $this->getResponse()->setStatusCode(400); - $this->getResponse()->setBody('invalid'); +/** + * We can manually create a response and return that to ignore any previous data. + */ +public function someaction(HTTPRequest $request) +{ + $this->setResponse(new HTTPResponse()); + $this->getResponse()->setStatusCode(400); + $this->getResponse()->setBody('invalid'); - return $this->getResponse(); - } + return $this->getResponse(); +} - /** - * Or, we can modify the response that is waiting to go out. - */ - public function anotheraction(HTTPRequest $request) - { - $this->getResponse()->setStatusCode(400); +/** + * Or, we can modify the response that is waiting to go out. + */ +public function anotheraction(HTTPRequest $request) +{ + $this->getResponse()->setStatusCode(400); - return $this->getResponse(); - } + return $this->getResponse(); +} - /** - * We can render HTML and leave SilverStripe to set the response code and body. - */ - public function htmlaction() - { - return $this->customise(new ArrayData([ - 'Title' => 'HTML Action' - ]))->renderWith('MyCustomTemplate'); - } +/** + * We can render HTML and leave SilverStripe to set the response code and body. + */ +public function htmlaction() +{ + return $this->customise(new ArrayData([ + 'Title' => 'HTML Action' + ]))->renderWith('MyCustomTemplate'); +} - /** - * We can send stuff to the browser which isn't HTML - */ - public function ajaxaction() - { - $this->getResponse()->setBody(json_encode([ - 'json' => true - ])); +/** + * We can send stuff to the browser which isn't HTML + */ +public function ajaxaction() +{ + $this->getResponse()->setBody(json_encode([ + 'json' => true + ])); - $this->getResponse()->addHeader("Content-type", "application/json"); - - return $this->getResponse(). - } + $this->getResponse()->addHeader("Content-type", "application/json"); + return $this->getResponse(). +} ``` For more information on how a URL gets mapped to an action see the [Routing](routing) documentation. @@ -167,10 +164,10 @@ Each controller should define a `Link()` method. This should be used to avoid ha **mysite/code/controllers/TeamController.php** ```php - public function Link($action = null) - { - return Controller::join_links('teams', $action); - } +public function Link($action = null) +{ + return Controller::join_links('teams', $action); +} ```
diff --git a/docs/en/02_Developer_Guides/02_Controllers/03_Access_Control.md b/docs/en/02_Developer_Guides/02_Controllers/03_Access_Control.md index dc66f4ebe..f24089630 100644 --- a/docs/en/02_Developer_Guides/02_Controllers/03_Access_Control.md +++ b/docs/en/02_Developer_Guides/02_Controllers/03_Access_Control.md @@ -12,32 +12,31 @@ Any action you define on a controller must be defined in a `$allowed_actions` st directly calling methods that they shouldn't. ```php - use SilverStripe\Control\Controller; +use SilverStripe\Control\Controller; - class MyController extends Controller - { +class MyController extends Controller +{ + + private static $allowed_actions = [ + // someaction can be accessed by anyone, any time + 'someaction', + + // So can otheraction + 'otheraction' => true, - private static $allowed_actions = [ - // someaction can be accessed by anyone, any time - 'someaction', + // restrictedaction can only be people with ADMIN privilege + 'restrictedaction' => 'ADMIN', - // So can otheraction - 'otheraction' => true, - - // restrictedaction can only be people with ADMIN privilege - 'restrictedaction' => 'ADMIN', - - // restricted to uses that have the 'CMS_ACCESS_CMSMain' access - 'cmsrestrictedaction' => 'CMS_ACCESS_CMSMain', - - // complexaction can only be accessed if $this->canComplexAction() returns true. - 'complexaction' => '->canComplexAction', - - // complexactioncheck can only be accessed if $this->canComplexAction("MyRestrictedAction", false, 42) is true. - 'complexactioncheck' => '->canComplexAction("MyRestrictedAction", false, 42)', - ]; - } + // restricted to uses that have the 'CMS_ACCESS_CMSMain' access + 'cmsrestrictedaction' => 'CMS_ACCESS_CMSMain', + + // complexaction can only be accessed if $this->canComplexAction() returns true. + 'complexaction' => '->canComplexAction', + // complexactioncheck can only be accessed if $this->canComplexAction("MyRestrictedAction", false, 42) is true. + 'complexactioncheck' => '->canComplexAction("MyRestrictedAction", false, 42)', + ]; +} ```
@@ -48,88 +47,86 @@ An action named "index" is white listed by default, unless `allowed_actions` is is specifically restricted. ```php - use SilverStripe\Control\Controller; +use SilverStripe\Control\Controller; + +class MyController extends Controller +{ - getVar('apikey')) { - return $this->httpError(403, 'No API key provided'); - } - - return 'valid'; - } + if(!$request->getVar('apikey')) { + return $this->httpError(403, 'No API key provided'); + } + + return 'valid'; } +} ``` @@ -206,25 +204,25 @@ execution. This behavior can be used to implement permission checks.
`init` is called for any possible action on the controller and before any specific method such as `index`.
+ ```php - use SilverStripe\Security\Permission; - use SilverStripe\Control\Controller; +use SilverStripe\Security\Permission; +use SilverStripe\Control\Controller; - class MyController extends Controller +class MyController extends Controller +{ + + private static $allowed_actions = []; + + public function init() { - - private static $allowed_actions = []; - - public function init() - { - parent::init(); + parent::init(); - if(!Permission::check('ADMIN')) { - return $this->httpError(403); - } + if(!Permission::check('ADMIN')) { + return $this->httpError(403); } } - +} ``` ## Related Documentation diff --git a/docs/en/02_Developer_Guides/02_Controllers/04_Redirection.md b/docs/en/02_Developer_Guides/02_Controllers/04_Redirection.md index 60e6c78d9..0c0ce7ec2 100644 --- a/docs/en/02_Developer_Guides/02_Controllers/04_Redirection.md +++ b/docs/en/02_Developer_Guides/02_Controllers/04_Redirection.md @@ -10,26 +10,27 @@ HTTP header. ```php - $this->redirect('goherenow'); - // redirect to Page::goherenow(), i.e on the contact-us page this will redirect to /contact-us/goherenow/ +$this->redirect('goherenow'); +// redirect to Page::goherenow(), i.e on the contact-us page this will redirect to /contact-us/goherenow/ - $this->redirect('goherenow/'); - // redirect to the URL on yoursite.com/goherenow/. (note the trailing slash) +$this->redirect('goherenow/'); +// redirect to the URL on yoursite.com/goherenow/. (note the trailing slash) - $this->redirect('http://google.com'); - // redirect to http://google.com +$this->redirect('http://google.com'); +// redirect to http://google.com - $this->redirectBack(); - // go back to the previous page. +$this->redirectBack(); +// go back to the previous page. ``` ## Status Codes The `redirect()` method takes an optional HTTP status code, either `301` for permanent redirects, or `302` for temporary redirects (default). + ```php - $this->redirect('/', 302); - // go back to the homepage, don't cache that this page has moved +$this->redirect('/', 302); +// go back to the homepage, don't cache that this page has moved ``` ## Redirection in URL Handling @@ -37,12 +38,10 @@ temporary redirects (default). Controllers can specify redirections in the `$url_handlers` property rather than defining a method by using the '~' operator. - ```php - private static $url_handlers = [ - 'players/john' => '~>coach' - ]; - +private static $url_handlers = [ + 'players/john' => '~>coach' +]; ``` For more information on `$url_handlers` see the [Routing](routing) documenation. diff --git a/docs/en/02_Developer_Guides/03_Forms/00_Introduction.md b/docs/en/02_Developer_Guides/03_Forms/00_Introduction.md index 3fcfbba03..d2cc94dfa 100644 --- a/docs/en/02_Developer_Guides/03_Forms/00_Introduction.md +++ b/docs/en/02_Developer_Guides/03_Forms/00_Introduction.md @@ -16,16 +16,16 @@ Creating a [Form](api:SilverStripe\Forms\Form) has the following signature. ```php - use SilverStripe\Forms\Form; - use SilverStripe\Forms\FieldList; - - $form = new Form( - $controller, // the Controller to render this form on - $name, // name of the method that returns this form on the controller - FieldList $fields, // list of FormField instances - FieldList $actions, // list of FormAction instances - $required // optional use of RequiredFields object - ); +use SilverStripe\Forms\Form; +use SilverStripe\Forms\FieldList; + +$form = new Form( + $controller, // the Controller to render this form on + $name, // name of the method that returns this form on the controller + FieldList $fields, // list of FormField instances + FieldList $actions, // list of FormAction instances + $required // optional use of RequiredFields object +); ``` In practice, this looks like: @@ -344,7 +344,6 @@ $validator = new SilverStripe\Forms\RequiredFields([ ]); $form = new Form($this, 'MyForm', $fields, $actions, $validator); - ``` ## API Documentation diff --git a/docs/en/02_Developer_Guides/03_Forms/01_Validation.md b/docs/en/02_Developer_Guides/03_Forms/01_Validation.md index 22bcdd855..b5d6aaa0a 100644 --- a/docs/en/02_Developer_Guides/03_Forms/01_Validation.md +++ b/docs/en/02_Developer_Guides/03_Forms/01_Validation.md @@ -174,9 +174,8 @@ class Page_Controller extends ContentController return $this->redirectBack(); } } - ``` - + ## Exempt validation actions In some cases you might need to disable validation for specific actions. E.g. actions which discard submitted diff --git a/docs/en/02_Developer_Guides/03_Forms/03_Form_Templates.md b/docs/en/02_Developer_Guides/03_Forms/03_Form_Templates.md index b314c5fc5..241189ede 100644 --- a/docs/en/02_Developer_Guides/03_Forms/03_Form_Templates.md +++ b/docs/en/02_Developer_Guides/03_Forms/03_Form_Templates.md @@ -8,12 +8,12 @@ can be rendered out using custom templates using `setTemplate`. ```php - $form = new Form(..); - $form->setTemplate('MyCustomFormTemplate'); +$form = new Form(..); +$form->setTemplate('MyCustomFormTemplate'); - // or, just a field - $field = new TextField(..); - $field->setTemplate('MyCustomTextField'); +// or, just a field +$field = new TextField(..); +$field->setTemplate('MyCustomTextField'); ``` Both `MyCustomTemplate.ss` and `MyCustomTextField.ss` should be located in **mysite/templates/forms/** or the same directory as the core. @@ -37,27 +37,27 @@ For [FormField](api:SilverStripe\Forms\FormField) instances, there are several o ```php - $field = new TextField(); +$field = new TextField(); - $field->setTemplate('CustomTextField'); - // Sets the template for the tag. i.e '' - - $field->setFieldHolderTemplate('CustomTextField_Holder'); - // Sets the template for the wrapper around the text field. i.e - // '
' - // - // The actual FormField is rendered into the holder via the `$Field` - // variable. - // - // setFieldHolder() is used in most `Form` instances and needs to output - // labels, error messages and the like. +$field->setTemplate('CustomTextField'); +// Sets the template for the tag. i.e '' - $field->setSmallFieldHolderTemplate('CustomTextField_Holder_Small'); - // Sets the template for the wrapper around the text field. - // - // The difference here is the small field holder template is used when the - // field is embedded within another field. For example, if the field is - // part of a `FieldGroup` or `CompositeField` alongside other fields. +$field->setFieldHolderTemplate('CustomTextField_Holder'); +// Sets the template for the wrapper around the text field. i.e +// '
' +// +// The actual FormField is rendered into the holder via the `$Field` +// variable. +// +// setFieldHolder() is used in most `Form` instances and needs to output +// labels, error messages and the like. + +$field->setSmallFieldHolderTemplate('CustomTextField_Holder_Small'); +// Sets the template for the wrapper around the text field. +// +// The difference here is the small field holder template is used when the +// field is embedded within another field. For example, if the field is +// part of a `FieldGroup` or `CompositeField` alongside other fields. ``` All templates are rendered within the scope of the [FormField](api:SilverStripe\Forms\FormField). To understand more about Scope within Templates as diff --git a/docs/en/02_Developer_Guides/03_Forms/04_Form_Security.md b/docs/en/02_Developer_Guides/03_Forms/04_Form_Security.md index c9db584f2..93c4c6cf9 100644 --- a/docs/en/02_Developer_Guides/03_Forms/04_Form_Security.md +++ b/docs/en/02_Developer_Guides/03_Forms/04_Form_Security.md @@ -22,18 +22,18 @@ The `SecurityToken` automatically added looks something like: ```php - use SilverStripe\Forms\Form; - - $form = new Form(..); - echo $form->getSecurityToken()->getValue(); +use SilverStripe\Forms\Form; - // 'c443076989a7f24cf6b35fe1360be8683a753e2c' +$form = new Form(..); +echo $form->getSecurityToken()->getValue(); + +// 'c443076989a7f24cf6b35fe1360be8683a753e2c' ``` This token value is passed through the rendered Form HTML as a [HiddenField](api:SilverStripe\Forms\HiddenField). -```html - +```html + ``` The token should be present whenever a operation has a side effect such as a `POST` operation. @@ -43,8 +43,8 @@ normally require a security token). ```php - $form = new Form(..); - $form->disableSecurityToken(); +$form = new Form(..); +$form->disableSecurityToken(); ```
@@ -60,13 +60,13 @@ application errors or edge cases. If you need to disable this setting follow the ```php - $form = new Form(..); +$form = new Form(..); - $form->setFormMethod('POST'); - $form->setStrictFormMethodCheck(false); +$form->setFormMethod('POST'); +$form->setStrictFormMethodCheck(false); - // or alternative short notation.. - $form->setFormMethod('POST', false); +// or alternative short notation.. +$form->setFormMethod('POST', false); ``` ## Spam and Bot Attacks diff --git a/docs/en/02_Developer_Guides/03_Forms/05_Form_Transformations.md b/docs/en/02_Developer_Guides/03_Forms/05_Form_Transformations.md index 877cba550..b7e830696 100644 --- a/docs/en/02_Developer_Guides/03_Forms/05_Form_Transformations.md +++ b/docs/en/02_Developer_Guides/03_Forms/05_Form_Transformations.md @@ -11,43 +11,43 @@ To make an entire [Form](api:SilverStripe\Forms\Form) read-only. ```php - use SilverStripe\Forms\Form; +use SilverStripe\Forms\Form; - $form = new Form(..); - $form->makeReadonly(); +$form = new Form(..); +$form->makeReadonly(); ``` To make all the fields within a [FieldList](api:SilverStripe\Forms\FieldList) read-only (i.e to make fields read-only but not buttons). ```php - use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\FieldList; - $fields = new FieldList(..); - $fields = $fields->makeReadonly(); +$fields = new FieldList(..); +$fields = $fields->makeReadonly(); ``` To make a [FormField](api:SilverStripe\Forms\FormField) read-only you need to know the name of the form field or call it direct on the object ```php - use SilverStripe\Forms\TextField; - use SilverStripe\Forms\FieldList; - - $field = new TextField(..); - $field = $field->performReadonlyTransformation(); +use SilverStripe\Forms\TextField; +use SilverStripe\Forms\FieldList; - $fields = new FieldList( - $field - ); +$field = new TextField(..); +$field = $field->performReadonlyTransformation(); - // Or, - $field = new TextField(..); - $field->setReadonly(true); +$fields = new FieldList( + $field +); - $fields = new FieldList( - $field - ); +// Or, +$field = new TextField(..); +$field->setReadonly(true); + +$fields = new FieldList( + $field +); ``` ## Disabled FormFields @@ -56,11 +56,10 @@ Disabling [FormField](api:SilverStripe\Forms\FormField) instances, sets the `dis a normal form, but set the `disabled` attribute on the `input` tag. ```php - $field = new TextField(..); - $field->setDisabled(true); +$field = new TextField(..); +$field->setDisabled(true); - echo $field->forTemplate(); +echo $field->forTemplate(); - // returns '' - -``` \ No newline at end of file +// returns '' +``` diff --git a/docs/en/02_Developer_Guides/03_Forms/06_Tabbed_Forms.md b/docs/en/02_Developer_Guides/03_Forms/06_Tabbed_Forms.md index 33961f275..b006b214c 100644 --- a/docs/en/02_Developer_Guides/03_Forms/06_Tabbed_Forms.md +++ b/docs/en/02_Developer_Guides/03_Forms/06_Tabbed_Forms.md @@ -23,42 +23,41 @@ display up to two levels of tabs in the interface. ```php - $fields->addFieldToTab('Root.Main', new TextField(..)); +$fields->addFieldToTab('Root.Main', new TextField(..)); ``` ## Removing a field from a tab ```php - $fields->removeFieldFromTab('Root.Main', 'Content'); +$fields->removeFieldFromTab('Root.Main', 'Content'); ``` ## Creating a new tab ```php - $fields->addFieldToTab('Root.MyNewTab', new TextField(..)); +$fields->addFieldToTab('Root.MyNewTab', new TextField(..)); ``` ## Moving a field between tabs ```php - $content = $fields->dataFieldByName('Content'); +$content = $fields->dataFieldByName('Content'); - $fields->removeFieldFromTab('Root.Main', 'Content'); - $fields->addFieldToTab('Root.MyContent', $content); +$fields->removeFieldFromTab('Root.Main', 'Content'); +$fields->addFieldToTab('Root.MyContent', $content); ``` ## Add multiple fields at once ```php - $fields->addFieldsToTab('Root.Content', [ - TextField::create('Name'), - TextField::create('Email') - ]); - +$fields->addFieldsToTab('Root.Content', [ + TextField::create('Name'), + TextField::create('Email') +]); ``` ## API Documentation diff --git a/docs/en/02_Developer_Guides/03_Forms/Field_types/02_DateField.md b/docs/en/02_Developer_Guides/03_Forms/Field_types/02_DateField.md index 6c059338c..f07a9202f 100644 --- a/docs/en/02_Developer_Guides/03_Forms/Field_types/02_DateField.md +++ b/docs/en/02_Developer_Guides/03_Forms/Field_types/02_DateField.md @@ -16,29 +16,27 @@ The following example will add a simple DateField to your Page, allowing you to ```php - use SilverStripe\Forms\DateField; - use SilverStripe\CMS\Model\SiteTree; +use SilverStripe\Forms\DateField; +use SilverStripe\CMS\Model\SiteTree; - class Page extends SiteTree +class Page extends SiteTree +{ + private static $db = [ + 'MyDate' => 'Date', + ]; + + public function getCMSFields() { - - private static $db = [ - 'MyDate' => 'Date', - ]; - - public function getCMSFields() - { - $fields = parent::getCMSFields(); - - $fields->addFieldToTab( - 'Root.Main', - DateField::create('MyDate', 'Enter a date') - ); - - return $fields; - } - } - + $fields = parent::getCMSFields(); + + $fields->addFieldToTab( + 'Root.Main', + DateField::create('MyDate', 'Enter a date') + ); + + return $fields; + } +} ``` ## Custom Date Format @@ -48,10 +46,10 @@ This is only necessary if you want to opt-out of the built-in browser localisati ```php - // will display a date in the following format: 31/06/2012 - DateField::create('MyDate') - ->setHTML5(false) - ->setDateFormat('dd/MM/yyyy'); +// will display a date in the following format: 31/06/2012 +DateField::create('MyDate') + ->setHTML5(false) + ->setDateFormat('dd/MM/yyyy'); ```
@@ -66,9 +64,9 @@ Sets the minimum and maximum allowed date values using the `min` and `max` confi ```php - DateField::create('MyDate') - ->setMinDate('-7 days') - ->setMaxDate('2012-12-31') +DateField::create('MyDate') + ->setMinDate('-7 days') + ->setMaxDate('2012-12-31') ``` ## Formatting Hints @@ -79,17 +77,17 @@ field description as an example. ```php - $dateField = DateField::create('MyDate'); +$dateField = DateField::create('MyDate'); - // Show long format as text below the field - $dateField->setDescription(_t( - 'FormField.Example', - 'e.g. {format}', - [ 'format' => $dateField->getDateFormat() ] - )); +// Show long format as text below the field +$dateField->setDescription(_t( + 'FormField.Example', + 'e.g. {format}', + [ 'format' => $dateField->getDateFormat() ] +)); - // Alternatively, set short format as a placeholder in the field - $dateField->setAttribute('placeholder', $dateField->getDateFormat()); +// Alternatively, set short format as a placeholder in the field +$dateField->setAttribute('placeholder', $dateField->getDateFormat()); ```
diff --git a/docs/en/02_Developer_Guides/03_Forms/Field_types/03_HTMLEditorField.md b/docs/en/02_Developer_Guides/03_Forms/Field_types/03_HTMLEditorField.md index 31cbf61ba..f40dc182e 100644 --- a/docs/en/02_Developer_Guides/03_Forms/Field_types/03_HTMLEditorField.md +++ b/docs/en/02_Developer_Guides/03_Forms/Field_types/03_HTMLEditorField.md @@ -17,25 +17,24 @@ functionality. It is usually added through the [DataObject::getCMSFields()](api: ```php - use SilverStripe\Forms\FieldList; - use SilverStripe\Forms\HTMLEditor\HTMLEditorField; - use SilverStripe\ORM\DataObject; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\HTMLEditor\HTMLEditorField; +use SilverStripe\ORM\DataObject; - class MyObject extends DataObject +class MyObject extends DataObject +{ + + private static $db = [ + 'Content' => 'HTMLText' + ]; + + public function getCMSFields() { - - private static $db = [ - 'Content' => 'HTMLText' - ]; - - public function getCMSFields() - { - return new FieldList( - new HTMLEditorField('Content') - ); - } + return new FieldList( + new HTMLEditorField('Content') + ); } - +} ``` ### Specify which configuration to use @@ -51,25 +50,25 @@ This is particularly useful if you need different configurations for multiple [H ```php - use SilverStripe\Forms\FieldList; - use SilverStripe\Forms\HTMLEditor\HTMLEditorField; - use SilverStripe\ORM\DataObject; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\HTMLEditor\HTMLEditorField; +use SilverStripe\ORM\DataObject; - class MyObject extends DataObject +class MyObject extends DataObject +{ + private static $db = [ + 'Content' => 'HTMLText', + 'OtherContent' => 'HTMLText' + ]; + + public function getCMSFields() { - private static $db = [ - 'Content' => 'HTMLText', - 'OtherContent' => 'HTMLText' - ]; - - public function getCMSFields() - { - return new FieldList([ - new HTMLEditorField('Content'), - new HTMLEditorField('OtherContent', 'Other content', $this->OtherContent, 'myConfig') - ]); - } + return new FieldList([ + new HTMLEditorField('Content'), + new HTMLEditorField('OtherContent', 'Other content', $this->OtherContent, 'myConfig') + ]); } +} ``` @@ -103,9 +102,9 @@ transparently generate the relevant underlying TinyMCE code. **mysite/_config.php** ```php - use SilverStripe\Forms\HTMLEditor\HtmlEditorConfig; +use SilverStripe\Forms\HTMLEditor\HtmlEditorConfig; - HtmlEditorConfig::get('cms')->enablePlugins('media'); +HtmlEditorConfig::get('cms')->enablePlugins('media'); ```
@@ -120,7 +119,7 @@ configuration. Here is an example of adding a `ssmacron` button after the `charm **mysite/_config.php** ```php - HtmlEditorConfig::get('cms')->insertButtonsAfter('charmap', 'ssmacron'); +HtmlEditorConfig::get('cms')->insertButtonsAfter('charmap', 'ssmacron'); ``` Buttons can also be removed: @@ -128,7 +127,7 @@ Buttons can also be removed: **mysite/_config.php** ```php - HtmlEditorConfig::get('cms')->removeButtons('tablecontrols', 'blockquote', 'hr'); +HtmlEditorConfig::get('cms')->removeButtons('tablecontrols', 'blockquote', 'hr'); ```
@@ -149,18 +148,18 @@ from the HTML source by the editor. **mysite/_config.php** ```php - // Add start and type attributes for
    , add and with all attributes. - HtmlEditorConfig::get('cms')->setOption( - 'extended_valid_elements', - 'img[class|src|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|usemap],' . - 'iframe[src|name|width|height|title|align|allowfullscreen|frameborder|marginwidth|marginheight|scrolling],' . - 'object[classid|codebase|width|height|data|type],' . - 'embed[src|type|pluginspage|width|height|autoplay],' . - 'param[name|value],' . - 'map[class|name|id],' . - 'area[shape|coords|href|target|alt],' . - 'ol[start|type]' - ); +// Add start and type attributes for
      , add and with all attributes. +HtmlEditorConfig::get('cms')->setOption( + 'extended_valid_elements', + 'img[class|src|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|usemap],' . + 'iframe[src|name|width|height|title|align|allowfullscreen|frameborder|marginwidth|marginheight|scrolling],' . + 'object[classid|codebase|width|height|data|type],' . + 'embed[src|type|pluginspage|width|height|autoplay],' . + 'param[name|value],' . + 'map[class|name|id],' . + 'area[shape|coords|href|target|alt],' . + 'ol[start|type]' +); ```
      @@ -176,8 +175,7 @@ You can enable them through [HtmlEditorConfig::enablePlugins()](api:SilverStripe **mysite/_config.php** ```php - HtmlEditorConfig::get('cms')->enablePlugins(['myplugin' => '../../../mysite/javascript/myplugin/editor_plugin.js']); - +HtmlEditorConfig::get('cms')->enablePlugins(['myplugin' => '../../../mysite/javascript/myplugin/editor_plugin.js']); ``` You can learn how to [create a plugin](http://www.tinymce.com/wiki.php/Creating_a_plugin) from the TinyMCE documentation. @@ -231,7 +229,7 @@ In case you want to adhere to HTML4 instead, use the following configuration: ```php - HtmlEditorConfig::get('cms')->setOption('element_format', 'html'); +HtmlEditorConfig::get('cms')->setOption('element_format', 'html'); ``` By default, TinyMCE and SilverStripe will generate valid HTML5 markup, but it will strip out HTML5 tags like @@ -256,25 +254,23 @@ Example: Remove field for "image captions" ```php - use SilverStripe\Core\Extension; +use SilverStripe\Core\Extension; - // File: mysite/code/MyToolbarExtension.php - class MyToolbarExtension extends Extension +// File: mysite/code/MyToolbarExtension.php +class MyToolbarExtension extends Extension +{ + public function updateFieldsForImage(&$fields, $url, $file) { - public function updateFieldsForImage(&$fields, $url, $file) - { - $fields->removeByName('CaptionText'); - } + $fields->removeByName('CaptionText'); } +} ``` - - ```php - // File: mysite/_config.php - use SilverStripe\Admin\ModalController; - - ModalController::add_extension('MyToolbarExtension'); +// File: mysite/_config.php +use SilverStripe\Admin\ModalController; + +ModalController::add_extension('MyToolbarExtension'); ``` Adding functionality is a bit more advanced, you'll most likely @@ -302,28 +298,27 @@ of the CMS you have to take care of instantiate yourself: ```php - use SilverStripe\Admin\ModalController; - use SilverStripe\Control\Controller; +use SilverStripe\Admin\ModalController; +use SilverStripe\Control\Controller; - // File: mysite/code/MyController.php - class MyObjectController extends Controller +// File: mysite/code/MyController.php +class MyObjectController extends Controller +{ + public function Modals() { - public function Modals() - { - return ModalController::create($this, "Modals"); - } + return ModalController::create($this, "Modals"); } +} ``` Note: The dialogs rely on CMS-access, e.g. for uploading and browsing files, so this is considered advanced usage of the field. - ```php - // File: mysite/_config.php - HtmlEditorConfig::get('cms')->disablePlugins('ssbuttons'); - HtmlEditorConfig::get('cms')->removeButtons('sslink', 'ssmedia'); - HtmlEditorConfig::get('cms')->addButtonsToLine(2, 'link', 'media'); +// File: mysite/_config.php +HtmlEditorConfig::get('cms')->disablePlugins('ssbuttons'); +HtmlEditorConfig::get('cms')->removeButtons('sslink', 'ssmedia'); +HtmlEditorConfig::get('cms')->addButtonsToLine(2, 'link', 'media'); ``` ### Developing a wrapper to use a different WYSIWYG editors with HTMLEditorField @@ -334,4 +329,4 @@ mainly around selecting and inserting content into the editor view. Have a look in `HtmlEditorField.js` and the `ss.editorWrapper` object to get you started on your own editor wrapper. Note that the [HtmlEditorConfig](api:SilverStripe\Forms\HTMLEditor\HtmlEditorConfig) is currently hardwired to support TinyMCE, so its up to you to either convert existing configuration as applicable, -or start your own configuration. \ No newline at end of file +or start your own configuration. diff --git a/docs/en/02_Developer_Guides/03_Forms/Field_types/04_GridField.md b/docs/en/02_Developer_Guides/03_Forms/Field_types/04_GridField.md index 114155717..5202e1de9 100644 --- a/docs/en/02_Developer_Guides/03_Forms/Field_types/04_GridField.md +++ b/docs/en/02_Developer_Guides/03_Forms/Field_types/04_GridField.md @@ -8,9 +8,9 @@ tabular data in a format that is easy to view and modify. It can be thought of a ```php - use SilverStripe\Forms\GridField\GridField; +use SilverStripe\Forms\GridField\GridField; - $field = new GridField($name, $title, $list); +$field = new GridField($name, $title, $list); ```
      @@ -31,23 +31,23 @@ actions such as deleting records. ```php - use SilverStripe\Forms\GridField\GridField; - use SilverStripe\CMS\Model\SiteTree; +use SilverStripe\Forms\GridField\GridField; +use SilverStripe\CMS\Model\SiteTree; - class Page extends SiteTree +class Page extends SiteTree +{ + + public function getCMSFields() { - - public function getCMSFields() - { - $fields = parent::getCMSFields(); + $fields = parent::getCMSFields(); - $fields->addFieldToTab('Root.Pages', - new GridField('Pages', 'All pages', SiteTree::get()) - ); + $fields->addFieldToTab('Root.Pages', + new GridField('Pages', 'All pages', SiteTree::get()) + ); - return $fields; - } + return $fields; } +} ``` This will display a bare bones `GridField` instance under `Pages` tab in the CMS. As we have not specified the @@ -67,88 +67,91 @@ the `getConfig()` method on `GridField`. ```php - use SilverStripe\Forms\GridField\GridField; - use SilverStripe\CMS\Model\SiteTree; +use SilverStripe\Forms\GridField\GridField; +use SilverStripe\CMS\Model\SiteTree; - class Page extends SiteTree +class Page extends SiteTree +{ + + public function getCMSFields() { + $fields = parent::getCMSFields(); + + $fields->addFieldToTab('Root.Pages', + $grid = new GridField('Pages', 'All pages', SiteTree::get()) + ); + + // GridField configuration + $config = $grid->getConfig(); + + // + // Modification of existing components can be done by fetching that component. + // Consult the API documentation for each component to determine the configuration + // you can do. + // + $dataColumns = $config->getComponentByType('GridFieldDataColumns'); - public function getCMSFields() - { - $fields = parent::getCMSFields(); + $dataColumns->setDisplayFields([ + 'Title' => 'Title', + 'Link'=> 'URL', + 'LastEdited' => 'Changed' + ]); - $fields->addFieldToTab('Root.Pages', - $grid = new GridField('Pages', 'All pages', SiteTree::get()) - ); - - // GridField configuration - $config = $grid->getConfig(); - - // - // Modification of existing components can be done by fetching that component. - // Consult the API documentation for each component to determine the configuration - // you can do. - // - $dataColumns = $config->getComponentByType('GridFieldDataColumns'); - - $dataColumns->setDisplayFields([ - 'Title' => 'Title', - 'Link'=> 'URL', - 'LastEdited' => 'Changed' - ]); - - return $fields; - } + return $fields; } +} ``` With the `GridFieldConfig` instance, we can modify the behavior of the `GridField`. ```php - use SilverStripe\Forms\GridField\GridFieldConfig; - use SilverStripe\Forms\GridField\GridFieldDataColumns; +use SilverStripe\Forms\GridField\GridFieldConfig; +use SilverStripe\Forms\GridField\GridFieldDataColumns; - // `GridFieldConfig::create()` will create an empty configuration (no components). - $config = GridFieldConfig::create(); +// `GridFieldConfig::create()` will create an empty configuration (no components). +$config = GridFieldConfig::create(); - // add a component - $config->addComponent(new GridFieldDataColumns()); +// add a component +$config->addComponent(new GridFieldDataColumns()); - // Update the GridField with our custom configuration - $gridField->setConfig($config); +// Update the GridField with our custom configuration +$gridField->setConfig($config); ``` `GridFieldConfig` provides a number of methods to make setting the configuration easier. We can insert a component before another component by passing the second parameter. ```php - use SilverStripe\Forms\GridField\GridFieldFilterHeader; +use SilverStripe\Forms\GridField\GridFieldFilterHeader; +use SilverStripe\Forms\GridField\GridFieldDataColumns; - $config->addComponent(new GridFieldFilterHeader(), 'GridFieldDataColumns'); +$config->addComponent(new GridFieldFilterHeader(), GridFieldDataColumns::class); ``` We can add multiple components in one call. ```php - $config->addComponents( - new GridFieldDataColumns(), - new GridFieldToolbarHeader() - ); +$config->addComponents( + new GridFieldDataColumns(), + new GridFieldToolbarHeader() +); ``` Or, remove a component. ```php - $config->removeComponentsByType('GridFieldDeleteAction'); +use SilverStripe\Forms\GridField\GridFieldDeleteAction; +$config->removeComponentsByType(GridFieldDeleteAction::class); ``` Fetch a component to modify it later on. ```php - $component = $config->getComponentByType('GridFieldFilterHeader') +use SilverStripe\Forms\GridField\GridFieldFilterHeader; +$component = $config->getComponentByType(GridFieldFilterHeader::class) ``` Here is a list of components for use bundled with the core framework. Many more components are provided by third-party @@ -177,19 +180,19 @@ A simple read-only and paginated view of records with sortable and searchable he ```php - use SilverStripe\Forms\GridField\GridFieldConfig_Base; +use SilverStripe\Forms\GridField\GridFieldConfig_Base; - $config = GridFieldConfig_Base::create(); +$config = GridFieldConfig_Base::create(); - $gridField->setConfig($config); +$gridField->setConfig($config); - // Is the same as adding the following components.. - // .. new GridFieldToolbarHeader() - // .. new GridFieldSortableHeader() - // .. new GridFieldFilterHeader() - // .. new GridFieldDataColumns() - // .. new GridFieldPageCount('toolbar-header-right') - // .. new GridFieldPaginator($itemsPerPage) +// Is the same as adding the following components.. +// .. new GridFieldToolbarHeader() +// .. new GridFieldSortableHeader() +// .. new GridFieldFilterHeader() +// .. new GridFieldDataColumns() +// .. new GridFieldPageCount('toolbar-header-right') +// .. new GridFieldPaginator($itemsPerPage) ``` ### GridFieldConfig_RecordViewer @@ -209,15 +212,15 @@ this record. ```php - use SilverStripe\Forms\GridField\GridFieldConfig_RecordViewer; +use SilverStripe\Forms\GridField\GridFieldConfig_RecordViewer; - $config = GridFieldConfig_RecordViewer::create(); - - $gridField->setConfig($config); +$config = GridFieldConfig_RecordViewer::create(); - // Same as GridFieldConfig_Base with the addition of - // .. new GridFieldViewButton(), - // .. new GridFieldDetailForm() +$gridField->setConfig($config); + +// Same as GridFieldConfig_Base with the addition of +// .. new GridFieldViewButton(), +// .. new GridFieldDetailForm() ``` ### GridFieldConfig_RecordEditor @@ -236,24 +239,25 @@ Permission control for editing and deleting the record uses the `canEdit()` and ```php - $config = GridFieldConfig_RecordEditor::create(); - - $gridField->setConfig($config); +$config = GridFieldConfig_RecordEditor::create(); - // Same as GridFieldConfig_RecordViewer with the addition of - // .. new GridFieldAddNewButton(), - // .. new GridFieldEditButton(), - // .. new GridFieldDeleteAction() +$gridField->setConfig($config); + +// Same as GridFieldConfig_RecordViewer with the addition of +// .. new GridFieldAddNewButton(), +// .. new GridFieldEditButton(), +// .. new GridFieldDeleteAction() ``` ### GridFieldConfig_RelationEditor Similar to `GridFieldConfig_RecordEditor`, but adds features to work on a record's has-many or many-many relationships. As such, it expects the list used with the `GridField` to be a instance of `RelationList`. -```php - $config = GridFieldConfig_RelationEditor::create(); - $gridField->setConfig($config); +```php +$config = GridFieldConfig_RelationEditor::create(); + +$gridField->setConfig($config); ``` This configuration adds the ability to searched for existing records and add a relationship @@ -270,10 +274,12 @@ The `GridFieldDetailForm` component drives the record viewing and editing form. ```php - $form = $gridField->getConfig()->getComponentByType('GridFieldDetailForm'); - $form->setFields(new FieldList( - new TextField('Title') - )); +use SilverStripe\Forms\GridField\GridFieldDetailForm; + +$form = $gridField->getConfig()->getComponentByType(GridFieldDetailForm::class); +$form->setFields(new FieldList( + new TextField('Title') +)); ``` ### many_many_extraFields @@ -289,62 +295,61 @@ The namespace notation is `ManyMany[]`, so for example `Ma ```php - use SilverStripe\Forms\TextField; - use SilverStripe\Forms\GridField\GridField; - use SilverStripe\Forms\GridField\GridFieldConfig_RelationEditor; - use SilverStripe\ORM\DataObject; +use SilverStripe\Forms\TextField; +use SilverStripe\Forms\GridField\GridField; +use SilverStripe\Forms\GridField\GridFieldConfig_RelationEditor; +use SilverStripe\ORM\DataObject; - class Team extends DataObject - { - - private static $db = [ - 'Name' => 'Text' - ]; - - public static $many_many = [ - 'Players' => 'Player' - ]; - } - class Player extends DataObject - { +class Team extends DataObject +{ - private static $db = [ - 'Name' => 'Text' - ]; - - public static $many_many = [ - 'Teams' => 'Team' - ]; - - public static $many_many_extraFields = [ - 'Teams' => [ - 'Position' => 'Text' - ] - ]; + private static $db = [ + 'Name' => 'Text' + ]; - public function getCMSFields() - { - $fields = parent::getCMSFields(); + public static $many_many = [ + 'Players' => 'Player' + ]; +} +class Player extends DataObject +{ - if($this->ID) { - $teamFields = singleton('Team')->getCMSFields(); - $teamFields->addFieldToTab( - 'Root.Main', - // The "ManyMany[]" convention - new TextField('ManyMany[Position]', 'Current Position') - ); + private static $db = [ + 'Name' => 'Text' + ]; + + public static $many_many = [ + 'Teams' => 'Team' + ]; + + public static $many_many_extraFields = [ + 'Teams' => [ + 'Position' => 'Text' + ] + ]; - $config = GridFieldConfig_RelationEditor::create(); - $config->getComponentByType('GridFieldDetailForm')->setFields($teamFields); + public function getCMSFields() + { + $fields = parent::getCMSFields(); - $gridField = new GridField('Teams', 'Teams', $this->Teams(), $config); - $fields->findOrMakeTab('Root.Teams')->replaceField('Teams', $gridField); - } + if($this->ID) { + $teamFields = singleton('Team')->getCMSFields(); + $teamFields->addFieldToTab( + 'Root.Main', + // The "ManyMany[]" convention + new TextField('ManyMany[Position]', 'Current Position') + ); - return $fields; + $config = GridFieldConfig_RelationEditor::create(); + $config->getComponentByType('GridFieldDetailForm')->setFields($teamFields); + + $gridField = new GridField('Teams', 'Teams', $this->Teams(), $config); + $fields->findOrMakeTab('Root.Teams')->replaceField('Teams', $gridField); } - } + return $fields; + } +} ``` ## Flexible Area Assignment through Fragments @@ -364,13 +369,12 @@ These built-ins can be used by passing the fragment names into the constructor o [GridFieldConfig](api:SilverStripe\Forms\GridField\GridFieldConfig) classes will already have rows added to them. The following example will add a print button at the bottom right of the table. - ```php - use SilverStripe\Forms\GridField\GridFieldButtonRow; - use SilverStripe\Forms\GridField\GridFieldPrintButton; +use SilverStripe\Forms\GridField\GridFieldButtonRow; +use SilverStripe\Forms\GridField\GridFieldPrintButton; - $config->addComponent(new GridFieldButtonRow('after')); - $config->addComponent(new GridFieldPrintButton('buttons-after-right')); +$config->addComponent(new GridFieldButtonRow('after')); +$config->addComponent(new GridFieldPrintButton('buttons-after-right')); ``` ### Creating your own Fragments @@ -381,18 +385,18 @@ create an area rendered before the table wrapped in a simple `
      `. ```php - use SilverStripe\Forms\GridField\GridField_HTMLProvider; +use SilverStripe\Forms\GridField\GridField_HTMLProvider; - class MyAreaComponent implements GridField_HTMLProvider +class MyAreaComponent implements GridField_HTMLProvider +{ + + public function getHTMLFragments( $gridField) { - - public function getHTMLFragments( $gridField) - { - return [ - 'before' => '
      $DefineFragment(my-area)
      ' - ]; - } + return [ + 'before' => '
      $DefineFragment(my-area)
      ' + ]; } +} ``` @@ -406,18 +410,18 @@ Now you can add other components into this area by returning them as an array fr ```php - use SilverStripe\Forms\GridField\GridField_HTMLProvider; +use SilverStripe\Forms\GridField\GridField_HTMLProvider; - class MyShareLinkComponent implements GridField_HTMLProvider - { - - public function getHTMLFragments( $gridField) - { - return [ - 'my-area' => '...' - ]; - } +class MyShareLinkComponent implements GridField_HTMLProvider +{ + + public function getHTMLFragments( $gridField) + { + return [ + 'my-area' => '...' + ]; } +} ``` @@ -425,7 +429,7 @@ Your new area can also be used by existing components, e.g. the [GridFieldPrintB ```php - new GridFieldPrintButton('my-component-area'); +new GridFieldPrintButton('my-component-area'); ``` ## Creating a Custom GridFieldComponent diff --git a/docs/en/02_Developer_Guides/03_Forms/How_Tos/01_Encapsulate_Forms.md b/docs/en/02_Developer_Guides/03_Forms/How_Tos/01_Encapsulate_Forms.md index 7bbe07fb0..d2eae29b7 100644 --- a/docs/en/02_Developer_Guides/03_Forms/How_Tos/01_Encapsulate_Forms.md +++ b/docs/en/02_Developer_Guides/03_Forms/How_Tos/01_Encapsulate_Forms.md @@ -6,71 +6,69 @@ Form definitions can often get long, complex and often end up cluttering up a `C to reuse the `Form` across multiple `Controller` classes rather than just one. A nice way to encapsulate the logic and code for a `Form` is to create it as a subclass to `Form`. Let's look at a example of a `Form` which is on our `Controller` but would be better written as a subclass. - + **mysite/code/Page.php** ```php - use SilverStripe\Forms\FieldList; - use SilverStripe\Forms\RequiredFields; - use SilverStripe\Forms\Form; - use SilverStripe\Forms\HeaderField; - use SilverStripe\Forms\OptionsetField; - use SilverStripe\Forms\CompositeField; - use SilverStripe\Forms\CheckboxSetField; - use SilverStripe\Forms\NumericField; - use SilverStripe\Forms\FormAction; - use SilverStripe\CMS\Controllers\ContentController; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\RequiredFields; +use SilverStripe\Forms\Form; +use SilverStripe\Forms\HeaderField; +use SilverStripe\Forms\OptionsetField; +use SilverStripe\Forms\CompositeField; +use SilverStripe\Forms\CheckboxSetField; +use SilverStripe\Forms\NumericField; +use SilverStripe\Forms\FormAction; +use SilverStripe\CMS\Controllers\ContentController; - class PageController extends ContentController +class PageController extends ContentController +{ + + public function SearchForm() { - - public function SearchForm() - { - $fields = new FieldList( - HeaderField::create('Header', 'Step 1. Basics'), - OptionsetField::create('Type', '', [ - 'foo' => 'Search Foo', - 'bar' => 'Search Bar', - 'baz' => 'Search Baz' + $fields = new FieldList( + HeaderField::create('Header', 'Step 1. Basics'), + OptionsetField::create('Type', '', [ + 'foo' => 'Search Foo', + 'bar' => 'Search Bar', + 'baz' => 'Search Baz' + ]), + + CompositeField::create( + HeaderField::create('Header2', 'Step 2. Advanced '), + CheckboxSetField::create('Foo', 'Select Option', [ + 'qux' => 'Search Qux' ]), - CompositeField::create( - HeaderField::create('Header2', 'Step 2. Advanced '), - CheckboxSetField::create('Foo', 'Select Option', [ - 'qux' => 'Search Qux' - ]), + CheckboxSetField::create('Category', 'Category', [ + 'Foo' => 'Foo', + 'Bar' => 'Bar' + ]), - CheckboxSetField::create('Category', 'Category', [ - 'Foo' => 'Foo', - 'Bar' => 'Bar' - ]), - - NumericField::create('Minimum', 'Minimum'), - NumericField::create('Maximum', 'Maximum') - ) - ); - - $actions = new FieldList( - FormAction::create('doSearchForm', 'Search') - ); - - $required = new RequiredFields([ - 'Type' - ]); - - $form = new Form($this, 'SearchForm', $fields, $actions, $required); - $form->setFormMethod('GET'); - - $form->addExtraClass('no-action-styles'); - $form->disableSecurityToken(); - $form->loadDataFrom($_REQUEST); + NumericField::create('Minimum', 'Minimum'), + NumericField::create('Maximum', 'Maximum') + ) + ); - return $form; - } + $actions = new FieldList( + FormAction::create('doSearchForm', 'Search') + ); + + $required = new RequiredFields([ + 'Type' + ]); - .. + $form = new Form($this, 'SearchForm', $fields, $actions, $required); + $form->setFormMethod('GET'); + + $form->addExtraClass('no-action-styles'); + $form->disableSecurityToken(); + $form->loadDataFrom($_REQUEST); + + return $form; } +} ``` @@ -79,72 +77,71 @@ should be. Good practice would be to move this to a subclass and create a new in **mysite/code/forms/SearchForm.php** - ```php - use SilverStripe\Forms\FieldList; - use SilverStripe\Forms\RequiredFields; - use SilverStripe\Forms\HeaderField; - use SilverStripe\Forms\OptionsetField; - use SilverStripe\Forms\CompositeField; - use SilverStripe\Forms\CheckboxSetField; - use SilverStripe\Forms\NumericField; - use SilverStripe\Forms\FormAction; - use SilverStripe\Forms\Form; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\RequiredFields; +use SilverStripe\Forms\HeaderField; +use SilverStripe\Forms\OptionsetField; +use SilverStripe\Forms\CompositeField; +use SilverStripe\Forms\CheckboxSetField; +use SilverStripe\Forms\NumericField; +use SilverStripe\Forms\FormAction; +use SilverStripe\Forms\Form; - class SearchForm extends Form +class SearchForm extends Form +{ + + /** + * Our constructor only requires the controller and the name of the form + * method. We'll create the fields and actions in here. + * + */ + public function __construct($controller, $name) { + $fields = new FieldList( + HeaderField::create('Header', 'Step 1. Basics'), + OptionsetField::create('Type', '', [ + 'foo' => 'Search Foo', + 'bar' => 'Search Bar', + 'baz' => 'Search Baz' + ]), - /** - * Our constructor only requires the controller and the name of the form - * method. We'll create the fields and actions in here. - * - */ - public function __construct($controller, $name) - { - $fields = new FieldList( - HeaderField::create('Header', 'Step 1. Basics'), - OptionsetField::create('Type', '', [ - 'foo' => 'Search Foo', - 'bar' => 'Search Bar', - 'baz' => 'Search Baz' + CompositeField::create( + HeaderField::create('Header2', 'Step 2. Advanced '), + CheckboxSetField::create('Foo', 'Select Option', [ + 'qux' => 'Search Qux' ]), - CompositeField::create( - HeaderField::create('Header2', 'Step 2. Advanced '), - CheckboxSetField::create('Foo', 'Select Option', [ - 'qux' => 'Search Qux' - ]), + CheckboxSetField::create('Category', 'Category', [ + 'Foo' => 'Foo', + 'Bar' => 'Bar' + ]), - CheckboxSetField::create('Category', 'Category', [ - 'Foo' => 'Foo', - 'Bar' => 'Bar' - ]), - - NumericField::create('Minimum', 'Minimum'), - NumericField::create('Maximum', 'Maximum') - ) - ); - - $actions = new FieldList( - FormAction::create('doSearchForm', 'Search') - ); - - $required = new RequiredFields([ - 'Type' - ]); - - // now we create the actual form with our fields and actions defined - // within this class - parent::__construct($controller, $name, $fields, $actions, $required); - - // any modifications we need to make to the form. - $this->setFormMethod('GET'); + NumericField::create('Minimum', 'Minimum'), + NumericField::create('Maximum', 'Maximum') + ) + ); - $this->addExtraClass('no-action-styles'); - $this->disableSecurityToken(); - $this->loadDataFrom($_REQUEST); - } + $actions = new FieldList( + FormAction::create('doSearchForm', 'Search') + ); + + $required = new RequiredFields([ + 'Type' + ]); + + // now we create the actual form with our fields and actions defined + // within this class + parent::__construct($controller, $name, $fields, $actions, $required); + + // any modifications we need to make to the form. + $this->setFormMethod('GET'); + + $this->addExtraClass('no-action-styles'); + $this->disableSecurityToken(); + $this->loadDataFrom($_REQUEST); } +} ``` @@ -154,22 +151,21 @@ Our controller will now just have to create a new instance of this form object. ```php - use SearchForm; - use SilverStripe\CMS\Controllers\ContentController; +use SearchForm; +use SilverStripe\CMS\Controllers\ContentController; - class PageController extends ContentController +class PageController extends ContentController +{ + + private static $allowed_actions = [ + 'SearchForm', + ]; + + public function SearchForm() { - - private static $allowed_actions = [ - 'SearchForm', - ]; - - public function SearchForm() - { - return new SearchForm($this, 'SearchForm'); - } + return new SearchForm($this, 'SearchForm'); } - +} ``` Form actions can also be defined within your `Form` subclass to keep the entire form logic encapsulated. diff --git a/docs/en/02_Developer_Guides/03_Forms/How_Tos/02_Lightweight_Form.md b/docs/en/02_Developer_Guides/03_Forms/How_Tos/02_Lightweight_Form.md index 4a1a69138..a7e6998b6 100644 --- a/docs/en/02_Developer_Guides/03_Forms/How_Tos/02_Lightweight_Form.md +++ b/docs/en/02_Developer_Guides/03_Forms/How_Tos/02_Lightweight_Form.md @@ -13,38 +13,36 @@ totally custom template to meet our needs. To do this, we'll provide the class w ```php - - public function SearchForm() - { - $fields = new FieldList( - TextField::create('q') - ); +public function SearchForm() +{ + $fields = new FieldList( + TextField::create('q') + ); - $actions = new FieldList( - FormAction::create('doSearch', 'Search') - ); + $actions = new FieldList( + FormAction::create('doSearch', 'Search') + ); - $form = new Form($this, 'SearchForm', $fields, $actions); - $form->setTemplate('SearchForm'); + $form = new Form($this, 'SearchForm', $fields, $actions); + $form->setTemplate('SearchForm'); - return $form; - } + return $form; +} ``` **mysite/templates/Includes/SearchForm.ss** ```ss - -
      -
      - $Fields.dataFieldByName(q) -
      - -
      - <% loop $Actions %>$Field<% end_loop %> -
      -
      +
      +
      + $Fields.dataFieldByName(q) +
      + +
      + <% loop $Actions %>$Field<% end_loop %> +
      +
      ``` `SearchForm.ss` will be executed within the scope of the `Form` object so has access to any of the methods and diff --git a/docs/en/02_Developer_Guides/03_Forms/How_Tos/04_Create_a_GridField_ActionProvider.md b/docs/en/02_Developer_Guides/03_Forms/How_Tos/04_Create_a_GridField_ActionProvider.md index 48ae5504e..02f04124c 100644 --- a/docs/en/02_Developer_Guides/03_Forms/How_Tos/04_Create_a_GridField_ActionProvider.md +++ b/docs/en/02_Developer_Guides/03_Forms/How_Tos/04_Create_a_GridField_ActionProvider.md @@ -19,72 +19,71 @@ below: ```php - use SilverStripe\Forms\GridField\GridField_ColumnProvider; - use SilverStripe\Forms\GridField\GridField_ActionProvider; - use SilverStripe\Forms\GridField\GridField_FormAction; - use SilverStripe\Control\Controller; +use SilverStripe\Forms\GridField\GridField_ColumnProvider; +use SilverStripe\Forms\GridField\GridField_ActionProvider; +use SilverStripe\Forms\GridField\GridField_FormAction; +use SilverStripe\Control\Controller; - class GridFieldCustomAction implements GridField_ColumnProvider, GridField_ActionProvider +class GridFieldCustomAction implements GridField_ColumnProvider, GridField_ActionProvider +{ + + public function augmentColumns($gridField, &$columns) { - - public function augmentColumns($gridField, &$columns) - { - if(!in_array('Actions', $columns)) { - $columns[] = 'Actions'; - } - } - - public function getColumnAttributes($gridField, $record, $columnName) - { - return ['class' => 'grid-field__col-compact']; - } - - public function getColumnMetadata($gridField, $columnName) - { - if($columnName == 'Actions') { - return ['title' => '']; - } - } - - public function getColumnsHandled($gridField) - { - return ['Actions']; - } - - public function getColumnContent($gridField, $record, $columnName) - { - if(!$record->canEdit()) return; - - $field = GridField_FormAction::create( - $gridField, - 'CustomAction'.$record->ID, - 'Do Action', - "docustomaction", - ['RecordID' => $record->ID] - ); - - return $field->Field(); - } - - public function getActions($gridField) - { - return ['docustomaction']; - } - - public function handleAction(GridField $gridField, $actionName, $arguments, $data) - { - if($actionName == 'docustomaction') { - // perform your action here - - // output a success message to the user - Controller::curr()->getResponse()->setStatusCode( - 200, - 'Do Custom Action Done.' - ); - } + if(!in_array('Actions', $columns)) { + $columns[] = 'Actions'; } } + public function getColumnAttributes($gridField, $record, $columnName) + { + return ['class' => 'grid-field__col-compact']; + } + + public function getColumnMetadata($gridField, $columnName) + { + if($columnName == 'Actions') { + return ['title' => '']; + } + } + + public function getColumnsHandled($gridField) + { + return ['Actions']; + } + + public function getColumnContent($gridField, $record, $columnName) + { + if(!$record->canEdit()) return; + + $field = GridField_FormAction::create( + $gridField, + 'CustomAction'.$record->ID, + 'Do Action', + "docustomaction", + ['RecordID' => $record->ID] + ); + + return $field->Field(); + } + + public function getActions($gridField) + { + return ['docustomaction']; + } + + public function handleAction(GridField $gridField, $actionName, $arguments, $data) + { + if($actionName == 'docustomaction') { + // perform your action here + + // output a success message to the user + Controller::curr()->getResponse()->setStatusCode( + 200, + 'Do Custom Action Done.' + ); + } + } +} ``` ## Add the GridFieldCustomAction to the current `GridFieldConfig` @@ -96,14 +95,14 @@ manipulating the `GridFieldConfig` instance if required. ```php - // option 1: creating a new GridField with the CustomAction - $config = GridFieldConfig::create(); - $config->addComponent(new GridFieldCustomAction()); +// option 1: creating a new GridField with the CustomAction +$config = GridFieldConfig::create(); +$config->addComponent(new GridFieldCustomAction()); - $gridField = new GridField('Teams', 'Teams', $this->Teams(), $config); +$gridField = new GridField('Teams', 'Teams', $this->Teams(), $config); - // option 2: adding the CustomAction to an exisitng GridField - $gridField->getConfig()->addComponent(new GridFieldCustomAction()); +// option 2: adding the CustomAction to an exisitng GridField +$gridField->getConfig()->addComponent(new GridFieldCustomAction()); ``` For documentation on adding a Component to a `GridField` created by `ModelAdmin` diff --git a/docs/en/02_Developer_Guides/03_Forms/How_Tos/05_Simple_Contact_Form.md b/docs/en/02_Developer_Guides/03_Forms/How_Tos/05_Simple_Contact_Form.md index d192a35a5..c6cf12d57 100644 --- a/docs/en/02_Developer_Guides/03_Forms/How_Tos/05_Simple_Contact_Form.md +++ b/docs/en/02_Developer_Guides/03_Forms/How_Tos/05_Simple_Contact_Form.md @@ -6,34 +6,34 @@ Let's start by defining a new `ContactPage` page type: ```php - use SilverStripe\Forms\FieldList; - use SilverStripe\Forms\TextField; - use SilverStripe\Forms\EmailField; - use SilverStripe\Forms\TextareaField; - use SilverStripe\Forms\FormAction; - use SilverStripe\Forms\Form; - use Page; - use PageController; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\TextField; +use SilverStripe\Forms\EmailField; +use SilverStripe\Forms\TextareaField; +use SilverStripe\Forms\FormAction; +use SilverStripe\Forms\Form; +use Page; +use PageController; - class ContactPage extends Page - { - } - class ContactPageController extends PageController - { - private static $allowed_actions = ['Form']; - public function Form() - { - $fields = new FieldList( - new TextField('Name'), - new EmailField('Email'), - new TextareaField('Message') - ); - $actions = new FieldList( - new FormAction('submit', 'Submit') - ); - return new Form($this, 'Form', $fields, $actions); - } +class ContactPage extends Page +{ +} +class ContactPageController extends PageController +{ + private static $allowed_actions = ['Form']; + public function Form() + { + $fields = new FieldList( + new TextField('Name'), + new EmailField('Email'), + new TextareaField('Message') + ); + $actions = new FieldList( + new FormAction('submit', 'Submit') + ); + return new Form($this, 'Form', $fields, $actions); } +} ``` @@ -43,32 +43,32 @@ There's quite a bit in this function, so we'll step through one piece at a time. ```php - use SilverStripe\Forms\FieldList; - use SilverStripe\Forms\TextField; - use SilverStripe\Forms\EmailField; - use SilverStripe\Forms\TextareaField; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\TextField; +use SilverStripe\Forms\EmailField; +use SilverStripe\Forms\TextareaField; - $fields = new FieldList( - new TextField('Name'), - new EmailField('Email'), - new TextareaField('Message') - ); +$fields = new FieldList( + new TextField('Name'), + new EmailField('Email'), + new TextareaField('Message') +); ``` First we create all the fields we want in the contact form, and put them inside a FieldList. You can find a list of form fields available on the [FormField](api:SilverStripe\Forms\FormField) page. ```php - $actions = FieldList( - new FormAction('submit', 'Submit') - ); +$actions = FieldList( + new FormAction('submit', 'Submit') +); ``` We then create a [FieldList](api:SilverStripe\Forms\FieldList) of the form actions, or the buttons that submit the form. Here we add a single form action, with the name 'submit', and the label 'Submit'. We'll use the name of the form action later. ```php - return new Form($this, 'Form', $fields, $actions); +return new Form($this, 'Form', $fields, $actions); ``` Finally we create the `Form` object and return it. The first argument is the controller that the form is on – this is almost always $this. The second argument is the name of the form – this has to be the same as the name of the function that creates the form, so we've used 'Form'. The third and fourth arguments are the fields and actions we created earlier. @@ -87,36 +87,35 @@ Now that we have a contact form, we need some way of collecting the data submitt ```php - use SilverStripe\Control\Email\Email; - use PageController; +use SilverStripe\Control\Email\Email; - class ContactPageController extends PageController +class ContactPageController extends PageController +{ + private static $allowed_actions = ['Form']; + public function Form() { - private static $allowed_actions = ['Form']; - public function Form() - { - // ... - } - public function submit($data, $form) - { - $email = new Email(); - - $email->setTo('siteowner@mysite.com'); - $email->setFrom($data['Email']); - $email->setSubject("Contact Message from {$data["Name"]}"); - - $messageBody = " -

      Name: {$data['Name']}

      -

      Message: {$data['Message']}

      - "; - $email->setBody($messageBody); - $email->send(); - return [ - 'Content' => '

      Thank you for your feedback.

      ', - 'Form' => '' - ]; - } + // ... } + public function submit($data, $form) + { + $email = new Email(); + + $email->setTo('siteowner@mysite.com'); + $email->setFrom($data['Email']); + $email->setSubject("Contact Message from {$data["Name"]}"); + + $messageBody = " +

      Name: {$data['Name']}

      +

      Message: {$data['Message']}

      + "; + $email->setBody($messageBody); + $email->send(); + return [ + 'Content' => '

      Thank you for your feedback.

      ', + 'Form' => '' + ]; + } +} ``` @@ -142,16 +141,15 @@ The framework comes with a predefined validator called [RequiredFields](api:Silv ```php - use SilverStripe\Forms\Form; - use SilverStripe\Forms\RequiredFields; - - public function Form() - { - // ... - $validator = new RequiredFields('Name', 'Message'); - return new Form($this, 'Form', $fields, $actions, $validator); - } +use SilverStripe\Forms\Form; +use SilverStripe\Forms\RequiredFields; + +public function Form() +{ + // ... + $validator = new RequiredFields('Name', 'Message'); + return new Form($this, 'Form', $fields, $actions, $validator); +} ``` We've created a RequiredFields object, passing the name of the fields we want to be required. The validator we have created is then passed as the fifth argument of the form constructor. If we now try to submit the form without filling out the required fields, JavaScript validation will kick in, and the user will be presented with a message about the missing fields. If the user has JavaScript disabled, PHP validation will kick in when the form is submitted, and the user will be redirected back to the Form with messages about their missing fields. - diff --git a/docs/en/02_Developer_Guides/04_Configuration/00_Configuration.md b/docs/en/02_Developer_Guides/04_Configuration/00_Configuration.md index 7ee680275..bf72c60e8 100644 --- a/docs/en/02_Developer_Guides/04_Configuration/00_Configuration.md +++ b/docs/en/02_Developer_Guides/04_Configuration/00_Configuration.md @@ -29,23 +29,19 @@ be marked `private static` and follow the `lower_case_with_underscores` structur ```php - use Page; +class MyClass extends Page +{ - class MyClass extends Page - { + /** + * @config + */ + private static $option_one = true; - /** - * @config - */ - private static $option_one = true; - - /** - * @config - */ - private static $option_two = []; - - // .. - } + /** + * @config + */ + private static $option_two = []; +} ``` @@ -55,12 +51,13 @@ This can be done by calling the static method [Config::inst()](api:SilverStripe\ ```php - $config = Config::inst()->get('MyClass', 'property'); +$config = Config::inst()->get('MyClass', 'property'); ``` Or through the `config()` object on the class. + ```php - $config = $this->config()->get('property')'; +$config = $this->config()->get('property')'; ``` Note that by default `Config::inst()` returns only an immutable version of config. Use `Config::modify()` @@ -86,45 +83,44 @@ To set those configuration options on our previously defined class we can define ```yml - - MyClass: - option_one: false - option_two: - - Foo - - Bar - - Baz +MyClass: + option_one: false + option_two: + - Foo + - Bar + - Baz ``` To use those variables in your application code: ```php - $me = new MyClass(); +$me = new MyClass(); - echo $me->config()->option_one; - // returns false +echo $me->config()->option_one; +// returns false - echo implode(', ', $me->config()->option_two); - // returns 'Foo, Bar, Baz' +echo implode(', ', $me->config()->option_two); +// returns 'Foo, Bar, Baz' - echo Config::inst()->get('MyClass', 'option_one'); - // returns false +echo Config::inst()->get('MyClass', 'option_one'); +// returns false - echo implode(', ', Config::inst()->get('MyClass', 'option_two')); - // returns 'Foo, Bar, Baz' +echo implode(', ', Config::inst()->get('MyClass', 'option_two')); +// returns 'Foo, Bar, Baz' - Config::modify()->set('MyClass', 'option_one', true); +Config::modify()->set('MyClass', 'option_one', true); - echo Config::inst()->get('MyClass', 'option_one'); - // returns true +echo Config::inst()->get('MyClass', 'option_one'); +// returns true - // You can also use the static version - MyClass::config()->option_two = [ - 'Qux' - ]; +// You can also use the static version +MyClass::config()->option_two = [ + 'Qux' +]; - echo implode(', ', MyClass::config()->option_one); - // returns 'Qux' +echo implode(', ', MyClass::config()->option_one); +// returns 'Qux' ``` @@ -174,9 +170,11 @@ be raised due to optimizations in the lookup code. At some of these levels you can also set masks. These remove values from the composite value at their priority point rather than add. - $actionsWithoutExtra = $this->config()->get( - 'allowed_actions', Config::UNINHERITED - ); +```php +$actionsWithoutExtra = $this->config()->get( + 'allowed_actions', Config::UNINHERITED +); +``` Available masks include: @@ -202,18 +200,18 @@ The name of the files within the applications `_config` directly are arbitrary.
      The structure of each YAML file is a series of headers and values separated by YAML document separators. -```yml - --- - Name: adminroutes - After: - - '#rootroutes' - - '#coreroutes' - --- - SilverStripe\Control\Director: - rules: - 'admin': 'SilverStripe\Admin\AdminRootController' - --- +```yml +--- +Name: adminroutes +After: + - '#rootroutes' + - '#coreroutes' +--- +SilverStripe\Control\Director: + rules: + 'admin': 'SilverStripe\Admin\AdminRootController' +--- ```
      @@ -253,17 +251,16 @@ keys is a list of reference paths to other value sections. A basic example: ```yml - - --- - Name: adminroutes - After: - - '#rootroutes' - - '#coreroutes' - --- - SilverStripe\Control\Director: - rules: - 'admin': 'SilverStripe\Admin\AdminRootController' - --- +--- +Name: adminroutes +After: + - '#rootroutes' + - '#coreroutes' +--- +SilverStripe\Control\Director: + rules: + 'admin': 'SilverStripe\Admin\AdminRootController' +--- ``` You do not have to specify all portions of a reference path. Any portion may be replaced with a wildcard "\*", or left @@ -319,33 +316,30 @@ For instance, to add a property to "foo" when a module exists, and "bar" otherwi ```yml - - --- - Only: - moduleexists: 'MyFineModule' - --- - MyClass: - property: 'foo' - --- - Except: - moduleexists: 'MyFineModule' - --- - MyClass: - property: 'bar' - --- +--- +Only: + moduleexists: 'MyFineModule' +--- +MyClass: + property: 'foo' +--- +Except: + moduleexists: 'MyFineModule' +--- +MyClass: + property: 'bar' +--- ``` Multiple conditions of the same type can be declared via array format - - ```yaml - - --- - Only: - moduleexists: - - 'silverstripe/blog' - - 'silverstripe/lumberjack' +--- +Only: + moduleexists: + - 'silverstripe/blog' + - 'silverstripe/lumberjack' +--- ```
      diff --git a/docs/en/02_Developer_Guides/04_Configuration/01_SiteConfig.md b/docs/en/02_Developer_Guides/04_Configuration/01_SiteConfig.md index c242d484c..d805d3234 100644 --- a/docs/en/02_Developer_Guides/04_Configuration/01_SiteConfig.md +++ b/docs/en/02_Developer_Guides/04_Configuration/01_SiteConfig.md @@ -12,24 +12,23 @@ throughout the site. Out of the box this includes selecting the current site the ```ss +$SiteConfig.Title +$SiteConfig.Tagline - $SiteConfig.Title - $SiteConfig.Tagline - - <% with $SiteConfig %> - $Title $AnotherField - <% end_with %> +<% with $SiteConfig %> + $Title $AnotherField +<% end_with %> ``` To access variables in the PHP: ```php - $config = SiteConfig::current_site_config(); - - echo $config->Title; +$config = SiteConfig::current_site_config(); - // returns "Website Name" +echo $config->Title; + +// returns "Website Name" ``` ## Extending SiteConfig @@ -40,25 +39,24 @@ To extend the options available in the panel, define your own fields via a [Data ```php - use SilverStripe\Forms\FieldList; - use SilverStripe\Forms\HTMLEditor\HTMLEditorField; - use SilverStripe\ORM\DataExtension; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\HTMLEditor\HTMLEditorField; +use SilverStripe\ORM\DataExtension; - class CustomSiteConfig extends DataExtension - { - - private static $db = [ - 'FooterContent' => 'HTMLText' - ]; +class CustomSiteConfig extends DataExtension +{ - public function updateCMSFields(FieldList $fields) - { - $fields->addFieldToTab("Root.Main", - new HTMLEditorField("FooterContent", "Footer Content") - ); - } - } + private static $db = [ + 'FooterContent' => 'HTMLText' + ]; + public function updateCMSFields(FieldList $fields) + { + $fields->addFieldToTab("Root.Main", + new HTMLEditorField("FooterContent", "Footer Content") + ); + } +} ``` Then activate the extension. @@ -67,10 +65,9 @@ Then activate the extension. ```yml - - Silverstripe\SiteConfig\SiteConfig: - extensions: - - CustomSiteConfig +Silverstripe\SiteConfig\SiteConfig: + extensions: + - CustomSiteConfig ```
      diff --git a/docs/en/02_Developer_Guides/05_Extending/01_Extensions.md b/docs/en/02_Developer_Guides/05_Extending/01_Extensions.md index 16ba05e44..fedd77a8b 100644 --- a/docs/en/02_Developer_Guides/05_Extending/01_Extensions.md +++ b/docs/en/02_Developer_Guides/05_Extending/01_Extensions.md @@ -19,22 +19,21 @@ and `RequestHandler`. You can still apply extensions to descendants of these cla ```php - use SilverStripe\ORM\DataExtension; +use SilverStripe\ORM\DataExtension; - class MyMemberExtension extends DataExtension +class MyMemberExtension extends DataExtension +{ + + private static $db = [ + 'DateOfBirth' => 'SS_Datetime' + ]; + + public function SayHi() { - - private static $db = [ - 'DateOfBirth' => 'SS_Datetime' - ]; - - public function SayHi() - { - // $this->owner refers to the original instance. In this case a `Member`. - return "Hi " . $this->owner->Name; - } + // $this->owner refers to the original instance. In this case a `Member`. + return "Hi " . $this->owner->Name; } - +} ```
      @@ -48,17 +47,16 @@ we want to add the `MyMemberExtension` too. To activate this extension, add the ```yml - - SilverStripe\Security\Member: - extensions: - - MyMemberExtension +SilverStripe\Security\Member: + extensions: + - MyMemberExtension ``` Alternatively, we can add extensions through PHP code (in the `_config.php` file). ```php - SilverStripe\Security\Member::add_extension('MyMemberExtension'); +SilverStripe\Security\Member::add_extension('MyMemberExtension'); ``` This class now defines a `MyMemberExtension` that applies to all `Member` instances on the website. It will have @@ -82,35 +80,33 @@ $has_one etc. ```php - use SilverStripe\ORM\DataExtension; +use SilverStripe\ORM\DataExtension; - class MyMemberExtension extends DataExtension +class MyMemberExtension extends DataExtension +{ + + private static $db = [ + 'Position' => 'Varchar', + ]; + + private static $has_one = [ + 'Image' => 'Image', + ]; + + public function SayHi() { - - private static $db = [ - 'Position' => 'Varchar', - ]; - - private static $has_one = [ - 'Image' => 'Image', - ]; - - public function SayHi() - { - // $this->owner refers to the original instance. In this case a `Member`. - return "Hi " . $this->owner->Name; - } + // $this->owner refers to the original instance. In this case a `Member`. + return "Hi " . $this->owner->Name; } - +} ``` **mysite/templates/Page.ss** ```ss - - $CurrentMember.Position - $CurrentMember.Image +$CurrentMember.Position +$CurrentMember.Image ``` ## Adding Methods @@ -121,21 +117,19 @@ we added a `SayHi` method which is unique to our extension. **mysite/templates/Page.ss** ```ss - -

      $CurrentMember.SayHi

      - - // "Hi Sam" +

      $CurrentMember.SayHi

      +// "Hi Sam" ``` **mysite/code/Page.php** ```php - use SilverStripe\Security\Security; - - $member = Security::getCurrentUser(); - echo $member->SayHi; +use SilverStripe\Security\Security; - // "Hi Sam" +$member = Security::getCurrentUser(); +echo $member->SayHi; + +// "Hi Sam" ``` ## Modifying Existing Methods @@ -148,14 +142,14 @@ through the `extend()` method of the [Extensible](api:SilverStripe\Core\Extensib ```php - public function getValidator() - { - // .. - - $this->extend('updateValidator', $validator); +public function getValidator() +{ + // .. + + $this->extend('updateValidator', $validator); - // .. - } + // .. +} ``` Extension Hooks can be located anywhere in the method and provide a point for any `Extension` instances to modify the @@ -167,19 +161,16 @@ validator by defining the `updateValidator` method. ```php - use SilverStripe\ORM\DataExtension; +use SilverStripe\ORM\DataExtension; - class MyMemberExtension extends DataExtension +class MyMemberExtension extends DataExtension +{ + public function updateValidator($validator) { - - // .. - - public function updateValidator($validator) - { - // we want to make date of birth required for each member - $validator->addRequiredField('DateOfBirth'); - } + // we want to make date of birth required for each member + $validator->addRequiredField('DateOfBirth'); } +} ```
      @@ -191,29 +182,28 @@ extension. The `CMS` provides a `updateCMSFields` Extension Hook to tie into. ```php - use SilverStripe\Forms\TextField; - use SilverStripe\AssetAdmin\Forms\UploadField; - use SilverStripe\ORM\DataExtension; +use SilverStripe\Forms\TextField; +use SilverStripe\AssetAdmin\Forms\UploadField; +use SilverStripe\ORM\DataExtension; - class MyMemberExtension extends DataExtension +class MyMemberExtension extends DataExtension +{ + + private static $db = [ + 'Position' => 'Varchar', + ]; + + private static $has_one = [ + 'Image' => 'Image', + ]; + + public function updateCMSFields(FieldList $fields) { - - private static $db = [ - 'Position' => 'Varchar', - ]; - - private static $has_one = [ - 'Image' => 'Image', - ]; - - public function updateCMSFields(FieldList $fields) - { - $fields->push(new TextField('Position')); - $fields->push($upload = new UploadField('Image', 'Profile Image')); - $upload->setAllowedFileCategories('image/supported'); - } + $fields->push(new TextField('Position')); + $fields->push($upload = new UploadField('Image', 'Profile Image')); + $upload->setAllowedFileCategories('image/supported'); } - +} ```
      @@ -223,14 +213,14 @@ which allows an Extension to modify the results. ```php - public function Foo() - { - $foo = // .. +public function Foo() +{ + $foo = // .. - $this->extend('updateFoo', $foo); + $this->extend('updateFoo', $foo); - return $foo; - } + return $foo; +} ``` The convention for extension hooks is to provide an `update{$Function}` hook at the end before you return the result. If @@ -243,31 +233,31 @@ In your [Extension](api:SilverStripe\Core\Extension) class you can only refer to ```php - use SilverStripe\ORM\DataExtension; +use SilverStripe\ORM\DataExtension; - class MyMemberExtension extends DataExtension +class MyMemberExtension extends DataExtension +{ + public function updateFoo($foo) { - - public function updateFoo($foo) - { - // outputs the original class - var_dump($this->owner); - } + // outputs the original class + var_dump($this->owner); } +} ``` ## Checking to see if an Object has an Extension To see what extensions are currently enabled on an object, use the [getExtensionInstances()](api:SilverStripe\Core\Extensible::getExtensionInstances()) and [hasExtension()](api:SilverStripe\Core\Extensible::hasExtension()) methods of the [Extensible](api:SilverStripe\Core\Extensible) trait. -```php - $member = Security::getCurrentUser(); - print_r($member->getExtensionInstances()); - - if($member->hasExtension('MyCustomMemberExtension')) { - // .. - } +```php +$member = Security::getCurrentUser(); + +print_r($member->getExtensionInstances()); + +if($member->hasExtension('MyCustomMemberExtension')) { + // .. +} ``` ## Extension injection points @@ -288,17 +278,16 @@ if not specified in `self::$defaults`, but before extensions have been called: ```php - function __construct() { - $self = $this; +public function __construct() +{ + $this->beforeExtending('populateDefaults', function() { + if(empty($this->MyField)) { + $this->MyField = 'Value we want as a default if not specified in $defaults, but set before extensions'; + } + }); - $this->beforeExtending('populateDefaults', function() use ($self) { - if(empty($self->MyField)) { - $self->MyField = 'Value we want as a default if not specified in $defaults, but set before extensions'; - } - }); - - parent::__construct(); - } + parent::__construct(); +} ``` Example 2: User code can intervene in the process of extending cms fields. @@ -309,18 +298,17 @@ This method is preferred to disabling, enabling, and calling field extensions ma ```php - public function getCMSFields() - { +public function getCMSFields() +{ + $this->beforeUpdateCMSFields(function($fields) { + // Include field which must be present when updateCMSFields is called on extensions + $fields->addFieldToTab("Root.Main", new TextField('Detail', 'Details', null, 255)); + }); - $this->beforeUpdateCMSFields(function($fields) { - // Include field which must be present when updateCMSFields is called on extensions - $fields->addFieldToTab("Root.Main", new TextField('Detail', 'Details', null, 255)); - }); - - $fields = parent::getCMSFields(); - // ... additional fields here - return $fields; - } + $fields = parent::getCMSFields(); + // ... additional fields here + return $fields; +} ``` ## Related Documentaion diff --git a/docs/en/02_Developer_Guides/05_Extending/04_Shortcodes.md b/docs/en/02_Developer_Guides/05_Extending/04_Shortcodes.md index 2d6175d3f..abfd9f8b6 100644 --- a/docs/en/02_Developer_Guides/05_Extending/04_Shortcodes.md +++ b/docs/en/02_Developer_Guides/05_Extending/04_Shortcodes.md @@ -12,22 +12,22 @@ in their WYSIWYG editor. Shortcodes are a semi-technical solution for this. A go viewer or a Google Map at a certain location. ```php - $text = "

      My Map

      [map]" - - // Will output - //

      My Map

      +$text = "

      My Map

      [map]" + +// Will output +//

      My Map

      ``` Here's some syntax variations: ```php - [my_shortcode] - # - [my_shortcode /] - # - [my_shortcode,myparameter="value"] - # - [my_shortcode,myparameter="value"]Enclosed Content[/my_shortcode] +[my_shortcode] +# +[my_shortcode /] +# +[my_shortcode,myparameter="value"] +# +[my_shortcode,myparameter="value"]Enclosed Content[/my_shortcode] ``` Shortcodes are automatically parsed on any database field which is declared as [HTMLValue](api:SilverStripe\View\Parsers\HTMLValue) or [DBHTMLText](api:SilverStripe\ORM\FieldType\DBHTMLText), @@ -38,10 +38,10 @@ Other fields can be manually parsed with shortcodes through the `parse` method. ```php - use SilverStripe\View\Parsers\ShortcodeParser; - - $text = "My awesome [my_shortcode] is here."; - ShortcodeParser::get_active()->parse($text); +use SilverStripe\View\Parsers\ShortcodeParser; + +$text = "My awesome [my_shortcode] is here."; +ShortcodeParser::get_active()->parse($text); ``` ## Defining Custom Shortcodes @@ -52,21 +52,19 @@ First we need to define a callback for the shortcode. ```php - use SilverStripe\CMS\Model\SiteTree; +use SilverStripe\CMS\Model\SiteTree; - class Page extends SiteTree +class Page extends SiteTree +{ + private static $casting = [ + 'MyShortCodeMethod' => 'HTMLText' + ]; + + public static function MyShortCodeMethod($arguments, $content = null, $parser = null, $tagName) { - - private static $casting = [ - 'MyShortCodeMethod' => 'HTMLText' - ]; - - public static function MyShortCodeMethod($arguments, $content = null, $parser = null, $tagName) - { - return "" . $tagName . " " . $content . "; " . count($arguments) . " arguments."; - } + return "" . $tagName . " " . $content . "; " . count($arguments) . " arguments."; } - +} ``` These parameters are passed to the `MyShortCodeMethod` callback: @@ -87,10 +85,9 @@ To register a shortcode you call the following. ```php - // ShortcodeParser::get('default')->register($shortcode, $callback); - - ShortcodeParser::get('default')->register('my_shortcode', ['Page', 'MyShortCodeMethod']); +// ShortcodeParser::get('default')->register($shortcode, $callback); +ShortcodeParser::get('default')->register('my_shortcode', ['Page', 'MyShortCodeMethod']); ``` ## Built-in Shortcodes @@ -105,14 +102,14 @@ shortcode, which takes an `id` parameter. ```php - + ``` Links to internal `File` database records work exactly the same, but with the `[file_link]` shortcode. ```php - + ``` ### Images @@ -121,7 +118,9 @@ Images inserted through the "Insert Media" form (WYSIWYG editor) need to retain the underlying `[Image](api:SilverStripe\Assets\Image)` database record. The `[image]` shortcode saves this database reference instead of hard-linking to the filesystem path of a given image. - [image id="99" alt="My text"] +```html +[image id="99" alt="My text"] +``` ### Media (Photo, Video and Rich Content) @@ -132,11 +131,11 @@ Youtube link pasted into the "Insert Media" form of the CMS. Since TinyMCE can't represent all these variations, we're showing a placeholder instead, and storing the URL with a custom `[embed]` shortcode. - +```html [embed width=480 height=270 class=left thumbnail=http://i1.ytimg.com/vi/lmWeD-vZAMY/hqdefault.jpg?r=8767] http://www.youtube.com/watch?v=lmWeD-vZAMY [/embed] - +``` ### Attribute and element scope @@ -149,84 +148,97 @@ The first is called "element scope" use, the second "attribute scope" You may not use shortcodes in any other location. Specifically, you can not use shortcodes to generate attributes or change the name of a tag. These usages are forbidden: -```ss - <[paragraph]>Some test - link +```html +<[paragraph]>Some test + +link ``` + You may need to escape text inside attributes `>` becomes `>`, You can include HTML tags inside a shortcode tag, but you need to be careful of nesting to ensure you don't break the output. -```ss +```html + +
      + [shortcode] +

      Caption

      + [/shortcode] +
      - -
      - [shortcode] -

      Caption

      - [/shortcode] -
      + - - -
      - [shortcode] -
      -

      - [/shortcode] -

      +
      + [shortcode] +
      +

      + [/shortcode] +

      ``` ### Location Element scoped shortcodes have a special ability to move the location they are inserted at to comply with HTML lexical rules. Take for example this basic paragraph tag: -```ss -

      Head [figure,src="assets/a.jpg",caption="caption"] Tail

      + +```html +

      Head [figure,src="assets/a.jpg",caption="caption"] Tail

      ``` + When converted naively would become: -```ss -

      Head

      caption
      Tail

      + +```html +

      Head

      caption
      Tail

      ``` + However this is not valid HTML - P elements can not contain other block level elements. To fix this you can specify a "location" attribute on a shortcode. When the location attribute is "left" or "right" the inserted content will be moved to immediately before the block tag. The result is this: -```ss -
      caption

      Head Tail

      + +```html +
      caption

      Head Tail

      ``` + When the location attribute is "leftAlone" or "center" then the DOM is split around the element. The result is this: -```ss -

      Head

      caption

      Tail

      + +```html +

      Head

      caption

      Tail

      ``` + ### Parameter values Here is a summary of the callback parameter values based on some example shortcodes. + ```php - public function MyCustomShortCode($arguments, $content = null, $parser = null, $tagName) - { - // .. - } +public function MyCustomShortCode($arguments, $content = null, $parser = null, $tagName) +{ + // .. +} +``` - [my_shortcode] - $attributes => []; - $content => null; - $parser => ShortcodeParser instance, - $tagName => 'my_shortcode') +``` +[my_shortcode] +$attributes => []; +$content => null; +$parser => ShortcodeParser instance, +$tagName => 'my_shortcode') +``` - [my_shortcode,attribute="foo",other="bar"] - - $attributes => ['attribute' => 'foo', 'other' => 'bar'] - $enclosedContent => null - $parser => ShortcodeParser instance - $tagName => 'my_shortcode' - - [my_shortcode,attribute="foo"]content[/my_shortcode] - - $attributes => ['attribute' => 'foo'] - $enclosedContent => 'content' - $parser => ShortcodeParser instance - $tagName => 'my_shortcode' +``` +[my_shortcode,attribute="foo",other="bar"] +$attributes => ['attribute' => 'foo', 'other' => 'bar'] +$enclosedContent => null +$parser => ShortcodeParser instance +$tagName => 'my_shortcode' +``` +``` +[my_shortcode,attribute="foo"]content[/my_shortcode] +$attributes => ['attribute' => 'foo'] +$enclosedContent => 'content' +$parser => ShortcodeParser instance +$tagName => 'my_shortcode' ``` ## Limitations @@ -234,9 +246,11 @@ Here is a summary of the callback parameter values based on some example shortco Since the shortcode parser is based on a simple regular expression it cannot properly handle nested shortcodes. For example the below code will not work as expected: - [shortcode] - [shortcode][/shortcode] - [/shortcode] +```html +[shortcode] +[shortcode][/shortcode] +[/shortcode] +``` The parser will raise an error if it can not find a matching opening tag for any particular closing tag diff --git a/docs/en/02_Developer_Guides/05_Extending/05_Injector.md b/docs/en/02_Developer_Guides/05_Extending/05_Injector.md index 0706237bd..cd7cd3be5 100644 --- a/docs/en/02_Developer_Guides/05_Extending/05_Injector.md +++ b/docs/en/02_Developer_Guides/05_Extending/05_Injector.md @@ -20,33 +20,32 @@ The following sums up the simplest usage of the `Injector` it creates a new obje ```php - use SilverStripe\Core\Injector\Injector; +use SilverStripe\Core\Injector\Injector; - $object = Injector::inst()->create('MyClassName'); +$object = Injector::inst()->create('MyClassName'); ``` The benefit of constructing objects through this syntax is `ClassName` can be swapped out using the [Configuration API](../configuration) by developers. -**mysite/_config/app.yml** +**mysite/_config/app.yml** ```yml - - SilverStripe\Core\Injector\Injector: - MyClassName: - class: MyBetterClassName +SilverStripe\Core\Injector\Injector: + MyClassName: + class: MyBetterClassName ``` Repeated calls to `create()` create a new object each time. ```php - $object = Injector::inst()->create('MyClassName'); - $object2 = Injector::inst()->create('MyClassName'); +$object = Injector::inst()->create('MyClassName'); +$object2 = Injector::inst()->create('MyClassName'); - echo $object !== $object2; +echo $object !== $object2; - // returns true; +// returns true; ``` ## Singleton Pattern @@ -56,13 +55,13 @@ object instance as the first call. ```php - // sets up MyClassName as a singleton - $object = Injector::inst()->get('MyClassName'); - $object2 = Injector::inst()->get('MyClassName'); +// sets up MyClassName as a singleton +$object = Injector::inst()->get('MyClassName'); +$object2 = Injector::inst()->get('MyClassName'); - echo ($object === $object2); +echo ($object === $object2); - // returns true; +// returns true; ``` ## Dependencies @@ -71,83 +70,78 @@ The `Injector` API can be used to define the types of `$dependencies` that an ob ```php - use SilverStripe\Control\Controller; +use SilverStripe\Control\Controller; - class MyController extends Controller - { - - // both of these properties will be automatically - // set by the injector on object creation - public $permissions; - public $textProperty; - - // we declare the types for each of the properties on the object. Anything we pass in via the Injector API must - // match these data types. - static $dependencies = [ - 'textProperty' => 'a string value', - 'permissions' => '%$PermissionService', - ]; - } +class MyController extends Controller +{ + // both of these properties will be automatically + // set by the injector on object creation + public $permissions; + public $textProperty; + + // we declare the types for each of the properties on the object. Anything we pass in via the Injector API must + // match these data types. + static $dependencies = [ + 'textProperty' => 'a string value', + 'permissions' => '%$PermissionService', + ]; +} ``` When creating a new instance of `MyController` the dependencies on that class will be met. ```php - $object = Injector::inst()->get('MyController'); - - echo ($object->permissions instanceof PermissionService); - // returns true; +$object = Injector::inst()->get('MyController'); - echo (is_string($object->textProperty)); - // returns true; +echo ($object->permissions instanceof PermissionService); +// returns true; + +echo (is_string($object->textProperty)); +// returns true; ``` The [Configuration YAML](../configuration) does the hard work of configuring those `$dependencies` for us. -**mysite/_config/app.yml** +**mysite/_config/app.yml** ```yml - - Injector: - PermissionService: - class: MyCustomPermissionService - MyController - properties: - textProperty: 'My Text Value' +Injector: + PermissionService: + class: MyCustomPermissionService + MyController + properties: + textProperty: 'My Text Value' ``` Now the dependencies will be replaced with our configuration. - ```php - $object = Injector::inst()->get('MyController'); - - echo ($object->permissions instanceof MyCustomPermissionService); - // returns true; +$object = Injector::inst()->get('MyController'); - echo ($object->textProperty == 'My Text Value'); - // returns true; +echo ($object->permissions instanceof MyCustomPermissionService); +// returns true; + +echo ($object->textProperty == 'My Text Value'); +// returns true; ``` As well as properties, method calls can also be specified: ```yml - - SilverStripe\Core\Injector\Injector: - Logger: - class: Monolog\Logger - calls: - - [ pushHandler, [ %$DefaultHandler ] ] +SilverStripe\Core\Injector\Injector: + Logger: + class: Monolog\Logger + calls: + - [ pushHandler, [ %$DefaultHandler ] ] ``` ## Using constants as variables Any of the core constants can be used as a service argument by quoting with back ticks "`". Please ensure you also quote the entire value (see below). - ```yaml CachingService: class: SilverStripe\Cache\CacheProvider @@ -168,30 +162,27 @@ An example using the `MyFactory` service to create instances of the `MyService` **mysite/_config/app.yml** - ```yml - - SilverStripe\Core\Injector\Injector: - MyService: - factory: MyFactory +SilverStripe\Core\Injector\Injector: + MyService: + factory: MyFactory ``` **mysite/code/MyFactory.php** ```php - class MyFactory implements SilverStripe\Core\Injector\Factory +class MyFactory implements SilverStripe\Core\Injector\Factory +{ + + public function create($service, array $params = []) { - - public function create($service, array $params = []) - { - return new MyServiceImplementation(); - } + return new MyServiceImplementation(); } +} - // Will use MyFactoryImplementation::create() to create the service instance. - $instance = Injector::inst()->get('MyService'); - +// Will use MyFactoryImplementation::create() to create the service instance. +$instance = Injector::inst()->get('MyService'); ``` ## Dependency overrides @@ -199,12 +190,14 @@ An example using the `MyFactory` service to create instances of the `MyService` To override the `$dependency` declaration for a class, define the following configuration file. **mysite/_config/app.yml** + ```yml - MyController: - dependencies: - textProperty: a string value - permissions: %$PermissionService +MyController: + dependencies: + textProperty: a string value + permissions: %$PermissionService ``` + ## Managed objects Simple dependencies can be specified by the `$dependencies`, but more complex configurations are possible by specifying @@ -215,57 +208,55 @@ runtime. Assuming a class structure such as - ```php - class RestrictivePermissionService - { - private $database; +class RestrictivePermissionService +{ + private $database; - public function setDatabase($d) - { - $this->database = $d; - } + public function setDatabase($d) + { + $this->database = $d; } - class MySQLDatabase +} +class MySQLDatabase +{ + private $username; + private $password; + + public function __construct($username, $password) { - private $username; - private $password; - - public function __construct($username, $password) - { - $this->username = $username; - $this->password = $password; - } + $this->username = $username; + $this->password = $password; } +} ``` And the following configuration.. ```yml - - name: MyController - --- - MyController: - dependencies: - permissions: %$PermissionService - SilverStripe\Core\Injector\Injector: - PermissionService: - class: RestrictivePermissionService - properties: - database: %$MySQLDatabase - MySQLDatabase - constructor: - 0: 'dbusername' - 1: 'dbpassword' +--- +name: MyController +--- +MyController: + dependencies: + permissions: %$PermissionService +SilverStripe\Core\Injector\Injector: + PermissionService: + class: RestrictivePermissionService + properties: + database: %$MySQLDatabase + MySQLDatabase + constructor: + 0: 'dbusername' + 1: 'dbpassword' ``` Calling.. - ```php - // sets up ClassName as a singleton - $controller = Injector::inst()->get('MyController'); +// sets up ClassName as a singleton +$controller = Injector::inst()->get('MyController'); ``` Would setup the following @@ -285,12 +276,12 @@ Thus if you want an object to have the injected dependencies of a service of ano assign a reference to that service. ```yaml - Injector: - JSONServiceDefinition: - class: JSONServiceImplementor - properties: - Serialiser: JSONSerialiser - GZIPJSONProvider: %$JSONServiceDefinition +SilverStripe\Core\Injector\Injector: + JSONServiceDefinition: + class: JSONServiceImplementor + properties: + Serialiser: JSONSerialiser + GZIPJSONProvider: %$JSONServiceDefinition ``` `Injector::inst()->get('GZIPJSONProvider')` will then be an instance of `JSONServiceImplementor` with the injected @@ -302,11 +293,11 @@ If class is not specified, then the class will be inherited from the outer servi For example with this config: ```yml - Injector: - Connector: - properties: - AsString: true - ServiceConnector: %$Connector +SilverStripe\Core\Injector\Injector: + Connector: + properties: + AsString: true + ServiceConnector: %$Connector ``` Both `Connector` and `ServiceConnector` will have the `AsString` property set to true, but the resulting @@ -321,18 +312,20 @@ This is useful when writing test cases, as certain services may be necessary to ```php - // Setup default service - Injector::inst()->registerService(new LiveService(), 'ServiceName'); +use SilverStripe\Core\Injector\Injector; - // Test substitute service temporarily - Injector::nest(); +// Setup default service +Injector::inst()->registerService(new LiveService(), 'ServiceName'); - Injector::inst()->registerService(new TestingService(), 'ServiceName'); - $service = Injector::inst()->get('ServiceName'); - // ... do something with $service +// Test substitute service temporarily +Injector::nest(); - // revert changes - Injector::unnest(); +Injector::inst()->registerService(new TestingService(), 'ServiceName'); +$service = Injector::inst()->get('ServiceName'); +// ... do something with $service + +// revert changes +Injector::unnest(); ``` ## API Documentation diff --git a/docs/en/02_Developer_Guides/05_Extending/06_Aspects.md b/docs/en/02_Developer_Guides/05_Extending/06_Aspects.md index e84d41eae..35b284064 100644 --- a/docs/en/02_Developer_Guides/05_Extending/06_Aspects.md +++ b/docs/en/02_Developer_Guides/05_Extending/06_Aspects.md @@ -47,32 +47,31 @@ used. ```php - class MySQLWriteDbAspect implements BeforeCallAspect +class MySQLWriteDbAspect implements BeforeCallAspect +{ + + /** + * @var MySQLDatabase + */ + public $writeDb; + + public $writeQueries = [ + 'insert','update','delete','replace' + ]; + + public function beforeCall($proxied, $method, $args, &$alternateReturn) { + if (isset($args[0])) { + $sql = $args[0]; + $code = isset($args[1]) ? $args[1] : E_USER_ERROR; - /** - * @var MySQLDatabase - */ - public $writeDb; - - public $writeQueries = [ - 'insert','update','delete','replace' - ]; - - public function beforeCall($proxied, $method, $args, &$alternateReturn) - { - if (isset($args[0])) { - $sql = $args[0]; - $code = isset($args[1]) ? $args[1] : E_USER_ERROR; - - if (in_array(strtolower(substr($sql,0,strpos($sql,' '))), $this->writeQueries)) { - $alternateReturn = $this->writeDb->query($sql, $code); - return false; - } + if (in_array(strtolower(substr($sql,0,strpos($sql,' '))), $this->writeQueries)) { + $alternateReturn = $this->writeDb->query($sql, $code); + return false; } } } - +} ``` To actually make use of this class, a few different objects need to be configured. First up, define the `writeDb` @@ -82,15 +81,15 @@ object that's made use of above. ```yml - - WriteMySQLDatabase: - class: MySQLDatabase - constructor: - - type: MySQLDatabase - server: write.hostname.db - username: user - password: pass - database: write_database +SilverStripe\Core\Injector\Injector: + WriteMySQLDatabase: + class: MySQLDatabase + constructor: + - type: MySQLDatabase + server: write.hostname.db + username: user + password: pass + database: write_database ``` This means that whenever something asks the [Injector](api:SilverStripe\Core\Injector\Injector) for the `WriteMySQLDatabase` object, it'll receive an object @@ -100,23 +99,23 @@ Next, this should be bound into an instance of the `Aspect` class **mysite/_config/app.yml** - ```yml - - MySQLWriteDbAspect: - properties: - writeDb: %$WriteMySQLDatabase +SilverStripe\Core\Injector\Injector: + MySQLWriteDbAspect: + properties: + writeDb: %$WriteMySQLDatabase ``` Next, we need to define the database connection that will be used for all non-write queries **mysite/_config/app.yml** -```yml - ReadMySQLDatabase: - class: MySQLDatabase - constructor: - - type: MySQLDatabase +```yml +SilverStripe\Core\Injector\Injector: + ReadMySQLDatabase: + class: MySQLDatabase + constructor: + - type: MySQLDatabase server: slavecluster.hostname.db username: user password: pass @@ -127,15 +126,16 @@ The final piece that ties everything together is the [AopProxyService](api:Silve object when the framework creates the database connection. **mysite/_config/app.yml** -```yml - MySQLDatabase: - class: AopProxyService - properties: - proxied: %$ReadMySQLDatabase - beforeCall: - query: - - %$MySQLWriteDbAspect +```yml +SilverStripe\Core\Injector\Injector: + MySQLDatabase: + class: AopProxyService + properties: + proxied: %$ReadMySQLDatabase + beforeCall: + query: + - %$MySQLWriteDbAspect ``` The two important parts here are in the `properties` declared for the object. @@ -147,35 +147,35 @@ defined method\_name Overall configuration for this would look as follows **mysite/_config/app.yml** -```yml - Injector: - ReadMySQLDatabase: - class: MySQLDatabase - constructor: - - type: MySQLDatabase - server: slavecluster.hostname.db - username: user - password: pass - database: read_database - MySQLWriteDbAspect: - properties: - writeDb: %$WriteMySQLDatabase - WriteMySQLDatabase: - class: MySQLDatabase - constructor: - - type: MySQLDatabase - server: write.hostname.db - username: user - password: pass - database: write_database - MySQLDatabase: - class: AopProxyService - properties: - proxied: %$ReadMySQLDatabase - beforeCall: - query: - - %$MySQLWriteDbAspect +```yml +SilverStripe\Core\Injector\Injector: + ReadMySQLDatabase: + class: MySQLDatabase + constructor: + - type: MySQLDatabase + server: slavecluster.hostname.db + username: user + password: pass + database: read_database + MySQLWriteDbAspect: + properties: + writeDb: %$WriteMySQLDatabase + WriteMySQLDatabase: + class: MySQLDatabase + constructor: + - type: MySQLDatabase + server: write.hostname.db + username: user + password: pass + database: write_database + MySQLDatabase: + class: AopProxyService + properties: + proxied: %$ReadMySQLDatabase + beforeCall: + query: + - %$MySQLWriteDbAspect ``` ## Changing what a method returns @@ -183,10 +183,10 @@ Overall configuration for this would look as follows One major feature of an `Aspect` is the ability to modify what is returned from the client's call to the proxied method. As seen in the above example, the `beforeCall` method modifies the `&$alternateReturn` variable, and returns `false` after doing so. -```php - $alternateReturn = $this->writeDb->query($sql, $code); - return false; +```php +$alternateReturn = $this->writeDb->query($sql, $code); +return false; ``` By returning `false` from the `beforeCall()` method, the wrapping proxy class will_not_ call any additional `beforeCall` diff --git a/docs/en/02_Developer_Guides/05_Extending/How_Tos/02_Create_a_Google_Maps_Shortcode.md b/docs/en/02_Developer_Guides/05_Extending/How_Tos/02_Create_a_Google_Maps_Shortcode.md index 8982e48ab..abf851588 100644 --- a/docs/en/02_Developer_Guides/05_Extending/How_Tos/02_Create_a_Google_Maps_Shortcode.md +++ b/docs/en/02_Developer_Guides/05_Extending/How_Tos/02_Create_a_Google_Maps_Shortcode.md @@ -6,8 +6,8 @@ To demonstrate how easy it is to build custom shortcodes, we'll build one to dis address. We want our CMS authors to be able to embed the map using the following code: -```php - [googlemap,width=500,height=300]97-99 Courtenay Place, Wellington, New Zealand[/googlemap] +```html +[googlemap,width=500,height=300]97-99 Courtenay Place, Wellington, New Zealand[/googlemap] ``` So we've got the address as "content" of our new `googlemap` shortcode tags, plus some `width` and `height` arguments. @@ -16,23 +16,23 @@ We'll add defaults to those in our shortcode parser so they're optional. **mysite/_config.php** ```php - use SilverStripe\View\Parsers\ShortcodeParser; - - ShortcodeParser::get('default')->register('googlemap', function($arguments, $address, $parser, $shortcode) { - $iframeUrl = sprintf( - 'http://maps.google.com/maps?q=%s&hnear=%s&ie=UTF8&hq=&t=m&z=14&output=embed', - urlencode($address), - urlencode($address) - ); +use SilverStripe\View\Parsers\ShortcodeParser; + +ShortcodeParser::get('default')->register('googlemap', function($arguments, $address, $parser, $shortcode) { + $iframeUrl = sprintf( + 'http://maps.google.com/maps?q=%s&hnear=%s&ie=UTF8&hq=&t=m&z=14&output=embed', + urlencode($address), + urlencode($address) + ); - $width = (isset($arguments['width']) && $arguments['width']) ? $arguments['width'] : 400; - $height = (isset($arguments['height']) && $arguments['height']) ? $arguments['height'] : 300; + $width = (isset($arguments['width']) && $arguments['width']) ? $arguments['width'] : 400; + $height = (isset($arguments['height']) && $arguments['height']) ? $arguments['height'] : 300; - return sprintf( - '', - $width, - $height, - $iframeUrl - ); - }); -``` \ No newline at end of file + return sprintf( + '', + $width, + $height, + $iframeUrl + ); +}); +``` diff --git a/docs/en/02_Developer_Guides/05_Extending/How_Tos/03_Track_member_logins.md b/docs/en/02_Developer_Guides/05_Extending/How_Tos/03_Track_member_logins.md index a694f2020..c8b97fc73 100644 --- a/docs/en/02_Developer_Guides/05_Extending/How_Tos/03_Track_member_logins.md +++ b/docs/en/02_Developer_Guides/05_Extending/How_Tos/03_Track_member_logins.md @@ -11,55 +11,54 @@ explicitly logging in or by invoking the "remember me" functionality. ```php - use SilverStripe\Forms\ReadonlyField; - use SilverStripe\Security\Security; - use SilverStripe\ORM\DB; - use SilverStripe\ORM\DataExtension; +use SilverStripe\Forms\ReadonlyField; +use SilverStripe\Security\Security; +use SilverStripe\ORM\DB; +use SilverStripe\ORM\DataExtension; - class MyMemberExtension extends DataExtension +class MyMemberExtension extends DataExtension +{ + private static $db = [ + 'LastVisited' => 'Datetime', + 'NumVisit' => 'Int', + ]; + + public function memberLoggedIn() { - private static $db = [ - 'LastVisited' => 'Datetime', - 'NumVisit' => 'Int', - ]; - - public function memberLoggedIn() - { - $this->logVisit(); - } - - public function memberAutoLoggedIn() - { - $this->logVisit(); - } - - public function updateCMSFields(FieldList $fields) - { - $fields->addFieldsToTab('Root.Main', [ - ReadonlyField::create('LastVisited', 'Last visited'), - ReadonlyField::create('NumVisit', 'Number of visits') - ]); - } - - protected function logVisit() - { - if(!Security::database_is_ready()) return; - - DB::query(sprintf( - 'UPDATE "Member" SET "LastVisited" = %s, "NumVisit" = "NumVisit" + 1 WHERE "ID" = %d', - DB::get_conn()->now(), - $this->owner->ID - )); - } + $this->logVisit(); } + public function memberAutoLoggedIn() + { + $this->logVisit(); + } + + public function updateCMSFields(FieldList $fields) + { + $fields->addFieldsToTab('Root.Main', [ + ReadonlyField::create('LastVisited', 'Last visited'), + ReadonlyField::create('NumVisit', 'Number of visits') + ]); + } + + protected function logVisit() + { + if(!Security::database_is_ready()) return; + + DB::query(sprintf( + 'UPDATE "Member" SET "LastVisited" = %s, "NumVisit" = "NumVisit" + 1 WHERE "ID" = %d', + DB::get_conn()->now(), + $this->owner->ID + )); + } +} + ``` Now you just need to apply this extension through your config: ```yml - SilverStripe\Security\Member: - extensions: - - MyMemberExtension - -``` \ No newline at end of file +SilverStripe\Security\Member: + extensions: + - MyMemberExtension +``` diff --git a/docs/en/02_Developer_Guides/06_Testing/00_Unit_Testing.md b/docs/en/02_Developer_Guides/06_Testing/00_Unit_Testing.md index 003c0dae8..944a191d4 100644 --- a/docs/en/02_Developer_Guides/06_Testing/00_Unit_Testing.md +++ b/docs/en/02_Developer_Guides/06_Testing/00_Unit_Testing.md @@ -10,33 +10,30 @@ to ensure that it works as it should. A simple example would be to test the resu ```php - - use SilverStripe\CMS\Model\SiteTree; +use SilverStripe\CMS\Model\SiteTree; - class Page extends SiteTree +class Page extends SiteTree +{ + public static function MyMethod() { - public static function MyMethod() - { - return (1 + 1); - } + return (1 + 1); } +} ``` **mysite/tests/PageTest.php** ```php - - use Page; - use SilverStripe\Dev\SapphireTest; +use SilverStripe\Dev\SapphireTest; - class PageTest extends SapphireTest +class PageTest extends SapphireTest +{ + public function testMyMethod() { - public function testMyMethod() - { - $this->assertEquals(2, Page::MyMethod()); - } + $this->assertEquals(2, Page::MyMethod()); } +} ```
      @@ -89,23 +86,16 @@ needs. ```xml - - - mysite/tests - cms/tests - framework/tests - - - - - - - - - sanitychecks - - - + + + mysite/tests + + + + sanitychecks + + + ``` ### setUp() and tearDown() @@ -114,40 +104,37 @@ In addition to loading data through a [Fixture File](fixtures), a test case may run before each test method. For this, use the PHPUnit `setUp` and `tearDown` methods. These are run at the start and end of each test. - ```php - - use SilverStripe\Core\Config\Config; - use SilverStripe\Dev\SapphireTest; +use SilverStripe\Core\Config\Config; +use SilverStripe\Dev\SapphireTest; - class PageTest extends SapphireTest +class PageTest extends SapphireTest +{ + public function setUp() { - function setUp() - { - parent::setUp(); + 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::inst()->update('Foo', 'bar', 'Hello!'); + // create 100 pages + for ($i = 0; $i < 100; $i++) { + $page = new Page(['Title' => "Page $i"]); + $page->write(); + $page->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); } - public function testMyMethod() - { - // .. - } - - public function testMySecondMethod() - { - // .. - } + // set custom configuration for the test. + Config::modify()->update('Foo', 'bar', 'Hello!'); } + public function testMyMethod() + { + // .. + } + + public function testMySecondMethod() + { + // .. + } +} ``` `tearDownAfterClass` and `setUpBeforeClass` can be used to run code just once for the file rather than before and after @@ -156,25 +143,24 @@ takes place. ```php - - use SilverStripe\Dev\SapphireTest; - - class PageTest extends SapphireTest +use SilverStripe\Dev\SapphireTest; + +class PageTest extends SapphireTest +{ + public static function setUpBeforeClass() { - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); + parent::setUpBeforeClass(); - // .. - } - - public static function tearDownAfterClass() - { - parent::tearDownAfterClass(); - - // .. - } + // .. } + + public static function tearDownAfterClass() + { + parent::tearDownAfterClass(); + + // .. + } +} ``` ### Config and Injector Nesting @@ -189,23 +175,23 @@ It's important to remember that the `parent::setUp();` functions will need to be ```php - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - //this will remain for the whole suite and be removed for any other tests - Config::inst()->update('ClassName', 'var_name', 'var_value'); - } - - public function testFeatureDoesAsExpected() - { - //this will be reset to 'var_value' at the end of this test function - Config::inst()->update('ClassName', 'var_name', 'new_var_value'); - } - - public function testAnotherFeatureDoesAsExpected() - { - Config::inst()->get('ClassName', 'var_name'); // this will be 'var_value' - } +public static function setUpBeforeClass() +{ + parent::setUpBeforeClass(); + //this will remain for the whole suite and be removed for any other tests + Config::inst()->update('ClassName', 'var_name', 'var_value'); +} + +public function testFeatureDoesAsExpected() +{ + //this will be reset to 'var_value' at the end of this test function + Config::inst()->update('ClassName', 'var_name', 'new_var_value'); +} + +public function testAnotherFeatureDoesAsExpected() +{ + Config::inst()->get('ClassName', 'var_name'); // this will be 'var_value' +} ``` ## Related Documentation diff --git a/docs/en/02_Developer_Guides/06_Testing/01_Functional_Testing.md b/docs/en/02_Developer_Guides/06_Testing/01_Functional_Testing.md index e3a3597ec..b4a28cbbd 100644 --- a/docs/en/02_Developer_Guides/06_Testing/01_Functional_Testing.md +++ b/docs/en/02_Developer_Guides/06_Testing/01_Functional_Testing.md @@ -8,8 +8,9 @@ core idea of these tests is the same as `SapphireTest` unit tests but `Functiona creating [HTTPRequest](api:SilverStripe\Control\HTTPRequest), receiving [HTTPResponse](api:SilverStripe\Control\HTTPResponse) objects and modifying the current user session. ## Get + ```php - $page = $this->get($url); +$page = $this->get($url); ``` Performs a GET request on $url and retrieves the [HTTPResponse](api:SilverStripe\Control\HTTPResponse). This also changes the current page to the value @@ -17,7 +18,7 @@ of the response. ## Post ```php - $page = $this->post($url); +$page = $this->post($url); ``` Performs a POST request on $url and retrieves the [HTTPResponse](api:SilverStripe\Control\HTTPResponse). This also changes the current page to the value @@ -27,8 +28,7 @@ of the response. ```php - $submit = $this->submitForm($formID, $button = null, $data = []); - +$submit = $this->submitForm($formID, $button = null, $data = []); ``` Submits the given form (`#ContactForm`) on the current page and returns the [HTTPResponse](api:SilverStripe\Control\HTTPResponse). @@ -37,14 +37,14 @@ Submits the given form (`#ContactForm`) on the current page and returns the [HTT ```php - $this->logInAs($member); +$this->logInAs($member); ``` Logs a given user in, sets the current session. To log all users out pass `null` to the method. ```php - $this->logInAs(null); +$this->logInAs(null); ``` ## Assertions @@ -55,10 +55,9 @@ The `FunctionalTest` class also provides additional asserts to validate your tes ```php - $this->assertPartialMatchBySelector('p.good',[ - 'Test save was successful' - ]); - +$this->assertPartialMatchBySelector('p.good',[ + 'Test save was successful' +]); ``` Asserts that the most recently queried page contains a number of content tags specified by a CSS selector. The given CSS @@ -70,10 +69,9 @@ assertion fails if one of the expectedMatches fails to appear. ```php - $this->assertExactMatchBySelector("#MyForm_ID p.error", [ - "That email address is invalid." - ]); - +$this->assertExactMatchBySelector("#MyForm_ID p.error", [ + "That email address is invalid." +]); ``` Asserts that the most recently queried page contains a number of content tags specified by a CSS selector. The given CSS @@ -81,11 +79,11 @@ selector will be applied to the HTML of the most recent page. The full HTML of e assertion fails if one of the expectedMatches fails to appear. ### assertPartialHTMLMatchBySelector -```php - $this->assertPartialHTMLMatchBySelector("#MyForm_ID p.error", [ - "That email address is invalid." - ]); +```php +$this->assertPartialHTMLMatchBySelector("#MyForm_ID p.error", [ + "That email address is invalid." +]); ``` Assert that the most recently queried page contains a number of content tags specified by a CSS selector. The given CSS @@ -98,10 +96,9 @@ assertion fails if one of the expectedMatches fails to appear. ### assertExactHTMLMatchBySelector ```php - $this->assertExactHTMLMatchBySelector("#MyForm_ID p.error", [ - "That email address is invalid." - ]); - +$this->assertExactHTMLMatchBySelector("#MyForm_ID p.error", [ + "That email address is invalid." +]); ``` Assert that the most recently queried page contains a number of content tags specified by a CSS selector. The given CSS diff --git a/docs/en/02_Developer_Guides/06_Testing/04_Fixtures.md b/docs/en/02_Developer_Guides/06_Testing/04_Fixtures.md index de436503b..8fabab9ce 100644 --- a/docs/en/02_Developer_Guides/06_Testing/04_Fixtures.md +++ b/docs/en/02_Developer_Guides/06_Testing/04_Fixtures.md @@ -3,10 +3,10 @@ summary: Populate test databases with fake seed data. # Fixtures -To test functionality correctly, we must use consistent data. If we are testing our code with the same data each -time, we can trust our tests to yield reliable results and to identify when the logic changes. Each test run in +To test functionality correctly, we must use consistent data. If we are testing our code with the same data each +time, we can trust our tests to yield reliable results and to identify when the logic changes. Each test run in SilverStripe starts with a fresh database containing no records. `Fixtures` provide a way to describe the initial data -to load into the database. The [SapphireTest](api:SilverStripe\Dev\SapphireTest) class takes care of populating a test database with data from +to load into the database. The [SapphireTest](api:SilverStripe\Dev\SapphireTest) class takes care of populating a test database with data from fixtures - all we have to do is define them. To include your fixture file in your tests, you should define it as your `$fixture_file`: @@ -16,115 +16,114 @@ To include your fixture file in your tests, you should define it as your `$fixtu ```php - use SilverStripe\Dev\SapphireTest; +use SilverStripe\Dev\SapphireTest; - class MyNewTest extends SapphireTest - { - - protected static $fixture_file = 'fixtures.yml'; - - } +class MyNewTest extends SapphireTest +{ + protected static $fixture_file = 'fixtures.yml'; +} ``` -You can also use an array of fixture files, if you want to use parts of multiple other tests: +You can also use an array of fixture files, if you want to use parts of multiple other tests. +If you are using [api:SilverStripe\Dev\TestOnly] dataobjects in your fixtures, you must +declare these classes within the $extra_dataobjects variable. **mysite/tests/MyNewTest.php** - ```php - use SilverStripe\Dev\SapphireTest; +use SilverStripe\Dev\SapphireTest; - class MyNewTest extends SapphireTest - { - - protected static $fixture_file = [ - 'fixtures.yml', - 'otherfixtures.yml' - ]; - - } +class MyNewTest extends SapphireTest +{ + protected static $fixture_file = [ + 'fixtures.yml', + 'otherfixtures.yml' + ]; + protected static $extra_dataobjects = [ + Player::class, + Team::class, + ]; +} ``` Typically, you'd have a separate fixture file for each class you are testing - although overlap between tests is common. -Fixtures are defined in `YAML`. `YAML` is a markup language which is deliberately simple and easy to read, so it is +Fixtures are defined in `YAML`. `YAML` is a markup language which is deliberately simple and easy to read, so it is ideal for fixture generation. Say we have the following two DataObjects: ```php - - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; +use SilverStripe\Dev\TestOnly; - class Player extends DataObject - { - private static $db = [ - 'Name' => 'Varchar(255)' - ]; +class Player extends DataObject implements TestOnly +{ + private static $db = [ + 'Name' => 'Varchar(255)' + ]; - private static $has_one = [ - 'Team' => 'Team' - ]; - } + private static $has_one = [ + 'Team' => 'Team' + ]; +} - class Team extends DataObject - { - private static $db = [ - 'Name' => 'Varchar(255)', - 'Origin' => 'Varchar(255)' - ]; - - private static $has_many = [ - 'Players' => 'Player' - ]; - } +class Team extends DataObject implements TestOnly +{ + private static $db = [ + 'Name' => 'Varchar(255)', + 'Origin' => 'Varchar(255)' + ]; + private static $has_many = [ + 'Players' => 'Player' + ]; +} ``` We can represent multiple instances of them in `YAML` as follows: **mysite/tests/fixtures.yml** - ```yml - Team: - hurricanes: - Name: The Hurricanes - Origin: Wellington - crusaders: - Name: The Crusaders - Origin: Canterbury - Player: - john: - Name: John - Team: =>Team.hurricanes - joe: - Name: Joe - Team: =>Team.crusaders - jack: - Name: Jack - Team: =>Team.crusaders +Team: + hurricanes: + Name: The Hurricanes + Origin: Wellington + crusaders: + Name: The Crusaders + Origin: Canterbury +Player: + john: + Name: John + Team: =>Team.hurricanes + joe: + Name: Joe + Team: =>Team.crusaders + jack: + Name: Jack + Team: =>Team.crusaders ``` -This `YAML` is broken up into three levels, signified by the indentation of each line. In the first level of +This `YAML` is broken up into three levels, signified by the indentation of each line. In the first level of indentation, `Player` and `Team`, represent the class names of the objects we want to be created. -The second level, `john`/`joe`/`jack` & `hurricanes`/`crusaders`, are **identifiers**. Each identifier you specify +The second level, `john`/`joe`/`jack` & `hurricanes`/`crusaders`, are **identifiers**. Each identifier you specify represents a new object and can be referenced in the PHP using `objFromFixture` ```php - $player = $this->objFromFixture('Player', 'jack'); +$player = $this->objFromFixture('Player', 'jack'); ``` The third and final level represents each individual object's fields. -A field can either be provided with raw data (such as the names for our Players), or we can define a relationship, as +A field can either be provided with raw data (such as the names for our Players), or we can define a relationship, as seen by the fields prefixed with `=>`. -Each one of our Players has a relationship to a Team, this is shown with the `Team` field for each `Player` being set +Each one of our Players has a relationship to a Team, this is shown with the `Team` field for each `Player` being set to `=>Team.` followed by a team name.
      @@ -133,7 +132,7 @@ sets the `has_one` relationship for John with with the `Team` object `hurricanes
      -Note that we use the name of the relationship (Team), and not the name of the +Note that we use the name of the relationship (Team), and not the name of the database field (TeamID).
      @@ -147,44 +146,42 @@ We can also declare the relationships conversely. Another way we could write the ```yml - - Player: - john: - Name: John - joe: - Name: Joe - jack: - Name: Jack - Team: - hurricanes: - Name: Hurricanes - Origin: Wellington - Players: =>Player.john - crusaders: - Name: Crusaders - Origin: Canterbury - Players: =>Player.joe,=>Player.jack +Player: + john: + Name: John + joe: + Name: Joe + jack: + Name: Jack +Team: + hurricanes: + Name: Hurricanes + Origin: Wellington + Players: =>Player.john + crusaders: + Name: Crusaders + Origin: Canterbury + Players: =>Player.joe,=>Player.jack ``` -The database is populated by instantiating `DataObject` objects and setting the fields declared in the `YAML`, then -calling `write()` on those objects. Take for instance the `hurricances` record in the `YAML`. It is equivalent to +The database is populated by instantiating `DataObject` objects and setting the fields declared in the `YAML`, then +calling `write()` on those objects. Take for instance the `hurricances` record in the `YAML`. It is equivalent to writing: ```php - $team = new Team([ - 'Name' => 'Hurricanes', - 'Origin' => 'Wellington' - ]); +$team = new Team([ + 'Name' => 'Hurricanes', + 'Origin' => 'Wellington' +]); - $team->write(); - - $team->Players()->add($john); +$team->write(); +$team->Players()->add($john); ```
      -As the YAML fixtures will call `write`, any `onBeforeWrite()` or default value logic will be executed as part of the +As the YAML fixtures will call `write`, any `onBeforeWrite()` or default value logic will be executed as part of the test.
      @@ -194,16 +191,14 @@ As of SilverStripe 4 you will need to use fully qualfied class names in your YAM ```yml - - MyProject\Model\Player: - john: - Name: join - - MyProject\Model\Team: - crusaders: - Name: Crusaders - Origin: Canterbury - Players: =>MyProject\Model\Player.john +MyProject\Model\Player: + john: + Name: join +MyProject\Model\Team: + crusaders: + Name: Crusaders + Origin: Canterbury + Players: =>MyProject\Model\Player.john ```
      @@ -212,110 +207,107 @@ If your tests are failing and your database has table names that follow the full ### Defining many_many_extraFields -`many_many` relations can have additional database fields attached to the relationship. For example we may want to +`many_many` relations can have additional database fields attached to the relationship. For example we may want to declare the role each player has in the team. ```php - use SilverStripe\ORM\DataObject; - - class Player extends DataObject - { - private static $db = [ - 'Name' => 'Varchar(255)' - ]; +use SilverStripe\ORM\DataObject; - private static $belongs_many_many = [ - 'Teams' => 'Team' - ]; - } +class Player extends DataObject +{ + private static $db = [ + 'Name' => 'Varchar(255)' + ]; - class Team extends DataObject - { - private static $db = [ - 'Name' => 'Varchar(255)' - ]; + private static $belongs_many_many = [ + 'Teams' => 'Team' + ]; +} - private static $many_many = [ - 'Players' => 'Player' - ]; +class Team extends DataObject +{ + private static $db = [ + 'Name' => 'Varchar(255)' + ]; - private static $many_many_extraFields = [ - 'Players' => [ - 'Role' => "Varchar" - ] - ]; - } + private static $many_many = [ + 'Players' => 'Player' + ]; + private static $many_many_extraFields = [ + 'Players' => [ + 'Role' => "Varchar" + ] + ]; +} ``` To provide the value for the `many_many_extraField` use the YAML list syntax. ```yml +Player: + john: + Name: John + joe: + Name: Joe + jack: + Name: Jack +Team: + hurricanes: + Name: The Hurricanes + Players: + - =>Player.john: + Role: Captain - Player: - john: - Name: John - joe: - Name: Joe - jack: - Name: Jack - Team: - hurricanes: - Name: The Hurricanes - Players: - - =>Player.john: - Role: Captain - - crusaders: - Name: The Crusaders - Players: - - =>Player.joe: - Role: Captain - - =>Player.jack: - Role: Winger + crusaders: + Name: The Crusaders + Players: + - =>Player.joe: + Role: Captain + - =>Player.jack: + Role: Winger ``` ## Fixture Factories -While manually defined fixtures provide full flexibility, they offer very little in terms of structure and convention. +While manually defined fixtures provide full flexibility, they offer very little in terms of structure and convention. -Alternatively, you can use the [FixtureFactory](api:SilverStripe\Dev\FixtureFactory) class, which allows you to set default values, callbacks on object +Alternatively, you can use the [FixtureFactory](api:SilverStripe\Dev\FixtureFactory) class, which allows you to set default values, callbacks on object creation, and dynamic/lazy value setting.
      `SapphireTest` uses `FixtureFactory` under the hood when it is provided with YAML based fixtures.
      -The idea is that rather than instantiating objects directly, we'll have a factory class for them. This factory can have -*blueprints* defined on it, which tells the factory how to instantiate an object of a specific type. Blueprints need a +The idea is that rather than instantiating objects directly, we'll have a factory class for them. This factory can have +*blueprints* defined on it, which tells the factory how to instantiate an object of a specific type. Blueprints need a name, which is usually set to the class it creates such as `Member` or `Page`. -Blueprints are auto-created for all available DataObject subclasses, you only need to instantiate a factory to start +Blueprints are auto-created for all available DataObject subclasses, you only need to instantiate a factory to start using them. ```php - use SilverStripe\Core\Injector\Injector; - - $factory = Injector::inst()->create('FixtureFactory'); +use SilverStripe\Core\Injector\Injector; - $obj = $factory->createObject('Team', 'hurricanes'); +$factory = Injector::inst()->create('FixtureFactory'); + +$obj = $factory->createObject('Team', 'hurricanes'); ``` In order to create an object with certain properties, just add a third argument: ```php - $obj = $factory->createObject('Team', 'hurricanes', [ - 'Name' => 'My Value' - ]); - +$obj = $factory->createObject('Team', 'hurricanes', [ + 'Name' => 'My Value' +]); ```
      -It is important to remember that fixtures are referenced by arbitrary identifiers ('hurricanes'). These are internally +It is important to remember that fixtures are referenced by arbitrary identifiers ('hurricanes'). These are internally mapped to their database identifiers.
      @@ -323,7 +315,7 @@ After we've created this object in the factory, `getId` is used to retrieve it b ```php - $databaseId = $factory->getId('Team', 'hurricanes'); +$databaseId = $factory->getId('Team', 'hurricanes'); ``` ### Default Properties @@ -333,59 +325,56 @@ name, we can set the default to be `Unknown Team`. ```php - $factory->define('Team', [ - 'Name' => 'Unknown Team' - ]); - +$factory->define('Team', [ + 'Name' => 'Unknown Team' +]); ``` ### Dependent Properties -Values can be set on demand through anonymous functions, which can either generate random defaults, or create composite +Values can be set on demand through anonymous functions, which can either generate random defaults, or create composite values based on other fixture data. ```php - $factory->define('Member', [ - 'Email' => function($obj, $data, $fixtures) { - if(isset($data['FirstName']) { - $obj->Email = strtolower($data['FirstName']) . '@example.org'; - } - }, - 'Score' => function($obj, $data, $fixtures) { - $obj->Score = rand(0,10); +$factory->define('Member', [ + 'Email' => function($obj, $data, $fixtures) { + if(isset($data['FirstName']) { + $obj->Email = strtolower($data['FirstName']) . '@example.org'; } - )]; - + }, + 'Score' => function($obj, $data, $fixtures) { + $obj->Score = rand(0,10); + } +)]; ``` ### Relations -Model relations can be expressed through the same notation as in the YAML fixture format described earlier, through the +Model relations can be expressed through the same notation as in the YAML fixture format described earlier, through the `=>` prefix on data values. ```php - $obj = $factory->createObject('Team', 'hurricanes', [ - 'MyHasManyRelation' => '=>Player.john,=>Player.joe' - ]); - +$obj = $factory->createObject('Team', 'hurricanes', [ + 'MyHasManyRelation' => '=>Player.john,=>Player.joe' +]); ``` #### Callbacks -Sometimes new model instances need to be modified in ways which can't be expressed in their properties, for example to +Sometimes new model instances need to be modified in ways which can't be expressed in their properties, for example to publish a page, which requires a method call. ```php - $blueprint = Injector::inst()->create('FixtureBlueprint', 'Member'); +$blueprint = Injector::inst()->create('FixtureBlueprint', 'Member'); - $blueprint->addCallback('afterCreate', function($obj, $identifier, $data, $fixtures) { - $obj->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); - }); +$blueprint->addCallback('afterCreate', function($obj, $identifier, $data, $fixtures) { + $obj->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); +}); - $page = $factory->define('Page', $blueprint); +$page = $factory->define('Page', $blueprint); ``` Available callbacks: @@ -395,26 +384,26 @@ Available callbacks: ### Multiple Blueprints -Data of the same type can have variations, for example forum members vs. CMS admins could both inherit from the `Member` -class, but have completely different properties. This is where named blueprints come in. By default, blueprint names +Data of the same type can have variations, for example forum members vs. CMS admins could both inherit from the `Member` +class, but have completely different properties. This is where named blueprints come in. By default, blueprint names equal the class names they manage. ```php - $memberBlueprint = Injector::inst()->create('FixtureBlueprint', 'Member', 'Member'); +$memberBlueprint = Injector::inst()->create('FixtureBlueprint', 'Member', 'Member'); - $adminBlueprint = Injector::inst()->create('FixtureBlueprint', 'AdminMember', 'Member'); +$adminBlueprint = Injector::inst()->create('FixtureBlueprint', 'AdminMember', 'Member'); - $adminBlueprint->addCallback('afterCreate', function($obj, $identifier, $data, $fixtures) { - if(isset($fixtures['Group']['admin'])) { - $adminGroup = Group::get()->byId($fixtures['Group']['admin']); - $obj->Groups()->add($adminGroup); - } - }); +$adminBlueprint->addCallback('afterCreate', function($obj, $identifier, $data, $fixtures) { + if(isset($fixtures['Group']['admin'])) { + $adminGroup = Group::get()->byId($fixtures['Group']['admin']); + $obj->Groups()->add($adminGroup); + } +}); - $member = $factory->createObject('Member'); // not in admin group +$member = $factory->createObject('Member'); // not in admin group - $admin = $factory->createObject('AdminMember'); // in admin group +$admin = $factory->createObject('AdminMember'); // in admin group ``` ## Related Documentation @@ -425,4 +414,3 @@ equal the class names they manage. * [FixtureFactory](api:SilverStripe\Dev\FixtureFactory) * [FixtureBlueprint](api:SilverStripe\Dev\FixtureBlueprint) - diff --git a/docs/en/02_Developer_Guides/06_Testing/How_Tos/00_Write_a_SapphireTest.md b/docs/en/02_Developer_Guides/06_Testing/How_Tos/00_Write_a_SapphireTest.md index 67cc5c1fd..c1ce5bbc7 100644 --- a/docs/en/02_Developer_Guides/06_Testing/How_Tos/00_Write_a_SapphireTest.md +++ b/docs/en/02_Developer_Guides/06_Testing/How_Tos/00_Write_a_SapphireTest.md @@ -7,44 +7,41 @@ how you can load default records into the test database. **mysite/tests/PageTest.php** - ```php - - use SilverStripe\Dev\SapphireTest; +use SilverStripe\Dev\SapphireTest; - class PageTest extends SapphireTest +class PageTest extends SapphireTest +{ + /** + * Defines the fixture file to use for this test class + * @var string + */ + protected static $fixture_file = 'SiteTreeTest.yml'; + + /** + * Test generation of the URLSegment values. + * + * Makes sure to: + * - Turn things into lowercase-hyphen-format + * - Generates from Title by default, unless URLSegment is explicitly set + * - Resolves duplicates by appending a number + */ + public function testURLGeneration() { - /** - * Defines the fixture file to use for this test class - * @var string - */ - protected static $fixture_file = 'SiteTreeTest.yml'; + $expectedURLs = [ + 'home' => 'home', + 'staff' => 'my-staff', + 'about' => 'about-us', + 'staffduplicate' => 'my-staff-2' + ]; - /** - * Test generation of the URLSegment values. - * - * Makes sure to: - * - Turn things into lowercase-hyphen-format - * - Generates from Title by default, unless URLSegment is explicitly set - * - Resolves duplicates by appending a number - */ - public function testURLGeneration() - { - $expectedURLs = [ - 'home' => 'home', - 'staff' => 'my-staff', - 'about' => 'about-us', - 'staffduplicate' => 'my-staff-2' - ]; + foreach ($expectedURLs as $fixture => $urlSegment) { + $obj = $this->objFromFixture('Page', $fixture); - foreach($expectedURLs as $fixture => $urlSegment) { - $obj = $this->objFromFixture('Page', $fixture); - - $this->assertEquals($urlSegment, $obj->URLSegment); - } + $this->assertEquals($urlSegment, $obj->URLSegment); } } - +} ``` Firstly we define a static `$fixture_file`, this should point to a file that represents the data we want to test, diff --git a/docs/en/02_Developer_Guides/06_Testing/How_Tos/01_Write_a_FunctionalTest.md b/docs/en/02_Developer_Guides/06_Testing/How_Tos/01_Write_a_FunctionalTest.md index b9d66e4e5..64aa77528 100644 --- a/docs/en/02_Developer_Guides/06_Testing/How_Tos/01_Write_a_FunctionalTest.md +++ b/docs/en/02_Developer_Guides/06_Testing/How_Tos/01_Write_a_FunctionalTest.md @@ -11,44 +11,43 @@ response and modify the session within a test. ```php - use SilverStripe\Security\Member; +use SilverStripe\Security\Member; - class HomePageTest extends FunctionalTest +class HomePageTest extends FunctionalTest +{ + + /** + * Test generation of the view + */ + public function testViewHomePage() { + $page = $this->get('home/'); - /** - * Test generation of the view - */ - public function testViewHomePage() - { - $page = $this->get('home/'); + // Home page should load.. + $this->assertEquals(200, $page->getStatusCode()); - // Home page should load.. - $this->assertEquals(200, $page->getStatusCode()); + // We should see a login form + $login = $this->submitForm("LoginFormID", null, [ + 'Email' => 'test@test.com', + 'Password' => 'wrongpassword' + ]); - // We should see a login form - $login = $this->submitForm("LoginFormID", null, [ - 'Email' => 'test@test.com', - 'Password' => 'wrongpassword' - ]); + // wrong details, should now see an error message + $this->assertExactHTMLMatchBySelector("#LoginForm p.error", [ + "That email address is invalid." + ]); - // wrong details, should now see an error message - $this->assertExactHTMLMatchBySelector("#LoginForm p.error", [ - "That email address is invalid." - ]); + // If we login as a user we should see a welcome message + $me = Member::get()->first(); - // If we login as a user we should see a welcome message - $me = Member::get()->first(); + $this->logInAs($me); + $page = $this->get('home/'); - $this->logInAs($me); - $page = $this->get('home/'); - - $this->assertExactHTMLMatchBySelector("#Welcome", [ - 'Welcome Back' - ]); - } + $this->assertExactHTMLMatchBySelector("#Welcome", [ + 'Welcome Back' + ]); } - +} ``` ## Related Documentation diff --git a/docs/en/02_Developer_Guides/06_Testing/How_Tos/02_FixtureFactories.md b/docs/en/02_Developer_Guides/06_Testing/How_Tos/02_FixtureFactories.md index fce9bd084..5beea1084 100644 --- a/docs/en/02_Developer_Guides/06_Testing/How_Tos/02_FixtureFactories.md +++ b/docs/en/02_Developer_Guides/06_Testing/How_Tos/02_FixtureFactories.md @@ -10,42 +10,41 @@ with information that we need. ```php - use SilverStripe\Core\Injector\Injector; - use SilverStripe\Dev\SapphireTest; - use SilverStripe\Core\Injector\Injector; - - class MyObjectTest extends SapphireTest - { +use SilverStripe\Core\Injector\Injector; +use SilverStripe\Dev\SapphireTest; +use SilverStripe\Core\Injector\Injector; - protected $factory; +class MyObjectTest extends SapphireTest +{ - function __construct() { - parent::__construct(); + protected $factory; - $factory = Injector::inst()->create('FixtureFactory'); + function __construct() { + parent::__construct(); - // Defines a "blueprint" for new objects - $factory->define('MyObject', [ - 'MyProperty' => 'My Default Value' - ]); + $factory = Injector::inst()->create('FixtureFactory'); - $this->factory = $factory; - } + // Defines a "blueprint" for new objects + $factory->define('MyObject', [ + 'MyProperty' => 'My Default Value' + ]); - function testSomething() { - $MyObjectObj = $this->factory->createObject( - 'MyObject', - ['MyOtherProperty' => 'My Custom Value'] - ); - - echo $MyObjectObj->MyProperty; - // returns "My Default Value" - - echo $myPageObj->MyOtherProperty; - // returns "My Custom Value" - } + $this->factory = $factory; } + function testSomething() { + $MyObjectObj = $this->factory->createObject( + 'MyObject', + ['MyOtherProperty' => 'My Custom Value'] + ); + + echo $MyObjectObj->MyProperty; + // returns "My Default Value" + + echo $myPageObj->MyOtherProperty; + // returns "My Custom Value" + } +} ``` ## Related Documentation diff --git a/docs/en/02_Developer_Guides/06_Testing/How_Tos/03_Testing_Email.md b/docs/en/02_Developer_Guides/06_Testing/How_Tos/03_Testing_Email.md index c6ca30149..c82316f16 100644 --- a/docs/en/02_Developer_Guides/06_Testing/How_Tos/03_Testing_Email.md +++ b/docs/en/02_Developer_Guides/06_Testing/How_Tos/03_Testing_Email.md @@ -8,26 +8,26 @@ email was sent using this method. ```php - use SilverStripe\Control\Email\Email; - - public function MyMethod() - { - $e = new Email(); - $e->To = "someone@example.com"; - $e->Subject = "Hi there"; - $e->Body = "I just really wanted to email you and say hi."; - $e->send(); - } +use SilverStripe\Control\Email\Email; + +public function MyMethod() +{ + $e = new Email(); + $e->To = "someone@example.com"; + $e->Subject = "Hi there"; + $e->Body = "I just really wanted to email you and say hi."; + $e->send(); +} ``` To test that `MyMethod` sends the correct email, use the [SapphireTest::assertEmailSent()](api:SilverStripe\Dev\SapphireTest::assertEmailSent()) method. ```php - $this->assertEmailSent($to, $from, $subject, $body); +$this->assertEmailSent($to, $from, $subject, $body); - // to assert that the email is sent to the correct person - $this->assertEmailSent("someone@example.com", null, "/th.*e$/"); +// to assert that the email is sent to the correct person +$this->assertEmailSent("someone@example.com", null, "/th.*e$/"); ``` Each of the arguments (`$to`, `$from`, `$subject` and `$body`) can be either one of the following. diff --git a/docs/en/02_Developer_Guides/06_Testing/index.md b/docs/en/02_Developer_Guides/06_Testing/index.md index e99799d23..2932e3737 100644 --- a/docs/en/02_Developer_Guides/06_Testing/index.md +++ b/docs/en/02_Developer_Guides/06_Testing/index.md @@ -57,7 +57,7 @@ some `thirdparty/` directories add the following to the `phpunit.xml` configurat framework/dev/ framework/thirdparty/ cms/thirdparty/ - + mysite/thirdparty/ diff --git a/docs/en/02_Developer_Guides/07_Debugging/00_Environment_Types.md b/docs/en/02_Developer_Guides/07_Debugging/00_Environment_Types.md index fd76d4410..fb4e01efd 100644 --- a/docs/en/02_Developer_Guides/07_Debugging/00_Environment_Types.md +++ b/docs/en/02_Developer_Guides/07_Debugging/00_Environment_Types.md @@ -29,13 +29,12 @@ want to password protect the site. You can enable that by adding this to your `m ```yml - - --- - Only: - environment: 'test' - --- - SilverStripe\Security\BasicAuth: - entire_site_protected: true +--- +Only: + environment: 'test' +--- +SilverStripe\Security\BasicAuth: + entire_site_protected: true ``` ### Live Mode @@ -52,32 +51,34 @@ Live sites should always run in live mode. You should not run production website You can check for the current environment type in [config files](../configuration) through the `environment` variant. **mysite/_config/app.yml** + ```yml - --- - Only: - environment: 'live' - --- - MyClass: - myvar: live_value - --- - Only: - environment: 'test' - --- - MyClass: - myvar: test_value +--- +Only: + environment: 'live' +--- +MyClass: + myvar: live_value +--- +Only: + environment: 'test' +--- +MyClass: + myvar: test_value ``` Checking for what environment you're running in can also be done in PHP. Your application code may disable or enable certain functionality depending on the environment type. + ```php - use SilverStripe\Control\Director; - - if (Director::isLive()) { - // is in live - } elseif (Director::isTest()) { - // is in test mode - } elseif (Director::isDev()) { - // is in dev mode - } +use SilverStripe\Control\Director; + +if (Director::isLive()) { + // is in live +} elseif (Director::isTest()) { + // is in test mode +} elseif (Director::isDev()) { + // is in dev mode +} ``` diff --git a/docs/en/02_Developer_Guides/07_Debugging/03_Template_debugging.md b/docs/en/02_Developer_Guides/07_Debugging/03_Template_debugging.md index c032b1311..67daa3cc3 100644 --- a/docs/en/02_Developer_Guides/07_Debugging/03_Template_debugging.md +++ b/docs/en/02_Developer_Guides/07_Debugging/03_Template_debugging.md @@ -10,11 +10,11 @@ to track down a template or two. The template engine can help you along by displ source code comments indicating which template is responsible for rendering each block of html on your page. -```yaml - --- - Only: - environment: 'dev' - --- - SilverStripe\View\SSViewer: - source_file_comments: true -``` \ No newline at end of file +```yml +--- +Only: + environment: 'dev' +--- +SilverStripe\View\SSViewer: + source_file_comments: true +``` diff --git a/docs/en/02_Developer_Guides/07_Debugging/index.md b/docs/en/02_Developer_Guides/07_Debugging/index.md index 884c5900b..db9cf6132 100644 --- a/docs/en/02_Developer_Guides/07_Debugging/index.md +++ b/docs/en/02_Developer_Guides/07_Debugging/index.md @@ -18,17 +18,17 @@ bottle-necks and identify slow moving parts of your application chain. The [Debug](api:SilverStripe\Dev\Debug) class contains a number of static utility methods for more advanced debugging. ```php - use SilverStripe\Dev\Debug; - use SilverStripe\Dev\Backtrace; - - Debug::show($myVariable); - // similar to print_r($myVariable) but shows it in a more useful format. +use SilverStripe\Dev\Debug; +use SilverStripe\Dev\Backtrace; - Debug::message("Wow, that's great"); - // prints a short debugging message. +Debug::show($myVariable); +// similar to print_r($myVariable) but shows it in a more useful format. - Backtrace::backtrace(); - // prints a calls-stack +Debug::message("Wow, that's great"); +// prints a short debugging message. + +Backtrace::backtrace(); +// prints a calls-stack ``` ## API Documentation diff --git a/docs/en/02_Developer_Guides/08_Performance/00_Partial_Caching.md b/docs/en/02_Developer_Guides/08_Performance/00_Partial_Caching.md index 9a597b31f..b3f013c5a 100644 --- a/docs/en/02_Developer_Guides/08_Performance/00_Partial_Caching.md +++ b/docs/en/02_Developer_Guides/08_Performance/00_Partial_Caching.md @@ -4,12 +4,12 @@ summary: Cache SilverStripe templates to reduce database queries. # Partial Caching Partial caching is a feature that allows the caching of just a portion of a page. -```ss - <% cached 'CacheKey' %> +```ss +<% cached 'CacheKey' %> $DataTable ... - <% end_cached %> +<% end_cached %> ``` Each cache block has a cache key. A cache key is an unlimited number of comma separated variables and quoted strings. @@ -23,18 +23,17 @@ Here are some more complex examples: ```ss +<% cached 'database', $LastEdited %> + +<% end_cached %> - <% cached 'database', $LastEdited %> - - <% end_cached %> - - <% cached 'loginblock', $CurrentMember.ID %> - - <% end_cached %> +<% cached 'loginblock', $CurrentMember.ID %> + +<% end_cached %> - <% cached 'loginblock', $LastEdited, $CurrentMember.isAdmin %> - - <% end_cached %> +<% cached 'loginblock', $LastEdited, $CurrentMember.isAdmin %> + +<% end_cached %> ``` An additional global key is incorporated in the cache lookup. The default value for this is @@ -48,10 +47,9 @@ user does not influence your template content, you can update this key as below; **mysite/_config/app.yml** -```yaml - - SilverStripe\View\SSViewer: - global_key: '$CurrentReadingMode, $Locale' +```yml +SilverStripe\View\SSViewer: + global_key: '$CurrentReadingMode, $Locale' ``` ## Aggregates @@ -65,8 +63,7 @@ otherwise. By using aggregates, we do that like this: ```ss - - <% cached 'navigation', $List('SiteTree').max('LastEdited'), $List('SiteTree').count() %> +<% cached 'navigation', $List('SiteTree').max('LastEdited'), $List('SiteTree').count() %> ``` The cache for this will update whenever a page is added, removed or edited. @@ -76,8 +73,7 @@ or edited ```ss - - <% cached 'categorylist', $List('Category').max('LastEdited'), $List('Category').count() %> +<% cached 'categorylist', $List('Category').max('LastEdited'), $List('Category').count() %> ```
      @@ -98,26 +94,24 @@ For example, a block that shows a collection of rotating slides needs to update ```php - public function SliderCacheKey() - { - $fragments = [ - 'Page-Slides', - $this->ID, - // identify which objects are in the list and their sort order - implode('-', $this->Slides()->Column('ID')), - $this->Slides()->max('LastEdited') - ]; - return implode('-_-', $fragments); - } - +public function SliderCacheKey() +{ + $fragments = [ + 'Page-Slides', + $this->ID, + // identify which objects are in the list and their sort order + implode('-', $this->Slides()->Column('ID')), + $this->Slides()->max('LastEdited') + ]; + return implode('-_-', $fragments); +} ``` Then reference that function in the cache key: ```ss - - <% cached $SliderCacheKey %> +<% cached $SliderCacheKey %> ``` The example above would work for both a has_many and many_many relationship. @@ -138,8 +132,7 @@ For instance, if we show some blog statistics, but are happy having them be slig ```ss - - <% cached 'blogstatistics', $Blog.ID %> +<% cached 'blogstatistics', $Blog.ID %> ``` which will invalidate after the cache lifetime expires. If you need more control than that (cache lifetime is @@ -147,10 +140,10 @@ configurable only on a site-wide basis), you could add a special function to you ```php - public function BlogStatisticsCounter() - { - return (int)(time() / 60 / 5); // Returns a new number every five minutes - } +public function BlogStatisticsCounter() +{ + return (int)(time() / 60 / 5); // Returns a new number every five minutes +} ``` @@ -158,8 +151,7 @@ and then use it in the cache key ```ss - - <% cached 'blogstatistics', $Blog.ID, $BlogStatisticsCounter %> +<% cached 'blogstatistics', $Blog.ID, $BlogStatisticsCounter %> ``` ## Cache block conditionals @@ -173,8 +165,7 @@ heavy load: ```ss - - <% cached 'blogstatistics', $Blog.ID if $HighLoad %> +<% cached 'blogstatistics', $Blog.ID if $HighLoad %> ``` By adding a `HighLoad` function to your `PageController`, you could enable or disable caching dynamically. @@ -184,8 +175,7 @@ To cache the contents of a page for all anonymous users, but dynamically calcula ```ss - - <% cached unless $CurrentUser %> +<% cached unless $CurrentUser %> ``` ## Uncached @@ -196,8 +186,7 @@ particular cache block by changing just the tag, leaving the key and conditional ```ss - - <% uncached %> +<% uncached %> ``` ## Nested cache blocks @@ -212,16 +201,15 @@ An example: ```ss - - <% cached $LastEdited %> - Our wonderful site +<% cached $LastEdited %> + Our wonderful site - <% cached $Member.ID %> + <% cached $Member.ID %> Welcome $Member.Name - <% end_cached %> - - $ASlowCalculation <% end_cached %> + + $ASlowCalculation +<% end_cached %> ``` This will cache the entire outer section until the next time the page is edited, but will display a different welcome @@ -232,16 +220,15 @@ could also write the last example as: ```ss - - <% cached $LastEdited %> - Our wonderful site +<% cached $LastEdited %> + Our wonderful site - <% uncached %> + <% uncached %> Welcome $Member.Name - <% end_uncached %> + <% end_uncached %> - $ASlowCalculation - <% end_cached %> + $ASlowCalculation +<% end_cached %> ```
      @@ -253,46 +240,40 @@ Failing example: ```ss +<% cached $LastEdited %> - <% cached $LastEdited %> - - <% loop $Children %> + <% loop $Children %> <% cached $LastEdited %> - $Name + $Name <% end_cached %> - <% end_loop %> - - <% end_cached %> + <% end_loop %> + +<% end_cached %> ``` Can be re-written as: ```ss - - <% cached $LastEdited %> - - <% cached $AllChildren.max('LastEdited') %> +<% cached $LastEdited %> + <% cached $AllChildren.max('LastEdited') %> <% loop $Children %> - $Name + $Name <% end_loop %> - <% end_cached %> - <% end_cached %> +<% end_cached %> ``` Or: - ```ss +<% cached $LastEdited %> + (other code) +<% end_cached %> +<% loop $Children %> <% cached $LastEdited %> - (other code) + $Name <% end_cached %> - - <% loop $Children %> - <% cached $LastEdited %> - $Name - <% end_cached %> - <% end_loop %> +<% end_loop %> ``` diff --git a/docs/en/02_Developer_Guides/08_Performance/01_Caching.md b/docs/en/02_Developer_Guides/08_Performance/01_Caching.md index 36773c715..5812efdc8 100644 --- a/docs/en/02_Developer_Guides/08_Performance/01_Caching.md +++ b/docs/en/02_Developer_Guides/08_Performance/01_Caching.md @@ -32,12 +32,11 @@ and SilverStripe's [dependency injection](/developer-guides/extending/injector) ```yml - - SilverStripe\Core\Injector\Injector: - Psr\SimpleCache\CacheInterface.myCache: - factory: SilverStripe\Core\Cache\CacheFactory - constructor: - namespace: "myCache" +SilverStripe\Core\Injector\Injector: + Psr\SimpleCache\CacheInterface.myCache: + factory: SilverStripe\Core\Cache\CacheFactory + constructor: + namespace: "myCache" ``` Cache objects are instantiated through a [CacheFactory](SilverStripe\Core\Cache\CacheFactory), @@ -46,10 +45,10 @@ This factory allows us you to globally define an adapter for all cache instances ```php - use Psr\SimpleCache\CacheInterface - use SilverStripe\Core\Injector\Injector; +use Psr\SimpleCache\CacheInterface +use SilverStripe\Core\Injector\Injector; - $cache = Injector::inst()->get(CacheInterface::class . '.myCache'); +$cache = Injector::inst()->get(CacheInterface::class . '.myCache'); ``` Caches are namespaced, which might allow granular clearing of a particular cache without affecting others. @@ -67,24 +66,24 @@ Cache objects follow the [PSR-16](http://www.php-fig.org/psr/psr-16/) class inte ```php - use Psr\SimpleCache\CacheInterface; - use SilverStripe\Core\Injector\Injector; +use Psr\SimpleCache\CacheInterface; +use SilverStripe\Core\Injector\Injector; - $cache = Injector::inst()->get(CacheInterface::class . '.myCache'); +$cache = Injector::inst()->get(CacheInterface::class . '.myCache'); - // create a new item by trying to get it from the cache - $myValue = $cache->get('myCacheKey'); - - // set a value and save it via the adapter - $cache->set('myCacheKey', 1234); - - // retrieve the cache item - if (!$cache->has('myCacheKey')) { - // ... item does not exists in the cache - } +// create a new item by trying to get it from the cache +$myValue = $cache->get('myCacheKey'); + +// set a value and save it via the adapter +$cache->set('myCacheKey', 1234); + +// retrieve the cache item +if (!$cache->has('myCacheKey')) { + // ... item does not exists in the cache +} ``` - + ## Invalidation Caches can be invalidated in different ways. The easiest is to actively clear the @@ -93,40 +92,39 @@ this will only affect a subset of cache keys ("myCache" in this example): ```php - use Psr\SimpleCache\CacheInterface; - use SilverStripe\Core\Injector\Injector; +use Psr\SimpleCache\CacheInterface; +use SilverStripe\Core\Injector\Injector; - $cache = Injector::inst()->get(CacheInterface::class . '.myCache'); - - // remove all items in this (namespaced) cache - $cache->clear(); - +$cache = Injector::inst()->get(CacheInterface::class . '.myCache'); + +// remove all items in this (namespaced) cache +$cache->clear(); ``` You can also delete a single item based on it's cache key: ```php - use Psr\SimpleCache\CacheInterface; - use SilverStripe\Core\Injector\Injector; +use Psr\SimpleCache\CacheInterface; +use SilverStripe\Core\Injector\Injector; - $cache = Injector::inst()->get(CacheInterface::class . '.myCache'); - - // remove the cache item - $cache->delete('myCacheKey'); +$cache = Injector::inst()->get(CacheInterface::class . '.myCache'); + +// remove the cache item +$cache->delete('myCacheKey'); ``` Individual cache items can define a lifetime, after which the cached value is marked as expired: ```php - use Psr\SimpleCache\CacheInterface; - use SilverStripe\Core\Injector\Injector; +use Psr\SimpleCache\CacheInterface; +use SilverStripe\Core\Injector\Injector; - $cache = Injector::inst()->get(CacheInterface::class . '.myCache'); - - // remove the cache item - $cache->set('myCacheKey', 'myValue', 300); // cache for 300 seconds +$cache = Injector::inst()->get(CacheInterface::class . '.myCache'); + +// remove the cache item +$cache->set('myCacheKey', 'myValue', 300); // cache for 300 seconds ``` If a lifetime isn't defined on the `set()` call, it'll use the adapter default. @@ -138,11 +136,10 @@ you need to be careful with resources here (e.g. filesystem space). ```yml - - SilverStripe\Core\Injector\Injector: - Psr\SimpleCache\CacheInterface.cacheblock: - constructor: - defaultLifetime: 3600 +SilverStripe\Core\Injector\Injector: + Psr\SimpleCache\CacheInterface.cacheblock: + constructor: + defaultLifetime: 3600 ``` In most cases, invalidation and expiry should be handled by your cache key. @@ -154,14 +151,14 @@ old cache keys will be garbage collected as the cache fills up. ```php - use Psr\SimpleCache\CacheInterface; - use SilverStripe\Core\Injector\Injector; - - $cache = Injector::inst()->get(CacheInterface::class . '.myCache'); - - // Automatically changes when any group is edited - $cacheKey = implode(['groupNames', $member->ID, Group::get()->max('LastEdited')]); - $cache->set($cacheKey, $member->Groups()->column('Title')); +use Psr\SimpleCache\CacheInterface; +use SilverStripe\Core\Injector\Injector; + +$cache = Injector::inst()->get(CacheInterface::class . '.myCache'); + +// Automatically changes when any group is edited +$cacheKey = implode(['groupNames', $member->ID, Group::get()->max('LastEdited')]); +$cache->set($cacheKey, $member->Groups()->column('Title')); ``` If `?flush=1` is requested in the URL, this will trigger a call to `flush()` on @@ -196,20 +193,19 @@ and takes a `MemcachedClient` instance as a constructor argument. ```yml - - --- - After: - - '#corecache' - --- - SilverStripe\Core\Injector\Injector: - MemcachedClient: - class: 'Memcached' - calls: - - [ addServer, [ 'localhost', 11211 ] ] - SilverStripe\Core\Cache\CacheFactory: - class: 'SilverStripe\Core\Cache\MemcachedCacheFactory' - constructor: - client: '%$MemcachedClient +--- +After: + - '#corecache' +--- +SilverStripe\Core\Injector\Injector: + MemcachedClient: + class: 'Memcached' + calls: + - [ addServer, [ 'localhost', 11211 ] ] + SilverStripe\Core\Cache\CacheFactory: + class: 'SilverStripe\Core\Cache\MemcachedCacheFactory' + constructor: + client: '%$MemcachedClient ``` ## Additional Caches diff --git a/docs/en/02_Developer_Guides/08_Performance/02_HTTP_Cache_Headers.md b/docs/en/02_Developer_Guides/08_Performance/02_HTTP_Cache_Headers.md index 87beb5e00..bb3df73c5 100644 --- a/docs/en/02_Developer_Guides/08_Performance/02_HTTP_Cache_Headers.md +++ b/docs/en/02_Developer_Guides/08_Performance/02_HTTP_Cache_Headers.md @@ -17,10 +17,11 @@ headers: ## Customizing Cache Headers ### HTTP::set_cache_age -```php - use SilverStripe\Control\HTTP; - HTTP::set_cache_age(0); +```php +use SilverStripe\Control\HTTP; + +HTTP::set_cache_age(0); ``` Used to set the max-age component of the cache-control line, in seconds. Set it to 0 to disable caching; the "no-cache" @@ -30,7 +31,7 @@ clause in `Cache-Control` and `Pragma` will be included. ```php - HTTP::register_modification_date('2014-10-10'); +HTTP::register_modification_date('2014-10-10'); ``` Used to set the modification date to something more recent than the default. [DataObject::__construct](api:SilverStripe\ORM\DataObject::__construct) calls @@ -51,7 +52,3 @@ To change the value of the `Vary` header, you can change this value by specifyin SilverStripe\Control\HTTP: vary: "" ``` - - - - diff --git a/docs/en/02_Developer_Guides/08_Performance/05_Resource_Usage.md b/docs/en/02_Developer_Guides/08_Performance/05_Resource_Usage.md index 3a1706f50..40d26a93d 100644 --- a/docs/en/02_Developer_Guides/08_Performance/05_Resource_Usage.md +++ b/docs/en/02_Developer_Guides/08_Performance/05_Resource_Usage.md @@ -24,10 +24,10 @@ SilverStripe can request more resources through `Environment::increaseMemoryLimi
      ```php - use SilverStripe\Core\Environment; - - public function myBigFunction() - { - Environment::increaseTimeLimitTo(400); - } -``` \ No newline at end of file +use SilverStripe\Core\Environment; + +public function myBigFunction() +{ + Environment::increaseTimeLimitTo(400); +} +``` diff --git a/docs/en/02_Developer_Guides/09_Security/00_Member.md b/docs/en/02_Developer_Guides/09_Security/00_Member.md index ca5cefaa4..cc435ecce 100644 --- a/docs/en/02_Developer_Guides/09_Security/00_Member.md +++ b/docs/en/02_Developer_Guides/09_Security/00_Member.md @@ -15,13 +15,13 @@ The [api:Security] class comes with a static method for getting information abou Retrieves the current logged in member. Returns *null* if user is not logged in, otherwise, the Member object is returned. ```php - use SilverStripe\Security\Security; +use SilverStripe\Security\Security; - if( $member = Security::getCurrentUser() ) { - // Work with $member - } else { - // Do non-member stuff - } +if( $member = Security::getCurrentUser() ) { + // Work with $member +} else { + // Do non-member stuff +} ``` ## Subclassing @@ -49,8 +49,8 @@ To ensure that all new members are created using this class, put a call to [api: ```yml SilverStripe\Core\Injector\Injector: - SilverStripe\Security\Member: - class: MyVendor\MyNamespace\MyMemberClass + SilverStripe\Security\Member: + class: MyVendor\MyNamespace\MyMemberClass ``` Note that if you want to look this class-name up, you can call `Injector::inst()->get('Member')->ClassName` @@ -62,15 +62,15 @@ details in the newsletter system. This function returns a [FieldList](api:Silve parent::getCMSFields() and manipulate the [FieldList](api:SilverStripe\Forms\FieldList) from there. ```php - use SilverStripe\Forms\TextField; - - public function getCMSFields() { - $fields = parent::getCMSFields(); - $fields->insertBefore("HTMLEmail", new TextField("Age")); - $fields->removeByName("JobTitle"); - $fields->removeByName("Organisation"); - return $fields; - } +use SilverStripe\Forms\TextField; + +public function getCMSFields() { + $fields = parent::getCMSFields(); + $fields->insertBefore("HTMLEmail", new TextField("Age")); + $fields->removeByName("JobTitle"); + $fields->removeByName("Organisation"); + return $fields; +} ``` ## Extending Member or DataObject? @@ -105,7 +105,6 @@ use SilverStripe\ORM\DataExtension; class MyMemberExtension extends DataExtension { /** - * Modify the field set to be displayed in the CMS detail pop-up */ public function updateCMSFields(FieldList $currentFields) @@ -156,8 +155,6 @@ reasonably be expected to be allowed to do. E.g. - - ```php use SilverStripe\Control\Director; use SilverStripe\Security\Security; diff --git a/docs/en/02_Developer_Guides/09_Security/03_Authentication.md b/docs/en/02_Developer_Guides/09_Security/03_Authentication.md index e4d2d4f44..ba9140871 100644 --- a/docs/en/02_Developer_Guides/09_Security/03_Authentication.md +++ b/docs/en/02_Developer_Guides/09_Security/03_Authentication.md @@ -8,7 +8,7 @@ authentication system. The main login system uses these controllers to handle the various security requests: -[Security](api:SilverStripe\Security\Security) - Which is the controller which handles most front-end security requests, including logging in, logging out, resetting password, or changing password. This class also provides an interface to allow configured [Authenticator](api:SilverStripe\Security\Authenticator) classes to each display a custom login form. +[Security](api:SilverStripe\Security\Security) - Which is the controller which handles most front-end security requests, including logging in, logging out, resetting password, or changing password. This class also provides an interface to allow configured [Authenticator](api:SilverStripe\Security\Authenticator) classes to each display a custom login form. [CMSSecurity](api:SilverStripe\Security\CMSSecurity) - Which is the controller which handles security requests within the CMS, and allows users to re-login without leaving the CMS. @@ -16,7 +16,7 @@ The main login system uses these controllers to handle the various security requ The default member authentication system is implemented in the following classes: -[MemberAuthenticator](api:SilverStripe\Security\MemberAuthenticator) - Which is the default member authentication implementation. This uses the email and password stored internally for each member to authenticate them. +[MemberAuthenticator](api:SilverStripe\Security\MemberAuthenticator) - Which is the default member authentication implementation. This uses the email and password stored internally for each member to authenticate them. [MemberLoginForm](api:SilverStripe\Security\MemberAuthenticator\MemberLoginForm) - Is the default form used by `MemberAuthenticator`, and is displayed on the public site at the url `Security/login` by default. @@ -38,11 +38,13 @@ CMS access for the first time. SilverStripe provides a default admin configurati and password to be configured for a single special user outside of the normal membership system. It is advisable to configure this user in your `.env` file inside of the web root, as below: + ``` - # Configure a default username and password to access the CMS on all sites in this environment. - SS_DEFAULT_ADMIN_USERNAME="admin" - SS_DEFAULT_ADMIN_PASSWORD="password" +# Configure a default username and password to access the CMS on all sites in this environment. +SS_DEFAULT_ADMIN_USERNAME="admin" +SS_DEFAULT_ADMIN_PASSWORD="password" ``` + When a user logs in with these credentials, then a [Member](api:SilverStripe\Security\Member) with the Email 'admin' will be generated in the database, but without any password information. This means that the password can be reset or changed by simply updating the `.env` file. @@ -68,24 +70,24 @@ SilverStripe\Core\Injector\Injector: By default, the `SilverStripe\Security\MemberAuthenticator\MemberAuthenticator` is seen as the default authenticator until it's explicitly set in the config. Every Authenticator is expected to handle services. The `Authenticator` Interface provides the available services: + ```php +const LOGIN = 1; +const LOGOUT = 2; +const CHANGE_PASSWORD = 4; +const RESET_PASSWORD = 8; +const CMS_LOGIN = 16; - const LOGIN = 1; - const LOGOUT = 2; - const CHANGE_PASSWORD = 4; - const RESET_PASSWORD = 8; - const CMS_LOGIN = 16; - - /** - * Returns the services supported by this authenticator - * - * The number should be a bitwise-OR of 1 or more of the following constants: - * Authenticator::LOGIN, Authenticator::LOGOUT, Authenticator::CHANGE_PASSWORD, - * Authenticator::RESET_PASSWORD, or Authenticator::CMS_LOGIN - * - * @return int - */ - public function supportedServices(); +/** + * Returns the services supported by this authenticator + * + * The number should be a bitwise-OR of 1 or more of the following constants: + * Authenticator::LOGIN, Authenticator::LOGOUT, Authenticator::CHANGE_PASSWORD, + * Authenticator::RESET_PASSWORD, or Authenticator::CMS_LOGIN + * + * @return int + */ +public function supportedServices(); ``` If there is no available authenticator for the required action (either one of the constants above), an error will be thrown. diff --git a/docs/en/02_Developer_Guides/09_Security/04_Secure_Coding.md b/docs/en/02_Developer_Guides/09_Security/04_Secure_Coding.md index 5b77a3362..e11507cf8 100644 --- a/docs/en/02_Developer_Guides/09_Security/04_Secure_Coding.md +++ b/docs/en/02_Developer_Guides/09_Security/04_Secure_Coding.md @@ -25,43 +25,42 @@ must still be taken when working with literal values or table/column identifiers come from user input. Example: + ```php - use SilverStripe\ORM\DB; - use SilverStripe\ORM\DataObject; - use SilverStripe\ORM\Queries\SQLSelect; - - $records = DB::prepared_query('SELECT * FROM "MyClass" WHERE "ID" = ?', [3]); - $records = MyClass::get()->where(['"ID" = ?' => 3]); - $records = MyClass::get()->where(['"ID"' => 3]); - $records = DataObject::get_by_id('MyClass', 3); - $records = DataObject::get_one('MyClass', ['"ID" = ?' => 3]); - $records = MyClass::get()->byID(3); - $records = SQLSelect::create()->addWhere(['"ID"' => 3])->execute(); +use SilverStripe\ORM\DB; +use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\Queries\SQLSelect; +$records = DB::prepared_query('SELECT * FROM "MyClass" WHERE "ID" = ?', [3]); +$records = MyClass::get()->where(['"ID" = ?' => 3]); +$records = MyClass::get()->where(['"ID"' => 3]); +$records = DataObject::get_by_id('MyClass', 3); +$records = DataObject::get_one('MyClass', ['"ID" = ?' => 3]); +$records = MyClass::get()->byID(3); +$records = SQLSelect::create()->addWhere(['"ID"' => 3])->execute(); ``` Parameterised updates and inserts are also supported, but the syntax is a little different ```php - use SilverStripe\ORM\Queries\SQLInsert; - use SilverStripe\ORM\DB; - - SQLInsert::create('"MyClass"') - ->assign('"Name"', 'Daniel') - ->addAssignments([ - '"Position"' => 'Accountant', - '"Age"' => [ - 'GREATEST(0,?,?)' => [24, 28] - ] - ]) - ->assignSQL('"Created"', 'NOW()') - ->execute(); - DB::prepared_query( - 'INSERT INTO "MyClass" ("Name", "Position", "Age", "Created") VALUES(?, ?, GREATEST(0,?,?), NOW())' - ['Daniel', 'Accountant', 24, 28] - ); +use SilverStripe\ORM\Queries\SQLInsert; +use SilverStripe\ORM\DB; +SQLInsert::create('"MyClass"') + ->assign('"Name"', 'Daniel') + ->addAssignments([ + '"Position"' => 'Accountant', + '"Age"' => [ + 'GREATEST(0,?,?)' => [24, 28] + ] + ]) + ->assignSQL('"Created"', 'NOW()') + ->execute(); +DB::prepared_query( + 'INSERT INTO "MyClass" ("Name", "Position", "Age", "Created") VALUES(?, ?, GREATEST(0,?,?), NOW())' + ['Daniel', 'Accountant', 24, 28] +); ``` ### Automatic escaping @@ -86,18 +85,18 @@ Data is not escaped when writing to object-properties, as inserts and updates ar handled via prepared statements. Example: + ```php - use SilverStripe\Security\Member; - - // automatically escaped/quoted - $members = Member::get()->filter('Name', $_GET['name']); - // automatically escaped/quoted - $members = Member::get()->filter(['Name' => $_GET['name']]); - // parameterised condition - $members = Member::get()->where(['"Name" = ?' => $_GET['name']]); - // needs to be escaped and quoted manually (note raw2sql called with the $quote parameter set to true) - $members = Member::get()->where(sprintf('"Name" = %s', Convert::raw2sql($_GET['name'], true))); +use SilverStripe\Security\Member; +// automatically escaped/quoted +$members = Member::get()->filter('Name', $_GET['name']); +// automatically escaped/quoted +$members = Member::get()->filter(['Name' => $_GET['name']]); +// parameterised condition +$members = Member::get()->where(['"Name" = ?' => $_GET['name']]); +// needs to be escaped and quoted manually (note raw2sql called with the $quote parameter set to true) +$members = Member::get()->where(sprintf('"Name" = %s', Convert::raw2sql($_GET['name'], true))); ```
      @@ -123,19 +122,19 @@ Example: ```php - use SilverStripe\Core\Convert; - use SilverStripe\Forms\Form; +use SilverStripe\Core\Convert; +use SilverStripe\Forms\Form; - class MyForm extends Form +class MyForm extends Form +{ + public function save($RAW_data, $form) { - public function save($RAW_data, $form) - { - // Pass true as the second parameter of raw2sql to quote the value safely - $SQL_data = Convert::raw2sql($RAW_data, true); // works recursively on an array - $objs = Player::get()->where("Name = " . $SQL_data['name']); + // Pass true as the second parameter of raw2sql to quote the value safely + $SQL_data = Convert::raw2sql($RAW_data, true); // works recursively on an array + $objs = Player::get()->where("Name = " . $SQL_data['name']); // ... - } } +} ``` @@ -144,23 +143,21 @@ Example: Example: - ```php - use SilverStripe\Core\Convert; - use SilverStripe\Control\Controller; +use SilverStripe\Core\Convert; +use SilverStripe\Control\Controller; - class MyController extends Controller +class MyController extends Controller +{ + private static $allowed_actions = ['myurlaction']; + public function myurlaction($RAW_urlParams) { - private static $allowed_actions = ['myurlaction']; - public function myurlaction($RAW_urlParams) - { - // Pass true as the second parameter of raw2sql to quote the value safely - $SQL_urlParams = Convert::raw2sql($RAW_urlParams, true); // works recursively on an array - $objs = Player::get()->where("Name = " . $SQL_data['OtherID']); + // Pass true as the second parameter of raw2sql to quote the value safely + $SQL_urlParams = Convert::raw2sql($RAW_urlParams, true); // works recursively on an array + $objs = Player::get()->where("Name = " . $SQL_data['OtherID']); // ... - } } - +} ``` As a rule of thumb, you should escape your data **as close to querying as possible** @@ -169,28 +166,27 @@ passing data through, escaping should happen at the end of the chain. ```php - use SilverStripe\Core\Convert; - use SilverStripe\ORM\DB; - use SilverStripe\Control\Controller; +use SilverStripe\Core\Convert; +use SilverStripe\ORM\DB; +use SilverStripe\Control\Controller; - class MyController extends Controller +class MyController extends Controller +{ + /** + * @param array $RAW_data All names in an indexed array (not SQL-safe) + */ + public function saveAllNames($RAW_data) { - /** - * @param array $RAW_data All names in an indexed array (not SQL-safe) - */ - public function saveAllNames($RAW_data) - { // $SQL_data = Convert::raw2sql($RAW_data); // premature escaping foreach($RAW_data as $item) $this->saveName($item); - } - - public function saveName($RAW_name) - { - $SQL_name = Convert::raw2sql($RAW_name, true); - DB::query("UPDATE Player SET Name = {$SQL_name}"); - } } + public function saveName($RAW_name) + { + $SQL_name = Convert::raw2sql($RAW_name, true); + DB::query("UPDATE Player SET Name = {$SQL_name}"); + } +} ``` This might not be applicable in all cases - especially if you are building an API thats likely to be customised. If @@ -225,9 +221,11 @@ stripped out To enable filtering, set the HtmlEditorField::$sanitise_server_side [configuration](/developer_guides/configuration/configuration) property to true, e.g. + ``` - HtmlEditorField::config()->sanitise_server_side = true +HtmlEditorField::config()->sanitise_server_side = true ``` + The built in sanitiser enforces the TinyMCE whitelist rules on the server side, and is sufficient to eliminate the most common XSS vectors. @@ -257,15 +255,15 @@ PHP: ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyObject extends DataObject - { - private static $db = [ +class MyObject extends DataObject +{ + private static $db = [ 'MyEscapedValue' => 'Text', // Example value: not bold 'MyUnescapedValue' => 'HTMLText' // Example value: bold - ]; - } + ]; +} ``` @@ -273,10 +271,10 @@ Template: ```php -
        -
      • $MyEscapedValue
      • // output: <b>not bold<b> -
      • $MyUnescapedValue
      • // output: bold -
      +
        +
      • $MyEscapedValue
      • // output: <b>not bold<b> +
      • $MyUnescapedValue
      • // output: bold +
      ``` The example below assumes that data wasn't properly filtered when saving to the database, but are escaped before @@ -291,13 +289,13 @@ Template (see above): ```php -
        - // output: foo & "bar" -
      • $Title
      • -
      • $MyEscapedValue
      • // output: <b>not bold<b> -
      • $MyUnescapedValue
      • // output: bold -
      • $MyUnescapedValue.XML
      • // output: <b>bold<b> -
      +
        + // output: foo & "bar" +
      • $Title
      • +
      • $MyEscapedValue
      • // output: <b>not bold<b> +
      • $MyUnescapedValue
      • // output: bold +
      • $MyUnescapedValue.XML
      • // output: <b>bold<b> +
      ``` ### Escaping custom attributes and getters @@ -307,37 +305,35 @@ static *$casting* array. Caution: Casting only applies when using values in a te PHP: - ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyObject extends DataObject +class MyObject extends DataObject +{ + public $Title = 'not bold'; // will be escaped due to Text casting + + $casting = [ + "Title" => "Text", // forcing a casting + 'TitleWithHTMLSuffix' => 'HTMLText' // optional, as HTMLText is the default casting + ]; + + public function TitleWithHTMLSuffix($suffix) { - public $Title = 'not bold'; // will be escaped due to Text casting - - $casting = [ - "Title" => "Text", // forcing a casting - 'TitleWithHTMLSuffix' => 'HTMLText' // optional, as HTMLText is the default casting - ]; - - public function TitleWithHTMLSuffix($suffix) - { - // $this->Title is not casted in PHP - return $this->Title . '(' . $suffix. ')'; - } + // $this->Title is not casted in PHP + return $this->Title . '(' . $suffix. ')'; } - +} ``` Template: ```php -
        -
      • $Title
      • // output: <b>not bold<b> -
      • $Title.RAW
      • // output: not bold -
      • $TitleWithHTMLSuffix
      • // output: not bold: (...) -
      +
        +
      • $Title
      • // output: <b>not bold<b> +
      • $Title.RAW
      • // output: not bold +
      • $TitleWithHTMLSuffix
      • // output: not bold: (...) +
      ``` Note: Avoid generating HTML by string concatenation in PHP wherever possible to minimize risk and separate your @@ -353,33 +349,30 @@ also used by *XML* and *ATT* in template code). PHP: - ```php - use SilverStripe\Core\Convert; - use SilverStripe\Control\Controller; - use SilverStripe\ORM\FieldType\DBText; - use SilverStripe\ORM\FieldType\DBHTMLText; +use SilverStripe\Core\Convert; +use SilverStripe\Control\Controller; +use SilverStripe\ORM\FieldType\DBText; +use SilverStripe\ORM\FieldType\DBHTMLText; - class MyController extends Controller +class MyController extends Controller +{ + private static $allowed_actions = ['search']; + public function search($request) { - private static $allowed_actions = ['search']; - public function search($request) - { - $htmlTitle = '

      Your results for:' . Convert::raw2xml($request->getVar('Query')) . '

      '; - return $this->customise([ - 'Query' => DBText::create($request->getVar('Query')), - 'HTMLTitle' => DBHTMLText::create($htmlTitle) - ]); - } + $htmlTitle = '

      Your results for:' . Convert::raw2xml($request->getVar('Query')) . '

      '; + return $this->customise([ + 'Query' => DBText::create($request->getVar('Query')), + 'HTMLTitle' => DBHTMLText::create($htmlTitle) + ]); } - +} ``` Template: - ```php -

      $HTMLTitle

      +

      $HTMLTitle

      ``` Whenever you insert a variable into an HTML attribute within a template, use $VarName.ATT, no not $VarName. @@ -395,29 +388,28 @@ PHP: ```php - use SilverStripe\Control\Controller; - use SilverStripe\ORM\FieldType\DBText; +use SilverStripe\Control\Controller; +use SilverStripe\ORM\FieldType\DBText; - class MyController extends Controller +class MyController extends Controller +{ + private static $allowed_actions = ['search']; + public function search($request) { - private static $allowed_actions = ['search']; - public function search($request) - { - $rssRelativeLink = "/rss?Query=" . urlencode($_REQUEST['query']) . "&sortOrder=asc"; - $rssLink = Controller::join_links($this->Link(), $rssRelativeLink); - return $this->customise([ - "RSSLink" => DBText::create($rssLink), - ]); - } + $rssRelativeLink = "/rss?Query=" . urlencode($_REQUEST['query']) . "&sortOrder=asc"; + $rssLink = Controller::join_links($this->Link(), $rssRelativeLink); + return $this->customise([ + "RSSLink" => DBText::create($rssLink), + ]); } - +} ``` Template: ```php - RSS feed +RSS feed ``` Some rules of thumb: @@ -466,21 +458,21 @@ Below is an example with different ways you would use this casting technique: ```php - public function CaseStudies() - { +public function CaseStudies() +{ + + // cast an ID from URL parameters e.g. (mysite.com/home/action/ID) + $anotherID = (int)Director::urlParam['ID']; - // cast an ID from URL parameters e.g. (mysite.com/home/action/ID) - $anotherID = (int)Director::urlParam['ID']; + // perform a calculation, the prerequisite being $anotherID must be an integer + $calc = $anotherID + (5 - 2) / 2; - // perform a calculation, the prerequisite being $anotherID must be an integer - $calc = $anotherID + (5 - 2) / 2; + // cast the 'category' GET variable as an integer + $categoryID = (int)$_GET['category']; - // cast the 'category' GET variable as an integer - $categoryID = (int)$_GET['category']; - - // perform a byID(), which ensures the ID is an integer before querying - return CaseStudy::get()->byID($categoryID); - } + // perform a byID(), which ensures the ID is an integer before querying + return CaseStudy::get()->byID($categoryID); +} ``` The same technique can be employed anywhere in your PHP code you know something must be of a certain type. A list of PHP @@ -512,13 +504,14 @@ with a `.yml` or `.yaml` extension through the default web server rewriting rule If you need users to access files with this extension, you can bypass the rules for a specific directory. Here's an example for a `.htaccess` file used by the Apache web server: -``` - - Order allow,deny - Allow from all - ``` + + Order allow,deny + Allow from all + +``` + ### User uploaded files Certain file types are by default excluded from user upload. html, xhtml, htm, and xml files may have embedded, @@ -540,7 +533,6 @@ take the following precautions: [Cookie Law and Flash Cookies](http://eucookiedirective.com/cookie-law-and-flash-cookies/). See [the Adobe Flash security page](http://www.adobe.com/devnet/flashplayer/security.html) for more information. - ADMIN privileged users may be allowed to override the above upload restrictions if the `File.apply_restrictions_to_admin` config is set to false. By default this is true, which enforces these @@ -564,15 +556,14 @@ a [PasswordValidator](api:SilverStripe\Security\PasswordValidator): ```php - use SilverStripe\Security\Member; - use SilverStripe\Security\PasswordValidator; - - $validator = new PasswordValidator(); - $validator->minLength(7); - $validator->checkHistoricalPasswords(6); - $validator->characterStrength(3, ["lowercase", "uppercase", "digits", "punctuation"]); - Member::set_password_validator($validator); +use SilverStripe\Security\Member; +use SilverStripe\Security\PasswordValidator; +$validator = new PasswordValidator(); +$validator->minLength(7); +$validator->checkHistoricalPasswords(6); +$validator->characterStrength(3, ["lowercase", "uppercase", "digits", "punctuation"]); +Member::set_password_validator($validator); ``` In addition, you can tighten password security with the following configuration settings: @@ -597,16 +588,16 @@ controller's `init()` method: ```php - use SilverStripe\Control\Controller; +use SilverStripe\Control\Controller; - class MyController extends Controller +class MyController extends Controller +{ + public function init() { - public function init() - { - parent::init(); - $this->getResponse()->addHeader('X-Frame-Options', 'SAMEORIGIN'); - } + parent::init(); + $this->getResponse()->addHeader('X-Frame-Options', 'SAMEORIGIN'); } +} ``` This is a recommended option to secure any controller which displays @@ -619,9 +610,11 @@ To prevent a forged hostname appearing being used by the application, SilverStri allows the configure of a whitelist of hosts that are allowed to access the system. By defining this whitelist in your `.env` file, any request presenting a `Host` header that is _not_ in this list will be blocked with a HTTP 400 error: + ``` - SS_ALLOWED_HOSTS="www.mysite.com,mysite.com,subdomain.mysite.com" +SS_ALLOWED_HOSTS="www.mysite.com,mysite.com,subdomain.mysite.com" ``` + Please note that if this configuration is defined, you _must_ include _all_ subdomains (eg www.) that will be accessing the site. @@ -636,24 +629,27 @@ into visiting external sites. In order to prevent this kind of attack, it's necessary to whitelist trusted proxy server IPs using the SS_TRUSTED_PROXY_IPS define in your `.env`. + ``` - SS_TRUSTED_PROXY_IPS="127.0.0.1,192.168.0.1" +SS_TRUSTED_PROXY_IPS="127.0.0.1,192.168.0.1" ``` + If you wish to change the headers that are used to find the proxy information, you should reconfigure the TrustedProxyMiddleware service: ```yml +SilverStripe\Control\TrustedProxyMiddleware: + properties: + ProxyHostHeaders: X-Forwarded-Host + ProxySchemeHeaders: X-Forwarded-Protocol + ProxyIPHeaders: X-Forwarded-Ip +``` - SilverStripe\Control\TrustedProxyMiddleware: - properties: - ProxyHostHeaders: X-Forwarded-Host - ProxySchemeHeaders: X-Forwarded-Protocol - ProxyIPHeaders: X-Forwarded-Ip - - SS_TRUSTED_PROXY_HOST_HEADER="HTTP_X_FORWARDED_HOST" - SS_TRUSTED_PROXY_IP_HEADER="HTTP_X_FORWARDED_FOR" - SS_TRUSTED_PROXY_PROTOCOL_HEADER="HTTP_X_FORWARDED_PROTOCOL" +``` +SS_TRUSTED_PROXY_HOST_HEADER="HTTP_X_FORWARDED_HOST" +SS_TRUSTED_PROXY_IP_HEADER="HTTP_X_FORWARDED_FOR" +SS_TRUSTED_PROXY_PROTOCOL_HEADER="HTTP_X_FORWARDED_PROTOCOL" ``` At the same time, you'll also need to define which headers you trust from these proxy IPs. Since there are multiple ways through which proxies can pass through HTTP information on the original hostname, IP and protocol, these values need to be adjusted for your specific proxy. The header names match their equivalent `$_SERVER` values. @@ -667,12 +663,12 @@ This behaviour is enabled whenever `SS_TRUSTED_PROXY_IPS` is defined, or if the following in your .htaccess to ensure this behaviour is activated. ``` - - # Ensure that X-Forwarded-Host is only allowed to determine the request - # hostname for servers ips defined by SS_TRUSTED_PROXY_IPS in your .env - # Note that in a future release this setting will be always on. - SetEnv BlockUntrustedIPs true - + + # Ensure that X-Forwarded-Host is only allowed to determine the request + # hostname for servers ips defined by SS_TRUSTED_PROXY_IPS in your .env + # Note that in a future release this setting will be always on. + SetEnv BlockUntrustedIPs true + ``` In a future release this behaviour will be changed to be on by default, and this environment @@ -683,12 +679,13 @@ variable will be no longer necessary, thus it will be necessary to always set SilverStripe recommends the use of TLS(HTTPS) for your application, and you can easily force the use through the director function `forceSSL()` -```php - use SilverStripe\Control\Director; - if (!Director::isDev()) { - Director::forceSSL(); - } +```php +use SilverStripe\Control\Director; + +if (!Director::isDev()) { + Director::forceSSL(); +} ``` Forcing HTTPS so requires a certificate to be purchased or obtained through a vendor such as @@ -697,10 +694,10 @@ Forcing HTTPS so requires a certificate to be purchased or obtained through a ve We also want to ensure cookies are not shared between secure and non-secure sessions, so we must tell SilverStripe to use a [secure session](https://docs.silverstripe.org/en/3/developer_guides/cookies_and_sessions/sessions/#secure-session-cookie). To do this, you may set the `cookie_secure` parameter to `true` in your `config.yml` for `Session` -```yml - SilverStripe\Control\Session: - cookie_secure: true +```yml +SilverStripe\Control\Session: + cookie_secure: true ``` For other cookies set by your application we should also ensure the users are provided with secure cookies by setting @@ -713,12 +710,13 @@ clear text and can be intercepted and stolen by an attacker who is listening on - The `HTTPOnly` flag lets the browser know whether or not a cookie should be accessible by client-side JavaScript code. It is best practice to set this flag unless the application is known to use JavaScript to access these cookies as this prevents an attacker who achieves cross-site scripting from accessing these cookies. + ```php - use SilverStripe\Control\Cookie; - - Cookie::set('cookie-name', 'chocolate-chip', $expiry = 30, $path = null, $domain = null, $secure = true, - $httpOnly = false - ); +use SilverStripe\Control\Cookie; + +Cookie::set('cookie-name', 'chocolate-chip', $expiry = 30, $path = null, $domain = null, $secure = true, + $httpOnly = false +); ``` ## Security Headers @@ -730,9 +728,9 @@ ensuring an HTTPS connection will provide a better and more secure user experien - The `Strict-Transport-Security` header instructs the browser to record that the website and assets on that website MUST use a secure connection. This prevents websites from becoming insecure in the future from stray absolute links or references without https from external sites. Check if your browser supports [HSTS](https://hsts.badssl.com/) - - `max-age` can be configured to anything in seconds: `max-age=31536000` (1 year), for roll out, consider something +- `max-age` can be configured to anything in seconds: `max-age=31536000` (1 year), for roll out, consider something lower - - `includeSubDomains` to ensure all present and future sub domains will also be HTTPS +- `includeSubDomains` to ensure all present and future sub domains will also be HTTPS For sensitive pages, such as members areas, or places where sensitive information is present, adding cache control headers can explicitly instruct browsers not to keep a local cached copy of content and can prevent content from @@ -744,27 +742,27 @@ unauthorised local persons. SilverStripe adds the current date for every request headers to the request for our secure controllers: ```php - use SilverStripe\Control\HTTP; - use SilverStripe\Control\Controller; +use SilverStripe\Control\HTTP; +use SilverStripe\Control\Controller; - class MySecureController extends Controller +class MySecureController extends Controller +{ + + public function init() { + parent::init(); - public function init() - { - parent::init(); - - // Add cache headers to ensure sensitive content isn't cached. - $this->response->addHeader('Cache-Control', 'max-age=0, must-revalidate, no-transform'); - $this->response->addHeader('Pragma', 'no-cache'); // for HTTP 1.0 support + // Add cache headers to ensure sensitive content isn't cached. + $this->response->addHeader('Cache-Control', 'max-age=0, must-revalidate, no-transform'); + $this->response->addHeader('Pragma', 'no-cache'); // for HTTP 1.0 support - HTTP::set_cache_age(0); - HTTP::add_cache_headers($this->response); - - // Add HSTS header to force TLS for document content - $this->response->addHeader('Strict-Transport-Security', 'max-age=86400; includeSubDomains'); - } + HTTP::set_cache_age(0); + HTTP::add_cache_headers($this->response); + + // Add HSTS header to force TLS for document content + $this->response->addHeader('Strict-Transport-Security', 'max-age=86400; includeSubDomains'); } +} ``` ## Related diff --git a/docs/en/02_Developer_Guides/10_Email/index.md b/docs/en/02_Developer_Guides/10_Email/index.md index a2e404eff..4261e490c 100644 --- a/docs/en/02_Developer_Guides/10_Email/index.md +++ b/docs/en/02_Developer_Guides/10_Email/index.md @@ -24,10 +24,10 @@ SilverStripe\Core\Injector\Injector: ```php - use SilverStripe\Control\Email\Email; +use SilverStripe\Control\Email\Email; - $email = new Email($from, $to, $subject, $body); - $email->sendPlain(); +$email = new Email($from, $to, $subject, $body); +$email->sendPlain(); ``` ### Sending combined HTML and plain text @@ -38,8 +38,8 @@ to `*text*`). ```php - $email = new Email($from, $to, $subject, $body); - $email->send(); +$email = new Email($from, $to, $subject, $body); +$email->send(); ```
      @@ -58,9 +58,8 @@ email object additional information using the `setData` and `addData` methods. ```ss - -

      Hi $Member.FirstName

      -

      You can go to $Link.

      +

      Hi $Member.FirstName

      +

      You can go to $Link.

      ``` The PHP Logic.. @@ -109,10 +108,8 @@ You can set the default sender address of emails through the `Email.admin_email` ```yaml - - SilverStripe\Control\Email\Email: - admin_email: support@silverstripe.org - +SilverStripe\Control\Email\Email: + admin_email: support@silverstripe.org ```
      @@ -135,15 +132,14 @@ Configuration of those properties looks like the following: **mysite/_config.php** - ```php - use SilverStripe\Control\Director; - use SilverStripe\Core\Config\Config; - if(Director::isLive()) { - Config::inst()->update('Email', 'bcc_all_emails_to', "client@example.com"); - } else { - Config::inst()->update('Email', 'send_all_emails_to', "developer@example.com"); - } +use SilverStripe\Control\Director; +use SilverStripe\Core\Config\Config; +if(Director::isLive()) { + Config::inst()->update('Email', 'bcc_all_emails_to', "client@example.com"); +} else { + Config::inst()->update('Email', 'send_all_emails_to', "developer@example.com"); +} ``` ### Setting custom "Reply To" email address. @@ -152,9 +148,10 @@ For email messages that should have an email address which is replied to that ac email, do the following. This is encouraged especially when the domain responsible for sending the message isn't necessarily the same which should be used for return correspondence and should help prevent your message from being marked as spam. + ```php - $email = new Email(..); - $email->setReplyTo('me@address.com'); +$email = new Email(..); +$email->setReplyTo('me@address.com'); ``` ### Setting Custom Headers @@ -164,9 +161,8 @@ For email headers which do not have getters or setters (like setTo(), setFrom()) ```php - $email = new Email(...); - $email->getSwiftMessage()->getHeaders()->addTextHeader('HeaderName', 'HeaderValue'); - .. +$email = new Email(...); +$email->getSwiftMessage()->getHeaders()->addTextHeader('HeaderName', 'HeaderValue'); ```
      diff --git a/docs/en/02_Developer_Guides/11_Integration/00_CSV_Import.md b/docs/en/02_Developer_Guides/11_Integration/00_CSV_Import.md index 19a552143..02476dc0e 100644 --- a/docs/en/02_Developer_Guides/11_Integration/00_CSV_Import.md +++ b/docs/en/02_Developer_Guides/11_Integration/00_CSV_Import.md @@ -28,18 +28,19 @@ You can use the CsvBulkLoader without subclassing or other customizations, if th in your CSV file match `$db` properties in your dataobject. E.g. a simple import for the [Member](api:SilverStripe\Security\Member) class could have this data in a file: ``` - FirstName,LastName,Email - Donald,Duck,donald@disney.com - Daisy,Duck,daisy@disney.com +FirstName,LastName,Email +Donald,Duck,donald@disney.com +Daisy,Duck,daisy@disney.com ``` + The loader would be triggered through the `load()` method: ```php - use SilverStripe\Dev\CsvBulkLoader; - - $loader = new CsvBulkLoader('Member'); - $result = $loader->load(''); +use SilverStripe\Dev\CsvBulkLoader; + +$loader = new CsvBulkLoader('Member'); +$result = $loader->load(''); ``` By the way, you can import [Member](api:SilverStripe\Security\Member) and [Group](api:SilverStripe\Security\Group) data through `http://localhost/admin/security` @@ -51,20 +52,18 @@ The simplest way to use [CsvBulkLoader](api:SilverStripe\Dev\CsvBulkLoader) is t ```php - use SilverStripe\Admin\ModelAdmin; - - class PlayerAdmin extends ModelAdmin - { - private static $managed_models = [ - 'Player' - ]; - private static $model_importers = [ - 'Player' => 'CsvBulkLoader', - ]; - private static $url_segment = 'players'; - } - ?> +use SilverStripe\Admin\ModelAdmin; +class PlayerAdmin extends ModelAdmin +{ + private static $managed_models = [ + 'Player' + ]; + private static $model_importers = [ + 'Player' => 'CsvBulkLoader', + ]; + private static $url_segment = 'players'; +} ``` The new admin interface will be available under `http://localhost/admin/players`, the import form is located @@ -79,57 +78,56 @@ You'll need to add a route to your controller to make it accessible via URL ```php - use SilverStripe\Forms\Form; - use SilverStripe\Forms\FieldList; - use SilverStripe\Forms\FileField; - use SilverStripe\Forms\FormAction; - use SilverStripe\Forms\RequiredFields; - use SilverStripe\Dev\CsvBulkLoader; - use SilverStripe\Control\Controller; +use SilverStripe\Forms\Form; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\FileField; +use SilverStripe\Forms\FormAction; +use SilverStripe\Forms\RequiredFields; +use SilverStripe\Dev\CsvBulkLoader; +use SilverStripe\Control\Controller; - class MyController extends Controller +class MyController extends Controller +{ + + private static $allowed_actions = ['Form']; + + protected $template = "BlankPage"; + + public function Link($action = null) { - - private static $allowed_actions = ['Form']; - - protected $template = "BlankPage"; - - public function Link($action = null) - { - return Controller::join_links('MyController', $action); - } - - public function Form() - { - $form = new Form( - $this, - 'Form', - new FieldList( - new FileField('CsvFile', false) - ), - new FieldList( - new FormAction('doUpload', 'Upload') - ), - new RequiredFields() - ); - return $form; - } - - public function doUpload($data, $form) - { - $loader = new CsvBulkLoader('MyDataObject'); - $results = $loader->load($_FILES['CsvFile']['tmp_name']); - $messages = []; - if($results->CreatedCount()) $messages[] = sprintf('Imported %d items', $results->CreatedCount()); - if($results->UpdatedCount()) $messages[] = sprintf('Updated %d items', $results->UpdatedCount()); - if($results->DeletedCount()) $messages[] = sprintf('Deleted %d items', $results->DeletedCount()); - if(!$messages) $messages[] = 'No changes'; - $form->sessionMessage(implode(', ', $messages), 'good'); - - return $this->redirectBack(); - } + return Controller::join_links('MyController', $action); } + public function Form() + { + $form = new Form( + $this, + 'Form', + new FieldList( + new FileField('CsvFile', false) + ), + new FieldList( + new FormAction('doUpload', 'Upload') + ), + new RequiredFields() + ); + return $form; + } + + public function doUpload($data, $form) + { + $loader = new CsvBulkLoader('MyDataObject'); + $results = $loader->load($_FILES['CsvFile']['tmp_name']); + $messages = []; + if($results->CreatedCount()) $messages[] = sprintf('Imported %d items', $results->CreatedCount()); + if($results->UpdatedCount()) $messages[] = sprintf('Updated %d items', $results->UpdatedCount()); + if($results->DeletedCount()) $messages[] = sprintf('Deleted %d items', $results->DeletedCount()); + if(!$messages) $messages[] = 'No changes'; + $form->sessionMessage(implode(', ', $messages), 'good'); + + return $this->redirectBack(); + } +} ``` Note: This interface is not secured, consider using [Permission::check()](api:SilverStripe\Security\Permission::check()) to limit the controller to users @@ -141,51 +139,46 @@ We're going to use our knowledge from the previous example to import a more soph Sample CSV Content ``` - "Number","Name","Birthday","Team" - 11,"John Doe",1982-05-12,"FC Bayern" - 12,"Jane Johnson", 1982-05-12,"FC Bayern" - 13,"Jimmy Dole",,"Schalke 04" +"Number","Name","Birthday","Team" +11,"John Doe",1982-05-12,"FC Bayern" +12,"Jane Johnson", 1982-05-12,"FC Bayern" +13,"Jimmy Dole",,"Schalke 04" ``` Datamodel for Player ```php - use SilverStripe\ORM\DataObject; - - class Player extends DataObject - { - private static $db = [ - 'PlayerNumber' => 'Int', - 'FirstName' => 'Text', - 'LastName' => 'Text', - 'Birthday' => 'Date', - ]; - private static $has_one = [ - 'Team' => 'FootballTeam' - ]; - } - ?> +use SilverStripe\ORM\DataObject; +class Player extends DataObject +{ + private static $db = [ + 'PlayerNumber' => 'Int', + 'FirstName' => 'Text', + 'LastName' => 'Text', + 'Birthday' => 'Date', + ]; + private static $has_one = [ + 'Team' => 'FootballTeam' + ]; +} ``` Datamodel for FootballTeam: - ```php - use SilverStripe\ORM\DataObject; - - class FootballTeam extends DataObject - { - private static $db = [ - 'Title' => 'Text', - ]; - private static $has_many = [ - 'Players' => 'Player' - ]; - } - ?> +use SilverStripe\ORM\DataObject; +class FootballTeam extends DataObject +{ + private static $db = [ + 'Title' => 'Text', + ]; + private static $has_many = [ + 'Players' => 'Player' + ]; +} ``` Sample implementation of a custom loader. Assumes a CSV-file in a certain format (see below). @@ -194,60 +187,57 @@ Sample implementation of a custom loader. Assumes a CSV-file in a certain format * Splits a combined "Name" fields from the CSV-data into `FirstName` and `Lastname` by a custom importer method * Avoids duplicate imports by a custom `$duplicateChecks` definition * Creates `Team` relations automatically based on the `Gruppe` column in the CSV data + ```php - use SilverStripe\Dev\CsvBulkLoader; - - class PlayerCsvBulkLoader extends CsvBulkLoader - { - public $columnMap = [ - 'Number' => 'PlayerNumber', - 'Name' => '->importFirstAndLastName', - 'Birthday' => 'Birthday', - 'Team' => 'Team.Title', - ]; - public $duplicateChecks = [ - 'Number' => 'PlayerNumber' - ]; - public $relationCallbacks = [ - 'Team.Title' => [ - 'relationname' => 'Team', - 'callback' => 'getTeamByTitle' - ] - ]; - public static function importFirstAndLastName(&$obj, $val, $record) - { - $parts = explode(' ', $val); - if(count($parts) != 2) return false; - $obj->FirstName = $parts[0]; - $obj->LastName = $parts[1]; - } - public static function getTeamByTitle(&$obj, $val, $record) - { - return FootballTeam::get()->filter('Title', $val)->First(); - } - } - ?> +use SilverStripe\Dev\CsvBulkLoader; +class PlayerCsvBulkLoader extends CsvBulkLoader +{ + public $columnMap = [ + 'Number' => 'PlayerNumber', + 'Name' => '->importFirstAndLastName', + 'Birthday' => 'Birthday', + 'Team' => 'Team.Title', + ]; + public $duplicateChecks = [ + 'Number' => 'PlayerNumber' + ]; + public $relationCallbacks = [ + 'Team.Title' => [ + 'relationname' => 'Team', + 'callback' => 'getTeamByTitle' + ] + ]; + public static function importFirstAndLastName(&$obj, $val, $record) + { + $parts = explode(' ', $val); + if(count($parts) != 2) return false; + $obj->FirstName = $parts[0]; + $obj->LastName = $parts[1]; + } + public static function getTeamByTitle(&$obj, $val, $record) + { + return FootballTeam::get()->filter('Title', $val)->First(); + } +} ``` Building off of the ModelAdmin example up top, use a custom loader instead of the default loader by adding it to `$model_importers`. In this example, `CsvBulkLoader` is replaced with `PlayerCsvBulkLoader`. ```php - use SilverStripe\Admin\ModelAdmin; - - class PlayerAdmin extends ModelAdmin - { - private static $managed_models = [ - 'Player' - ]; - private static $model_importers = [ - 'Player' => 'PlayerCsvBulkLoader', - ]; - private static $url_segment = 'players'; - } - ?> +use SilverStripe\Admin\ModelAdmin; +class PlayerAdmin extends ModelAdmin +{ + private static $managed_models = [ + 'Player' + ]; + private static $model_importers = [ + 'Player' => 'PlayerCsvBulkLoader', + ]; + private static $url_segment = 'players'; +} ``` ## Related diff --git a/docs/en/02_Developer_Guides/11_Integration/02_RSSFeed.md b/docs/en/02_Developer_Guides/11_Integration/02_RSSFeed.md index 1ab453ba2..f7e3abaf8 100644 --- a/docs/en/02_Developer_Guides/11_Integration/02_RSSFeed.md +++ b/docs/en/02_Developer_Guides/11_Integration/02_RSSFeed.md @@ -24,27 +24,28 @@ An outline of step one looks like: ```php - use SilverStripe\Control\RSS\RSSFeed; +use SilverStripe\Control\RSS\RSSFeed; - $feed = new RSSFeed( - $list, - $link, - $title, - $description, - $titleField, - $descriptionField, - $authorField, - $lastModifiedTime, - $etag - ); +$feed = new RSSFeed( + $list, + $link, + $title, + $description, + $titleField, + $descriptionField, + $authorField, + $lastModifiedTime, + $etag +); - $feed->outputToBrowser(); +$feed->outputToBrowser(); ``` To achieve step two include the following code where ever you want to include the `` tag to the RSS Feed. This will normally go in your `Controllers` `init` method. + ```php - RSSFeed::linkToFeed($link, $title); +RSSFeed::linkToFeed($link, $title); ``` ## Examples @@ -56,46 +57,41 @@ You can use [RSSFeed](api:SilverStripe\Control\RSS\RSSFeed) to easily create a f **mysite/code/Page.php** - ```php - use SilverStripe\Control\RSS\RSSFeed; - use Page; - use SilverStripe\CMS\Controllers\ContentController; +use SilverStripe\Control\RSS\RSSFeed; +use SilverStripe\CMS\Controllers\ContentController; - - .. - class PageController extends ContentController +class PageController extends ContentController +{ + private static $allowed_actions = [ + 'rss' + ]; + + public function init() { + parent::init(); - private static $allowed_actions = [ - 'rss' - ]; - - public function init() - { - parent::init(); - - RSSFeed::linkToFeed($this->Link() . "rss", "10 Most Recently Updated Pages"); - } - - public function rss() - { - $rss = new RSSFeed( - $this->LatestUpdates(), - $this->Link(), - "10 Most Recently Updated Pages", - "Shows a list of the 10 most recently updated pages." - ); - - return $rss->outputToBrowser(); - } - - public function LatestUpdates() - { - return Page::get()->sort("LastEdited", "DESC")->limit(10); - } + RSSFeed::linkToFeed($this->Link() . "rss", "10 Most Recently Updated Pages"); } + public function rss() + { + $rss = new RSSFeed( + $this->LatestUpdates(), + $this->Link(), + "10 Most Recently Updated Pages", + "Shows a list of the 10 most recently updated pages." + ); + + return $rss->outputToBrowser(); + } + + public function LatestUpdates() + { + return Page::get()->sort("LastEdited", "DESC")->limit(10); + } +} + ``` ### Rendering DataObjects in a RSSFeed @@ -112,59 +108,58 @@ method is defined and returns a string to the full website URL. ```php - use SilverStripe\Control\Controller; - use SilverStripe\Control\Director; - use SilverStripe\ORM\DataObject; +use SilverStripe\Control\Controller; +use SilverStripe\Control\Director; +use SilverStripe\ORM\DataObject; - class Player extends DataObject +class Player extends DataObject +{ + + public function AbsoluteLink() { + // assumes players can be accessed at yoursite.com/players/2 - public function AbsoluteLink() - { - // assumes players can be accessed at yoursite.com/players/2 - - return Controller::join_links( - Director::absoluteBaseUrl(), - 'players', - $this->ID - ); - } + return Controller::join_links( + Director::absoluteBaseUrl(), + 'players', + $this->ID + ); } +} ``` Then in our controller, we add a new action which returns a the XML list of `Players`. ```php - use SilverStripe\Control\RSS\RSSFeed; - use SilverStripe\CMS\Controllers\ContentController; +use SilverStripe\Control\RSS\RSSFeed; +use SilverStripe\CMS\Controllers\ContentController; - class PageController extends ContentController +class PageController extends ContentController +{ + + private static $allowed_actions = [ + 'players' + ]; + + public function init() { + parent::init(); - private static $allowed_actions = [ - 'players' - ]; - - public function init() - { - parent::init(); - - RSSFeed::linkToFeed($this->Link("players"), "Players"); - } - - public function players() - { - $rss = new RSSFeed( - Player::get(), - $this->Link("players"), - "Players" - ); - - return $rss->outputToBrowser(); - } + RSSFeed::linkToFeed($this->Link("players"), "Players"); } + public function players() + { + $rss = new RSSFeed( + Player::get(), + $this->Link("players"), + "Players" + ); + + return $rss->outputToBrowser(); + } +} ``` ### Customizing the RSS Feed template @@ -176,47 +171,44 @@ Say from that last example we want to include the Players Team in the XML feed w **mysite/templates/PlayersRss.ss** - ```xml + + + + $Title + $Link + + $Description.XML - - - - $Title - $Link - - $Description.XML - - <% loop $Entries %> - - $Title.XML - $Team.Title - - <% end_loop %> - - + <% loop $Entries %> + + $Title.XML + $Team.Title + + <% end_loop %> + + ``` `setTemplate` can then be used to tell RSSFeed to use that new template. **mysite/code/Page.php** - ```php - use SilverStripe\Control\RSS\RSSFeed; - - public function players() - { - $rss = new RSSFeed( - Player::get(), - $this->Link("players"), - "Players" - ); - - $rss->setTemplate('PlayersRss'); +use SilverStripe\Control\RSS\RSSFeed; - return $rss->outputToBrowser(); - } +public function players() +{ + $rss = new RSSFeed( + Player::get(), + $this->Link("players"), + "Players" + ); + + $rss->setTemplate('PlayersRss'); + + return $rss->outputToBrowser(); +} ```
      diff --git a/docs/en/02_Developer_Guides/11_Integration/How_Tos/Import_CSV_through_a_Controller.md b/docs/en/02_Developer_Guides/11_Integration/How_Tos/Import_CSV_through_a_Controller.md index 3e123d71d..a0549eee4 100644 --- a/docs/en/02_Developer_Guides/11_Integration/How_Tos/Import_CSV_through_a_Controller.md +++ b/docs/en/02_Developer_Guides/11_Integration/How_Tos/Import_CSV_through_a_Controller.md @@ -8,72 +8,71 @@ form (which is used for `MyDataObject` instances). You can access it through ```php - use SilverStripe\Forms\Form; - use SilverStripe\Forms\FieldList; - use SilverStripe\Forms\FileField; - use SilverStripe\Forms\FormAction; - use SilverStripe\Forms\RequiredFields; - use SilverStripe\Dev\CsvBulkLoader; - use SilverStripe\Control\Controller; +use SilverStripe\Forms\Form; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\FileField; +use SilverStripe\Forms\FormAction; +use SilverStripe\Forms\RequiredFields; +use SilverStripe\Dev\CsvBulkLoader; +use SilverStripe\Control\Controller; - class MyController extends Controller +class MyController extends Controller +{ + + private static $allowed_actions = [ + 'Form' + ]; + + protected $template = "BlankPage"; + + public function Link($action = null) { - - private static $allowed_actions = [ - 'Form' - ]; - - protected $template = "BlankPage"; - - public function Link($action = null) - { - return Controller::join_links('MyController', $action); - } - - public function Form() - { - $form = new Form( - $this, - 'Form', - new FieldList( - new FileField('CsvFile', false) - ), - new FieldList( - new FormAction('doUpload', 'Upload') - ), - new RequiredFields() - ); - return $form; - } - - public function doUpload($data, $form) - { - $loader = new CsvBulkLoader('MyDataObject'); - $results = $loader->load($_FILES['CsvFile']['tmp_name']); - $messages = []; - - if($results->CreatedCount()) { - $messages[] = sprintf('Imported %d items', $results->CreatedCount()); - } - - if($results->UpdatedCount()) { - $messages[] = sprintf('Updated %d items', $results->UpdatedCount()); - } - - if($results->DeletedCount()) { - $messages[] = sprintf('Deleted %d items', $results->DeletedCount()); - } - - if(!$messages) { - $messages[] = 'No changes'; - } - - $form->sessionMessage(implode(', ', $messages), 'good'); - - return $this->redirectBack(); - } + return Controller::join_links('MyController', $action); } + public function Form() + { + $form = new Form( + $this, + 'Form', + new FieldList( + new FileField('CsvFile', false) + ), + new FieldList( + new FormAction('doUpload', 'Upload') + ), + new RequiredFields() + ); + return $form; + } + + public function doUpload($data, $form) + { + $loader = new CsvBulkLoader('MyDataObject'); + $results = $loader->load($_FILES['CsvFile']['tmp_name']); + $messages = []; + + if($results->CreatedCount()) { + $messages[] = sprintf('Imported %d items', $results->CreatedCount()); + } + + if($results->UpdatedCount()) { + $messages[] = sprintf('Updated %d items', $results->UpdatedCount()); + } + + if($results->DeletedCount()) { + $messages[] = sprintf('Deleted %d items', $results->DeletedCount()); + } + + if(!$messages) { + $messages[] = 'No changes'; + } + + $form->sessionMessage(implode(', ', $messages), 'good'); + + return $this->redirectBack(); + } +} ```
      diff --git a/docs/en/02_Developer_Guides/11_Integration/How_Tos/custom_csvbulkloader.md b/docs/en/02_Developer_Guides/11_Integration/How_Tos/custom_csvbulkloader.md index fffe5a3ed..b4505496c 100644 --- a/docs/en/02_Developer_Guides/11_Integration/How_Tos/custom_csvbulkloader.md +++ b/docs/en/02_Developer_Guides/11_Integration/How_Tos/custom_csvbulkloader.md @@ -4,12 +4,14 @@ title: A custom CSVBulkLoader instance A an implementation of a custom `CSVBulkLoader` loader. In this example. we're provided with a unique CSV file containing a list of football players and the team they play for. The file we have is in the format like below. + ``` - "SpielerNummer", "Name", "Geburtsdatum", "Gruppe" - 11, "John Doe", 1982-05-12,"FC Bayern" - 12, "Jane Johnson", 1982-05-12,"FC Bayern" - 13, "Jimmy Dole",,"Schalke 04" +"SpielerNummer", "Name", "Geburtsdatum", "Gruppe" +11, "John Doe", 1982-05-12,"FC Bayern" +12, "Jane Johnson", 1982-05-12,"FC Bayern" +13, "Jimmy Dole",,"Schalke 04" ``` + This data needs to be imported into our application. For this, we have two `DataObjects` setup. `Player` contains information about the individual player and a relation set up for managing the `Team`. @@ -17,43 +19,40 @@ information about the individual player and a relation set up for managing the ` ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Player extends DataObject - { - - private static $db = [ - 'PlayerNumber' => 'Int', - 'FirstName' => 'Text', - 'LastName' => 'Text', - 'Birthday' => 'Date' - ]; - - private static $has_one = [ - 'Team' => 'FootballTeam' - ]; - } +class Player extends DataObject +{ + private static $db = [ + 'PlayerNumber' => 'Int', + 'FirstName' => 'Text', + 'LastName' => 'Text', + 'Birthday' => 'Date' + ]; + + private static $has_one = [ + 'Team' => 'FootballTeam' + ]; +} ``` **mysite/code/FootballTeam.php** ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class FootballTeam extends DataObject - { - - private static $db = [ - 'Title' => 'Text' - ]; - - private static $has_many = [ - 'Players' => 'Player' - ]; - } +class FootballTeam extends DataObject +{ + private static $db = [ + 'Title' => 'Text' + ]; + private static $has_many = [ + 'Players' => 'Player' + ]; +} ``` Now going back to look at the CSV, we can see that what we're provided with does not match what our data model looks @@ -72,43 +71,42 @@ Our final import looks like this. ```php - use SilverStripe\Dev\CsvBulkLoader; +use SilverStripe\Dev\CsvBulkLoader; - class PlayerCsvBulkLoader extends CsvBulkLoader - { +class PlayerCsvBulkLoader extends CsvBulkLoader +{ - public $columnMap = [ - 'Number' => 'PlayerNumber', - 'Name' => '->importFirstAndLastName', - 'Geburtsdatum' => 'Birthday', - 'Gruppe' => 'Team.Title', - ]; + public $columnMap = [ + 'Number' => 'PlayerNumber', + 'Name' => '->importFirstAndLastName', + 'Geburtsdatum' => 'Birthday', + 'Gruppe' => 'Team.Title', + ]; - public $duplicateChecks = [ - 'SpielerNummer' => 'PlayerNumber' - ]; + public $duplicateChecks = [ + 'SpielerNummer' => 'PlayerNumber' + ]; - public $relationCallbacks = [ - 'Team.Title' => [ - 'relationname' => 'Team', - 'callback' => 'getTeamByTitle' - ] - ]; + public $relationCallbacks = [ + 'Team.Title' => [ + 'relationname' => 'Team', + 'callback' => 'getTeamByTitle' + ] + ]; - public static function importFirstAndLastName(&$obj, $val, $record) - { - $parts = explode(' ', $val); - if(count($parts) != 2) return false; - $obj->FirstName = $parts[0]; - $obj->LastName = $parts[1]; - } - - public static function getTeamByTitle(&$obj, $val, $record) - { - return FootballTeam::get()->filter('Title', $val)->First(); - } - } + public static function importFirstAndLastName(&$obj, $val, $record) + { + $parts = explode(' ', $val); + if(count($parts) != 2) return false; + $obj->FirstName = $parts[0]; + $obj->LastName = $parts[1]; + } + public static function getTeamByTitle(&$obj, $val, $record) + { + return FootballTeam::get()->filter('Title', $val)->First(); + } +} ``` ## Related diff --git a/docs/en/02_Developer_Guides/12_Search/01_Searchcontext.md b/docs/en/02_Developer_Guides/12_Search/01_Searchcontext.md index 5aa28a925..e9ff60eb9 100644 --- a/docs/en/02_Developer_Guides/12_Search/01_Searchcontext.md +++ b/docs/en/02_Developer_Guides/12_Search/01_Searchcontext.md @@ -20,16 +20,15 @@ Defining search-able fields on your DataObject. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyDataObject extends DataObject - { - - private static $searchable_fields = [ - 'Name', - 'ProductCode' - ]; - } +class MyDataObject extends DataObject +{ + private static $searchable_fields = [ + 'Name', + 'ProductCode' + ]; +} ``` @@ -41,39 +40,38 @@ and `MyDate`. The attribute `HiddenProperty` should not be searchable, and `MyDa ```php - use SilverStripe\ORM\Filters\PartialMatchFilter; - use SilverStripe\ORM\Filters\GreaterThanFilter; - use SilverStripe\ORM\Search\SearchContext; - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\Filters\PartialMatchFilter; +use SilverStripe\ORM\Filters\GreaterThanFilter; +use SilverStripe\ORM\Search\SearchContext; +use SilverStripe\ORM\DataObject; - class MyDataObject extends DataObject +class MyDataObject extends DataObject +{ + + private static $db = [ + 'PublicProperty' => 'Text' + 'HiddenProperty' => 'Text', + 'MyDate' => 'Date' + ]; + + public function getDefaultSearchContext() { + $fields = $this->scaffoldSearchFields([ + 'restrictFields' => ['PublicProperty','MyDate'] + ]); - private static $db = [ - 'PublicProperty' => 'Text' - 'HiddenProperty' => 'Text', - 'MyDate' => 'Date' + $filters = [ + 'PublicProperty' => new PartialMatchFilter('PublicProperty'), + 'MyDate' => new GreaterThanFilter('MyDate') ]; - - public function getDefaultSearchContext() - { - $fields = $this->scaffoldSearchFields([ - 'restrictFields' => ['PublicProperty','MyDate'] - ]); - $filters = [ - 'PublicProperty' => new PartialMatchFilter('PublicProperty'), - 'MyDate' => new GreaterThanFilter('MyDate') - ]; - - return new SearchContext( - $this->class, - $fields, - $filters - ); - } + return new SearchContext( + $this->class, + $fields, + $filters + ); } - +} ```
      @@ -90,42 +88,41 @@ the `$fields` constructor parameter. ```php - use SilverStripe\Forms\Form; - use SilverStripe\Forms\FieldList; - use SilverStripe\Forms\FormAction; - use SilverStripe\CMS\Controllers\ContentController; +use SilverStripe\Forms\Form; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\FormAction; +use SilverStripe\CMS\Controllers\ContentController; - - // .. - class PageController extends ContentController + +// .. +class PageController extends ContentController +{ + + public function SearchForm() { + $context = singleton('MyDataObject')->getCustomSearchContext(); + $fields = $context->getSearchFields(); - public function SearchForm() - { - $context = singleton('MyDataObject')->getCustomSearchContext(); - $fields = $context->getSearchFields(); + $form = new Form($this, "SearchForm", + $fields, + new FieldList( + new FormAction('doSearch') + ) + ); - $form = new Form($this, "SearchForm", - $fields, - new FieldList( - new FormAction('doSearch') - ) - ); - - return $form; - } - - public function doSearch($data, $form) - { - $context = singleton('MyDataObject')->getCustomSearchContext(); - $results = $context->getResults($data); - - return $this->customise([ - 'Results' => $results - ])->renderWith('Page_results'); - } + return $form; } + public function doSearch($data, $form) + { + $context = singleton('MyDataObject')->getCustomSearchContext(); + $results = $context->getResults($data); + + return $this->customise([ + 'Results' => $results + ])->renderWith('Page_results'); + } +} ``` ### Pagination @@ -137,42 +134,40 @@ in order to read page limit information. It is also passed the current ```php - use SilverStripe\ORM\PaginatedList; - - public function getResults($searchCriteria = []) - { - $start = ($this->getRequest()->getVar('start')) ? (int)$this->getRequest()->getVar('start') : 0; - $limit = 10; - - $context = singleton('MyDataObject')->getCustomSearchContext(); - $query = $context->getQuery($searchCriteria, null, ['start'=>$start,'limit'=>$limit]); - $records = $context->getResults($searchCriteria, null, ['start'=>$start,'limit'=>$limit]); - - if($records) { - $records = new PaginatedList($records, $this->getRequest()); - $records->setPageStart($start); - $records->setPageLength($limit); - $records->setTotalItems($query->unlimitedRowCount()); - } - - return $records; - } +use SilverStripe\ORM\PaginatedList; +public function getResults($searchCriteria = []) +{ + $start = ($this->getRequest()->getVar('start')) ? (int)$this->getRequest()->getVar('start') : 0; + $limit = 10; + + $context = singleton('MyDataObject')->getCustomSearchContext(); + $query = $context->getQuery($searchCriteria, null, ['start'=>$start,'limit'=>$limit]); + $records = $context->getResults($searchCriteria, null, ['start'=>$start,'limit'=>$limit]); + + if($records) { + $records = new PaginatedList($records, $this->getRequest()); + $records->setPageStart($start); + $records->setPageLength($limit); + $records->setTotalItems($query->unlimitedRowCount()); + } + + return $records; +} ``` notice that if you want to use this getResults function, you need to change the function doSearch for this one: ```php - public function doSearch($data, $form) - { - $context = singleton('MyDataObject')->getCustomSearchContext(); - $results = $this->getResults($data); - return $this->customise([ - 'Results' => $results - ])->renderWith(['Catalogo_results', 'Page']); - } - +public function doSearch($data, $form) +{ + $context = singleton('MyDataObject')->getCustomSearchContext(); + $results = $this->getResults($data); + return $this->customise([ + 'Results' => $results + ])->renderWith(['Catalogo_results', 'Page']); +} ``` The change is in **$results = $this->getResults($data);**, because you are using a custom getResults function. @@ -189,45 +184,45 @@ to show the results of your custom search you need at least this content in your Results.PaginationSummary(4) defines how many pages the search will show in the search results. something like: **Next 1 2 *3* 4 5 … 558** -```ss - <% if $Results %> -
        - <% loop $Results %> -
      • $Title, $Autor
      • - <% end_loop %> -
      - <% else %> -

      Sorry, your search query did not return any results.

      - <% end_if %> - - <% if $Results.MoreThanOnePage %> -
      -

      - <% if $Results.NotFirstPage %> - - <% end_if %> - - - <% loop $Results.PaginationSummary(4) %> - <% if $CurrentBool %> - $PageNum +```ss +<% if $Results %> +

        + <% loop $Results %> +
      • $Title, $Autor
      • + <% end_loop %> +
      +<% else %> +

      Sorry, your search query did not return any results.

      +<% end_if %> + +<% if $Results.MoreThanOnePage %> +
      +

      + <% if $Results.NotFirstPage %> + + <% end_if %> + + + <% loop $Results.PaginationSummary(4) %> + <% if $CurrentBool %> + $PageNum + <% else %> + <% if $Link %> + $PageNum <% else %> - <% if $Link %> - $PageNum - <% else %> - … - <% end_if %> + … <% end_if %> - <% end_loop %> - - - <% if $Results.NotLastPage %> - - <% end_if %> -

      -
      - <% end_if %> + <% end_if %> + <% end_loop %> + + + <% if $Results.NotLastPage %> + + <% end_if %> +

      +
      +<% end_if %> ``` ## Available SearchFilters diff --git a/docs/en/02_Developer_Guides/12_Search/02_FulltextSearch.md b/docs/en/02_Developer_Guides/12_Search/02_FulltextSearch.md index f400ed7d8..395cd4d32 100644 --- a/docs/en/02_Developer_Guides/12_Search/02_FulltextSearch.md +++ b/docs/en/02_Developer_Guides/12_Search/02_FulltextSearch.md @@ -23,16 +23,15 @@ You can do so by adding this static variable to your class definition: ```php - use SilverStripe\ORM\DataObject; - - class MyDataObject extends DataObject - { - - private static $create_table_options = [ - 'MySQLDatabase' => 'ENGINE=MyISAM' - ]; - } +use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\Connect\MySQLSchemaManager; +class MyDataObject extends DataObject +{ + private static $create_table_options = [ + MySQLSchemaManager::ID => 'ENGINE=MyISAM' + ]; +} ``` The [FulltextSearchable](api:SilverStripe\ORM\Search\FulltextSearchable) extension will add the correct `Fulltext` indexes to the data model. @@ -52,28 +51,29 @@ Example DataObject: ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\Connect\MySQLSchemaManager; - class SearchableDataObject extends DataObject - { - - private static $db = [ - "Title" => "Varchar(255)", - "Content" => "HTMLText", - ]; +class SearchableDataObject extends DataObject +{ + + private static $db = [ + "Title" => "Varchar(255)", + "Content" => "HTMLText", + ]; - private static $indexes = [ - 'SearchFields' => [ - 'type' => 'fulltext', - 'columns' => ['Title', 'Content'], - ] - ]; + private static $indexes = [ + 'SearchFields' => [ + 'type' => 'fulltext', + 'columns' => ['Title', 'Content'], + ] + ]; - private static $create_table_options = [ - 'MySQLDatabase' => 'ENGINE=MyISAM' - ]; + private static $create_table_options = [ + MySQLSchemaManager::ID => 'ENGINE=MyISAM' + ]; - } +} ``` @@ -81,7 +81,7 @@ Performing the search: ```php - SearchableDataObject::get()->filter('SearchFields:Fulltext', 'search term'); +SearchableDataObject::get()->filter('SearchFields:Fulltext', 'search term'); ``` If your search index is a single field size, then you may also specify the search filter by the name of the diff --git a/docs/en/02_Developer_Guides/13_i18n/index.md b/docs/en/02_Developer_Guides/13_i18n/index.md index 4da8bbcdb..a4db8a2c3 100644 --- a/docs/en/02_Developer_Guides/13_i18n/index.md +++ b/docs/en/02_Developer_Guides/13_i18n/index.md @@ -29,11 +29,11 @@ you want to set. ```php - use SilverStripe\i18n\i18n; +use SilverStripe\i18n\i18n; - // mysite/_config.php - i18n::set_locale('de_DE'); // Setting the locale to German (Germany) - i18n::set_locale('ca_AD'); // Setting to Catalan (Andorra) +// mysite/_config.php +i18n::set_locale('de_DE'); // Setting the locale to German (Germany) +i18n::set_locale('ca_AD'); // Setting to Catalan (Andorra) ``` Once we set a locale, all the calls to the translator function will return strings according to the set locale value, if @@ -56,12 +56,11 @@ To let browsers know which language they're displaying a document in, you can de ```html +//'Page.ss' (HTML) + - //'Page.ss' (HTML) - - - //'Page.ss' (XHTML) - +//'Page.ss' (XHTML) + ``` Setting the `` attribute is the most commonly used technique. There are other ways to specify content languages @@ -73,8 +72,7 @@ and default alignment of paragraphs and tables to browsers. ```html - - + ``` ### Date and time formats @@ -84,10 +82,12 @@ You can use these settings for your own view logic. ```php - use SilverStripe\Core\Config\Config; +use SilverStripe\Core\Config\Config; +use SilverStripe\i18n\i18n; - Config::inst()->update('i18n', 'date_format', 'dd.MM.yyyy'); - Config::inst()->update('i18n', 'time_format', 'HH:mm'); +i18n::config() + ->set('date_format', 'dd.MM.yyyy') + ->set('time_format', 'HH:mm'); ``` Localization in SilverStripe uses PHP's [intl extension](http://php.net/intl). @@ -110,23 +110,21 @@ In order to add a value, add the following to your `config.yml`: ```yml - - SilverStripe\i18n\i18n: - common_locales: - de_CGN: - name: German (Cologne) - native: Kölsch +SilverStripe\i18n\i18n: + common_locales: + de_CGN: + name: German (Cologne) + native: Kölsch ``` Similarly, to change an existing language label, you can overwrite one of these keys: ```yml - - SilverStripe\i18n\i18n: - common_locales: - en_NZ: - native: Niu Zillund +SilverStripe\i18n\i18n: + common_locales: + en_NZ: + native: Niu Zillund ``` ### i18n in URLs @@ -159,11 +157,11 @@ followed by `setLocale()` or `setDateFormat()`/`setTimeFormat()`. ```php - use SilverStripe\Forms\DateField; +use SilverStripe\Forms\DateField; - $field = new DateField(); - $field->setLocale('de_AT'); // set Austrian/German locale, defaulting format to dd.MM.y - $field->setDateFormat('d.M.y'); // set a more specific date format (single digit day/month) +$field = new DateField(); +$field->setLocale('de_AT'); // set Austrian/German locale, defaulting format to dd.MM.y +$field->setDateFormat('d.M.y'); // set a more specific date format (single digit day/month) ``` ## Translating text @@ -173,10 +171,10 @@ language-dependent and use a translator function call instead. ```php - // without i18n - echo "This is a string"; - // with i18n - echo _t("Namespace.Entity","This is a string"); +// without i18n +echo "This is a string"; +// with i18n +echo _t("Namespace.Entity","This is a string"); ``` All strings passed through the `_t()` function will be collected in a separate language table (see [Collecting text](#collecting-text)), which is the starting point for translations. @@ -217,38 +215,35 @@ For instance, this is an example of how to correctly declare pluralisations for ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class MyObject extends DataObject, implements i18nEntityProvider +class MyObject extends DataObject implements i18nEntityProvider +{ + public function provideI18nEntities() { - public function provideI18nEntities() - { - return [ - 'MyObject.SINGULAR_NAME' => 'object', - 'MyObject.PLURAL_NAME' => 'objects', - 'MyObject.PLURALS' => [ - 'one' => 'An object', - 'other' => '{count} objects', - ], - ]; - } + return [ + 'MyObject.SINGULAR_NAME' => 'object', + 'MyObject.PLURAL_NAME' => 'objects', + 'MyObject.PLURALS' => [ + 'one' => 'An object', + 'other' => '{count} objects', + ], + ]; } +} ``` In YML format this will be expressed as the below. This follows the [ruby i18n convention](guides.rubyonrails.org/i18n.html#pluralization) for plural forms. - - ```yaml - - en: - MyObject: - SINGULAR_NAME: 'object' - PLURAL_NAME: 'objects' - PLURALS: - one: 'An object', - other: '{count} objects' +en: + MyObject: + SINGULAR_NAME: 'object' + PLURAL_NAME: 'objects' + PLURALS: + one: 'An object', + other: '{count} objects' ``` Note: i18nTextCollector support for pluralisation is not yet available. @@ -258,18 +253,17 @@ Please ensure that any required plurals are exposed via provideI18nEntities. ```php - // Simple string translation - _t('LeftAndMain.FILESIMAGES','Files & Images'); +// Simple string translation +_t('LeftAndMain.FILESIMAGES','Files & Images'); - // Using injection to add variables into the translated strings. - _t('CMSMain.RESTORED', - "Restored {value} successfully", - ['value' => $itemRestored] - ); - - // Plurals are invoked via a `|` pipe-delimeter with a {count} argument - _t('MyObject.PLURALS', 'An object|{count} objects', [ 'count' => '$count ]); +// Using injection to add variables into the translated strings. +_t('CMSMain.RESTORED', + "Restored {value} successfully", + ['value' => $itemRestored] +); +// Plurals are invoked via a `|` pipe-delimeter with a {count} argument +_t('MyObject.PLURALS', 'An object|{count} objects', [ 'count' => '$count ]); ``` #### Usage in Template Files @@ -287,15 +281,14 @@ the PHP version of the function. ```ss +// Simple string translation +<%t Namespace.Entity "String to translate" %> - // Simple string translation - <%t Namespace.Entity "String to translate" %> +// Using injection to add variables into the translated strings (note that $Name and $Greeting must be available in the current template scope). +<%t Header.Greeting "Hello {name} {greeting}" name=$Name greeting=$Greeting %> - // Using injection to add variables into the translated strings (note that $Name and $Greeting must be available in the current template scope). - <%t Header.Greeting "Hello {name} {greeting}" name=$Name greeting=$Greeting %> - - // Plurals follow the same convention, required a `|` and `{count}` in the default string - <%t MyObject.PLURALS 'An item|{count} items' count=$Count %> +// Plurals follow the same convention, required a `|` and `{count}` in the default string +<%t MyObject.PLURALS 'An item|{count} items' count=$Count %> ``` #### Caching in Template Files with locale switching @@ -303,14 +296,12 @@ the PHP version of the function. When caching a `<% loop %>` or `<% with %>` with `<%t params %>`. It is important to add the Locale to the cache key otherwise it won't pick up locale changes. - ```ss - - <% cached 'MyIdentifier', $CurrentLocale %> - <% loop $Students %> - $Name - <% end_loop %> - <% end_cached %> +<% cached 'MyIdentifier', $CurrentLocale %> + <% loop $Students %> + $Name + <% end_loop %> +<% end_cached %> ``` ## Collecting text @@ -342,16 +333,17 @@ By default, the language files are loaded from modules in this order: This default order is configured in `framework/_config/i18n.yml`. This file specifies two blocks of module ordering: `basei18n`, listing admin, and framework, and `defaulti18n` listing all other modules. To create a custom module order, you need to specify a config fragment that inserts itself either after or before those items. For example, you may have a number of modules that have to come after the framework/admin, but before anyhting else. To do that, you would use this + ```yml - --- - Name: customi18n - Before: 'defaulti18n' - --- - SilverStripe\i18n\i18n: - module_priority: - - module1 - - module2 - - module3 +--- +Name: customi18n +Before: 'defaulti18n' +--- +SilverStripe\i18n\i18n: + module_priority: + - module1 + - module2 + - module3 ``` The config option being set is `i18n.module_priority`, and it is a list of module names. @@ -371,21 +363,25 @@ By default, SilverStripe uses a YAML format which is loaded via the [symfony/translate](http://symfony.com/doc/current/translation.html) library. Example: framework/lang/en.yml (extract) + ```yml - en: - ImageUploader: - Attach: 'Attach {title}' - UploadField: - NOTEADDFILES: 'You can add files once you have saved for the first time.' +en: + ImageUploader: + Attach: 'Attach {title}' + UploadField: + NOTEADDFILES: 'You can add files once you have saved for the first time.' ``` + Translation table: framework/lang/de.yml (extract) + ```yml - de: - ImageUploader: - ATTACH: '{title} anhängen' - UploadField: - NOTEADDFILES: 'Sie können Dateien hinzufügen sobald Sie das erste mal gespeichert haben' +de: + ImageUploader: + ATTACH: '{title} anhängen' + UploadField: + NOTEADDFILES: 'Sie können Dateien hinzufügen sobald Sie das erste mal gespeichert haben' ``` + Note that translations are cached across requests. The cache can be cleared through the `?flush=1` query parameter, or explicitly through `Zend_Translate::getCache()->clean(Zend_Cache::CLEANING_MODE_ALL)`. @@ -423,24 +419,22 @@ Master Table (`/javascript/lang/en.js`) ```js - - if(typeof(ss) == 'undefined' || typeof(ss.i18n) == 'undefined') { - console.error('Class ss.i18n not defined'); - } else { - ss.i18n.addDictionary('en', { - 'MYMODULE.MYENTITY' : "Really delete these articles?" - }); - } +if(typeof(ss) == 'undefined' || typeof(ss.i18n) == 'undefined') { + console.error('Class ss.i18n not defined'); +} else { + ss.i18n.addDictionary('en', { + 'MYMODULE.MYENTITY' : "Really delete these articles?" + }); +} ``` Example Translation Table (`/javascript/lang/de.js`) ```js - - ss.i18n.addDictionary('de', { - 'MYMODULE.MYENTITY' : "Artikel wirklich löschen?" - }); +ss.i18n.addDictionary('de', { + 'MYMODULE.MYENTITY' : "Artikel wirklich löschen?" +}); ``` For most core modules, these files are generated by a @@ -452,8 +446,7 @@ format which can be processed more easily by external translation providers (see ```js - - alert(ss.i18n._t('MYMODULE.MYENTITY')); +alert(ss.i18n._t('MYMODULE.MYENTITY')); ``` ### Advanced Use @@ -462,33 +455,34 @@ The `ss.i18n` object contain a couple functions to help and replace dynamic vari #### Legacy sequential replacement with sprintf() - `sprintf()` will substitute occurencies of `%s` in the main string with each of the following arguments passed to the function. The substitution is done sequentially. - +`sprintf()` will substitute occurencies of `%s` in the main string with +each of the following arguments passed to the function. The substitution +is done sequentially. ```js - - // MYMODULE.MYENTITY contains "Really delete %s articles by %s?" - alert(ss.i18n.sprintf( - ss.i18n._t('MYMODULE.MYENTITY'), - 42, - 'Douglas Adams' - )); - // Displays: "Really delete 42 articles by Douglas Adams?" +// MYMODULE.MYENTITY contains "Really delete %s articles by %s?" +alert(ss.i18n.sprintf( + ss.i18n._t('MYMODULE.MYENTITY'), + 42, + 'Douglas Adams' +)); +// Displays: "Really delete 42 articles by Douglas Adams?" ``` #### Variable injection with inject() - `inject()` will substitute variables in the main string like `{myVar}` by the keys in the object passed as second argument. Each variable can be in any order and appear multiple times. +`inject()` will substitute variables in the main string like `{myVar}` by the +keys in the object passed as second argument. Each variable can be in any order +and appear multiple times. ```js - - // MYMODULE.MYENTITY contains "Really delete {count} articles by {author}?" - alert(ss.i18n.inject( - ss.i18n._t('MYMODULE.MYENTITY'), - {count: 42, author: 'Douglas Adams'} - )); - // Displays: "Really delete 42 articles by Douglas Adams?" +// MYMODULE.MYENTITY contains "Really delete {count} articles by {author}?" +alert(ss.i18n.inject( + ss.i18n._t('MYMODULE.MYENTITY'), + {count: 42, author: 'Douglas Adams'} +)); +// Displays: "Really delete 42 articles by Douglas Adams?" ``` ## Limitations diff --git a/docs/en/02_Developer_Guides/14_Files/02_Images.md b/docs/en/02_Developer_Guides/14_Files/02_Images.md index 56fff008f..f7473ed86 100644 --- a/docs/en/02_Developer_Guides/14_Files/02_Images.md +++ b/docs/en/02_Developer_Guides/14_Files/02_Images.md @@ -37,45 +37,42 @@ Here are some examples, assuming the `$Image` object has dimensions of 200x100px ```ss +// Scaling functions +$Image.ScaleWidth(150) // Returns a 150x75px image +$Image.ScaleMaxWidth(100) // Returns a 100x50px image (like ScaleWidth but prevents up-sampling) +$Image.ScaleHeight(150) // Returns a 300x150px image (up-sampled. Try to avoid doing this) +$Image.ScaleMaxHeight(150) // Returns a 200x100px image (like ScaleHeight but prevents up-sampling) +$Image.Fit(300,300) // Returns an image that fits within a 300x300px boundary, resulting in a 300x150px image (up-sampled) +$Image.FitMax(300,300) // Returns a 200x100px image (like Fit but prevents up-sampling) - // Scaling functions - $Image.ScaleWidth(150) // Returns a 150x75px image - $Image.ScaleMaxWidth(100) // Returns a 100x50px image (like ScaleWidth but prevents up-sampling) - $Image.ScaleHeight(150) // Returns a 300x150px image (up-sampled. Try to avoid doing this) - $Image.ScaleMaxHeight(150) // Returns a 200x100px image (like ScaleHeight but prevents up-sampling) - $Image.Fit(300,300) // Returns an image that fits within a 300x300px boundary, resulting in a 300x150px image (up-sampled) - $Image.FitMax(300,300) // Returns a 200x100px image (like Fit but prevents up-sampling) - - // Warning: This method can distort images that are not the correct aspect ratio - $Image.ResizedImage(200, 300) // Forces dimensions of this image to the given values. - - // Cropping functions - $Image.Fill(150,150) // Returns a 150x150px image resized and cropped to fill specified dimensions (up-sampled) - $Image.FillMax(150,150) // Returns a 100x100px image (like Fill but prevents up-sampling) - $Image.CropWidth(150) // Returns a 150x100px image (trims excess pixels off the x axis from the center) - $Image.CropHeight(50) // Returns a 200x50px image (trims excess pixels off the y axis from the center) - - // Padding functions (add space around an image) - $Image.Pad(100,100) // Returns a 100x100px padded image, with white bars added at the top and bottom - $Image.Pad(100, 100, CCCCCC) // Same as above but with a grey background - - // Metadata - $Image.Width // Returns width of image - $Image.Height // Returns height of image - $Image.Orientation // Returns Orientation - $Image.Title // Returns the friendly file name - $Image.Name // Returns the actual file name - $Image.FileName // Returns the actual file name including directory path from web root - $Image.Link // Returns relative URL path to image - $Image.AbsoluteLink // Returns absolute URL path to image +// Warning: This method can distort images that are not the correct aspect ratio +$Image.ResizedImage(200, 300) // Forces dimensions of this image to the given values. + +// Cropping functions +$Image.Fill(150,150) // Returns a 150x150px image resized and cropped to fill specified dimensions (up-sampled) +$Image.FillMax(150,150) // Returns a 100x100px image (like Fill but prevents up-sampling) +$Image.CropWidth(150) // Returns a 150x100px image (trims excess pixels off the x axis from the center) +$Image.CropHeight(50) // Returns a 200x50px image (trims excess pixels off the y axis from the center) + +// Padding functions (add space around an image) +$Image.Pad(100,100) // Returns a 100x100px padded image, with white bars added at the top and bottom +$Image.Pad(100, 100, CCCCCC) // Same as above but with a grey background + +// Metadata +$Image.Width // Returns width of image +$Image.Height // Returns height of image +$Image.Orientation // Returns Orientation +$Image.Title // Returns the friendly file name +$Image.Name // Returns the actual file name +$Image.FileName // Returns the actual file name including directory path from web root +$Image.Link // Returns relative URL path to image +$Image.AbsoluteLink // Returns absolute URL path to image ``` Image methods are chainable. Example: - ```ss - - + ``` ### Padded Image Resize @@ -88,9 +85,9 @@ png images. ```php - $Image.Pad(80, 80, FFFFFF, 50) // white padding with 50% transparency - $Image.Pad(80, 80, FFFFFF, 100) // white padding with 100% transparency - $Image.Pad(80, 80, FFFFFF) // white padding with no transparency +$Image.Pad(80, 80, FFFFFF, 50) // white padding with 50% transparency +$Image.Pad(80, 80, FFFFFF, 100) // white padding with 100% transparency +$Image.Pad(80, 80, FFFFFF) // white padding with no transparency ``` ### Manipulating images in PHP @@ -107,42 +104,43 @@ You can also create your own functions by decorating the `Image` class. ```php - class ImageExtension extends \SilverStripe\Core\Extension +use SilverStripe\Core\Extension; +class ImageExtension extends Extension +{ + public function Square($width) { - - public function Square($width) - { - $variant = $this->owner->variantName(__FUNCTION__, $width); - return $this->owner->manipulateImage($variant, function (\SilverStripe\Assets\Image_Backend $backend) use($width) { - $clone = clone $backend; - $resource = clone $backend->getImageResource(); - $resource->fit($width); - $clone->setImageResource($resource); - return $clone; - }); - } - - public function Blur($amount = null) - { - $variant = $this->owner->variantName(__FUNCTION__, $amount); - return $this->owner->manipulateImage($variant, function (\SilverStripe\Assets\Image_Backend $backend) use ($amount) { - $clone = clone $backend; - $resource = clone $backend->getImageResource(); - $resource->blur($amount); - $clone->setImageResource($resource); - return $clone; - }); - } - + $variant = $this->owner->variantName(__FUNCTION__, $width); + return $this->owner->manipulateImage($variant, function (\SilverStripe\Assets\Image_Backend $backend) use($width) { + $clone = clone $backend; + $resource = clone $backend->getImageResource(); + $resource->fit($width); + $clone->setImageResource($resource); + return $clone; + }); } - :::yml - SilverStripe\Assets\Image: - extensions: - - ImageExtension - SilverStripe\Filesystem\Storage\DBFile: - extensions: - - ImageExtension + public function Blur($amount = null) + { + $variant = $this->owner->variantName(__FUNCTION__, $amount); + return $this->owner->manipulateImage($variant, function (\SilverStripe\Assets\Image_Backend $backend) use ($amount) { + $clone = clone $backend; + $resource = clone $backend->getImageResource(); + $resource->blur($amount); + $clone->setImageResource($resource); + return $clone; + }); + } + +} +``` + +```yml +SilverStripe\Assets\Image: + extensions: + - ImageExtension +SilverStripe\Filesystem\Storage\DBFile: + extensions: + - ImageExtension ``` ### Form Upload @@ -176,13 +174,12 @@ necessary, you can add this to your mysite/config/config.yml file: ```yml - - # Configure resampling for File dataobject - File: - force_resample: false - # DBFile can be configured independently - SilverStripe\Filesystem\Storage\DBFile: - force_resample: false +# Configure resampling for File dataobject +SilverStripe\Assets\File: + force_resample: false +# DBFile can be configured independently +SilverStripe\Assets\Storage\DBFile: + force_resample: false ``` #### Resampled image quality @@ -192,11 +189,10 @@ following to your mysite/config/config.yml file: ```yml - - SilverStripe\Core\Injector\Injector: - SilverStripe\Assets\Image_Backend: - properties: - Quality: 90 +SilverStripe\Core\Injector\Injector: + SilverStripe\Assets\Image_Backend: + properties: + Quality: 90 ``` ## Changing the manipulation driver to Imagick diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/01_ModelAdmin.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/01_ModelAdmin.md index 97c04b3b4..e5e794903 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/01_ModelAdmin.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/01_ModelAdmin.md @@ -21,42 +21,40 @@ a category. ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Product extends DataObject - { +class Product extends DataObject +{ - private static $db = [ - 'Name' => 'Varchar', - 'ProductCode' => 'Varchar', - 'Price' => 'Currency' - ]; - - private static $has_one = [ - 'Category' => 'Category' - ]; - } + private static $db = [ + 'Name' => 'Varchar', + 'ProductCode' => 'Varchar', + 'Price' => 'Currency' + ]; + private static $has_one = [ + 'Category' => 'Category' + ]; +} ``` **mysite/code/Category.php** ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Category extends DataObject - { +class Category extends DataObject +{ - private static $db = [ - 'Title' => 'Text' - ]; - - private static $has_many = [ - 'Products' => 'Product' - ]; - } + private static $db = [ + 'Title' => 'Text' + ]; + private static $has_many = [ + 'Products' => 'Product' + ]; +} ``` To create your own `ModelAdmin`, simply extend the base class, and edit the `$managed_models` property with the list of @@ -68,21 +66,20 @@ We'll name it `MyAdmin`, but the class name can be anything you want. ```php - use SilverStripe\Admin\ModelAdmin; +use SilverStripe\Admin\ModelAdmin; - class MyAdmin extends ModelAdmin - { +class MyAdmin extends ModelAdmin +{ - private static $managed_models = [ - 'Product', - 'Category' - ]; + private static $managed_models = [ + 'Product', + 'Category' + ]; - private static $url_segment = 'products'; - - private static $menu_title = 'My Product Admin'; - } + private static $url_segment = 'products'; + private static $menu_title = 'My Product Admin'; +} ``` This will automatically add a new menu entry to the SilverStripe Admin UI entitled `My Product Admin` and logged in @@ -110,31 +107,31 @@ permissions by default. For most cases, less restrictive checks make sense, e.g. ```php - use SilverStripe\Security\Permission; - use SilverStripe\ORM\DataObject; +use SilverStripe\Security\Permission; +use SilverStripe\ORM\DataObject; - class Category extends DataObject +class Category extends DataObject +{ + public function canView($member = null) { - // ... - public function canView($member = null) - { - return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member); - } + return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member); + } - public function canEdit($member = null) - { - return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member); - } + public function canEdit($member = null) + { + return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member); + } - public function canDelete($member = null) - { - return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member); - } + public function canDelete($member = null) + { + return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member); + } - public function canCreate($member = null) - { - return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member); - } + public function canCreate($member = null) + { + return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member); + } +} ``` ## Searching Records @@ -151,17 +148,16 @@ class (see [SearchContext](../search/searchcontext) docs for details). ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Product extends DataObject - { - - private static $searchable_fields = [ - 'Name', - 'ProductCode' - ]; - } +class Product extends DataObject +{ + private static $searchable_fields = [ + 'Name', + 'ProductCode' + ]; +} ```
      @@ -178,21 +174,19 @@ model class, where you can add or remove columns. To change the title, use [Data ```php - use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\DataObject; - class Product extends DataObject - { - - private static $field_labels = [ - 'Price' => 'Cost' // renames the column to "Cost" - ]; - - private static $summary_fields = [ - 'Name', - 'Price' - ]; - } +class Product extends DataObject +{ + private static $field_labels = [ + 'Price' => 'Cost' // renames the column to "Cost" + ]; + private static $summary_fields = [ + 'Name', + 'Price' + ]; +} ``` The results list are retrieved from [SearchContext::getResults()](api:SilverStripe\ORM\Search\SearchContext::getResults()), based on the parameters passed through the search @@ -205,23 +199,22 @@ For example, we might want to exclude all products without prices in our sample ```php - use SilverStripe\Admin\ModelAdmin; +use SilverStripe\Admin\ModelAdmin; - class MyAdmin extends ModelAdmin +class MyAdmin extends ModelAdmin +{ + public function getList() { + $list = parent::getList(); - public function getList() - { - $list = parent::getList(); - - // Always limit by model class, in case you're managing multiple - if($this->modelClass == 'Product') { - $list = $list->exclude('Price', '0'); - } - - return $list; + // Always limit by model class, in case you're managing multiple + if($this->modelClass == 'Product') { + $list = $list->exclude('Price', '0'); } + + return $list; } +} ``` You can also customize the search behavior directly on your `ModelAdmin` instance. For example, we might want to have a @@ -229,38 +222,36 @@ checkbox which limits search results to expensive products (over $100). **mysite/code/MyAdmin.php** - ```php - use SilverStripe\Forms\CheckboxField; - use SilverStripe\Admin\ModelAdmin; +use SilverStripe\Forms\CheckboxField; +use SilverStripe\Admin\ModelAdmin; - class MyAdmin extends ModelAdmin +class MyAdmin extends ModelAdmin +{ + public function getSearchContext() { + $context = parent::getSearchContext(); - public function getSearchContext() - { - $context = parent::getSearchContext(); - - if($this->modelClass == 'Product') { - $context->getFields()->push(new CheckboxField('q[ExpensiveOnly]', 'Only expensive stuff')); - } - - return $context; + if($this->modelClass == 'Product') { + $context->getFields()->push(new CheckboxField('q[ExpensiveOnly]', 'Only expensive stuff')); } - public function getList() - { - $list = parent::getList(); - - $params = $this->getRequest()->requestVar('q'); // use this to access search parameters - - if($this->modelClass == 'Product' && isset($params['ExpensiveOnly']) && $params['ExpensiveOnly']) { - $list = $list->exclude('Price:LessThan', '100'); - } - - return $list; - } + return $context; } + + public function getList() + { + $list = parent::getList(); + + $params = $this->getRequest()->requestVar('q'); // use this to access search parameters + + if($this->modelClass == 'Product' && isset($params['ExpensiveOnly']) && $params['ExpensiveOnly']) { + $list = $list->exclude('Price:LessThan', '100'); + } + + return $list; + } +} ``` To alter how the results are displayed (via [GridField](api:SilverStripe\Forms\GridField\GridField)), you can also overload the `getEditForm()` method. For @@ -270,35 +261,34 @@ example, to add a new component. ```php - use SilverStripe\Forms\GridField\GridFieldFilterHeader; - use SilverStripe\Admin\ModelAdmin; +use SilverStripe\Forms\GridField\GridFieldFilterHeader; +use SilverStripe\Admin\ModelAdmin; - class MyAdmin extends ModelAdmin +class MyAdmin extends ModelAdmin +{ + + private static $managed_models = [ + 'Product', + 'Category' + ]; + + // ... + public function getEditForm($id = null, $fields = null) { + $form = parent::getEditForm($id, $fields); - private static $managed_models = [ - 'Product', - 'Category' - ]; + // $gridFieldName is generated from the ModelClass, eg if the Class 'Product' + // is managed by this ModelAdmin, the GridField for it will also be named 'Product' - // ... - public function getEditForm($id = null, $fields = null) - { - $form = parent::getEditForm($id, $fields); + $gridFieldName = $this->sanitiseClassName($this->modelClass); + $gridField = $form->Fields()->fieldByName($gridFieldName); - // $gridFieldName is generated from the ModelClass, eg if the Class 'Product' - // is managed by this ModelAdmin, the GridField for it will also be named 'Product' + // modify the list view. + $gridField->getConfig()->addComponent(new GridFieldFilterHeader()); - $gridFieldName = $this->sanitiseClassName($this->modelClass); - $gridField = $form->Fields()->fieldByName($gridFieldName); - - // modify the list view. - $gridField->getConfig()->addComponent(new GridFieldFilterHeader()); - - return $form; - } + return $form; } - +} ``` The above example will add the component to all `GridField`s (of all managed models). Alternatively we can also add it @@ -308,32 +298,31 @@ to only one specific `GridField`: ```php - use SilverStripe\Forms\GridField\GridFieldFilterHeader; - use SilverStripe\Admin\ModelAdmin; +use SilverStripe\Forms\GridField\GridFieldFilterHeader; +use SilverStripe\Admin\ModelAdmin; - class MyAdmin extends ModelAdmin +class MyAdmin extends ModelAdmin +{ + + private static $managed_models = [ + 'Product', + 'Category' + ]; + + public function getEditForm($id = null, $fields = null) { + $form = parent::getEditForm($id, $fields); - private static $managed_models = [ - 'Product', - 'Category' - ]; + $gridFieldName = 'Product'; + $gridField = $form->Fields()->fieldByName($gridFieldName); - public function getEditForm($id = null, $fields = null) - { - $form = parent::getEditForm($id, $fields); - - $gridFieldName = 'Product'; - $gridField = $form->Fields()->fieldByName($gridFieldName); - - if ($gridField) { - $gridField->getConfig()->addComponent(new GridFieldFilterHeader()); - } - - return $form; + if ($gridField) { + $gridField->getConfig()->addComponent(new GridFieldFilterHeader()); } - } + return $form; + } +} ``` ## Data Import @@ -354,22 +343,21 @@ To customize the exported columns, create a new method called `getExportFields` ```php - use SilverStripe\Admin\ModelAdmin; +use SilverStripe\Admin\ModelAdmin; - class MyAdmin extends ModelAdmin +class MyAdmin extends ModelAdmin +{ + // ... + + public function getExportFields() { - // ... - - public function getExportFields() - { - return [ - 'Name' => 'Name', - 'ProductCode' => 'Product Code', - 'Category.Title' => 'Category' - ]; - } + return [ + 'Name' => 'Name', + 'ProductCode' => 'Product Code', + 'Category.Title' => 'Category' + ]; } - +} ``` ## Related Documentation diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/02_CMS_Architecture.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/02_CMS_Architecture.md index 90e3e312d..2bd5bf72c 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/02_CMS_Architecture.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/02_CMS_Architecture.md @@ -57,16 +57,16 @@ The CMS interface can be accessed by default through the `admin/` URL. You can c ```yml - --- - Name: myadmin - After: - - '#adminroutes' - --- - SilverStripe\Control\Director: - rules: - 'admin': '' - 'newAdmin': 'AdminRootController' - --- +--- +Name: myadmin +After: + - '#adminroutes' +--- +SilverStripe\Control\Director: + rules: + 'admin': '' + 'newAdmin': 'AdminRootController' +--- ``` When extending the CMS or creating modules, you can take advantage of various functions that will return the configured admin URL (by default 'admin/' is returned): @@ -75,23 +75,21 @@ In PHP you should use: ```php - SilverStripe\Admin\AdminRootController::admin_url() +SilverStripe\Admin\AdminRootController::admin_url() ``` When writing templates use: ```ss - - $AdminURL +$AdminURL ``` And in JavaScript, this is avaible through the `ss` namespace ```js - - ss.config.adminUrl +ss.config.adminUrl ``` ### Multiple Admin URL and overrides @@ -162,45 +160,45 @@ Basic example form in a CMS controller subclass: ```php - use SilverStripe\Forms\TabSet; - use SilverStripe\Forms\FieldList; - use SilverStripe\Forms\Tab; - use SilverStripe\Forms\TextField; - use SilverStripe\Forms\FormAction; - use SilverStripe\Admin\LeftAndMain; - use SilverStripe\Admin\LeftAndMainFormRequestHandler; +use SilverStripe\Forms\TabSet; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\Tab; +use SilverStripe\Forms\TextField; +use SilverStripe\Forms\FormAction; +use SilverStripe\Admin\LeftAndMain; +use SilverStripe\Admin\LeftAndMainFormRequestHandler; - class MyAdmin extends LeftAndMain - { - function getEditForm() { - return Form::create( - $this, - 'EditForm', - new FieldList( - TabSet::create( - 'Root', - Tab::create('Main', - TextField::create('MyText') - ) - )->setTemplate('CMSTabset') - ), - new FieldList( - FormAction::create('doSubmit') - ) +class MyAdmin extends LeftAndMain +{ + public function getEditForm() { + return Form::create( + $this, + 'EditForm', + new FieldList( + TabSet::create( + 'Root', + Tab::create('Main', + TextField::create('MyText') + ) + )->setTemplate('CMSTabset') + ), + new FieldList( + FormAction::create('doSubmit') ) - // Use a custom request handler - ->setRequestHandler( - LeftAndMainFormRequestHandler::create($form) - ) - // JS and CSS use this identifier - ->setHTMLID('Form_EditForm') - // Render correct responses on validation errors - ->setResponseNegotiator($this->getResponseNegotiator()); - // Required for correct CMS layout - ->addExtraClass('cms-edit-form') - ->setTemplate($this->getTemplatesWithSuffix('_EditForm')); - } + ) + // Use a custom request handler + ->setRequestHandler( + LeftAndMainFormRequestHandler::create($form) + ) + // JS and CSS use this identifier + ->setHTMLID('Form_EditForm') + // Render correct responses on validation errors + ->setResponseNegotiator($this->getResponseNegotiator()); + // Required for correct CMS layout + ->addExtraClass('cms-edit-form') + ->setTemplate($this->getTemplatesWithSuffix('_EditForm')); } +} ``` Note: Usually you don't need to worry about these settings, @@ -306,48 +304,48 @@ routing mechanism for this section. However, there are two major differences: Firstly, `reactRouter` must be passed as a boolean flag to indicate that this section is controlled by the react section, and thus should suppress registration of a page.js route for this section. -```php - public function getClientConfig() - { - return array_merge(parent::getClientConfig(), [ - 'reactRouter' => true - ]); - } +```php +public function getClientConfig() +{ + return array_merge(parent::getClientConfig(), [ + 'reactRouter' => true + ]); +} ``` Secondly, you should ensure that your react CMS section triggers route registration on the client side with the reactRouteRegister component. This will need to be done on the `DOMContentLoaded` event to ensure routes are registered before window.load is invoked. -```js - import { withRouter } from 'react-router'; - import ConfigHelpers from 'lib/Config'; - import reactRouteRegister from 'lib/ReactRouteRegister'; - import MyAdmin from './MyAdmin'; - - document.addEventListener('DOMContentLoaded', () => { - const sectionConfig = ConfigHelpers.getSection('MyAdmin'); - - reactRouteRegister.add({ - path: sectionConfig.url, - component: withRouter(MyAdminComponent), - childRoutes: [ - { path: 'form/:id/:view', component: MyAdminComponent }, - ], - }); +```js +import { withRouter } from 'react-router'; +import ConfigHelpers from 'lib/Config'; +import reactRouteRegister from 'lib/ReactRouteRegister'; +import MyAdmin from './MyAdmin'; + +document.addEventListener('DOMContentLoaded', () => { + const sectionConfig = ConfigHelpers.getSection('MyAdmin'); + + reactRouteRegister.add({ + path: sectionConfig.url, + component: withRouter(MyAdminComponent), + childRoutes: [ + { path: 'form/:id/:view', component: MyAdminComponent }, + ], }); +}); ``` Child routes can be registered post-boot by using `ReactRouteRegister` in the same way. -```js - // Register a nested url under `sectionConfig.url` - const sectionConfig = ConfigHelpers.getSection('MyAdmin'); - reactRouteRegister.add({ - path: 'nested', - component: NestedComponent, - }, [ sectionConfig.url ]); +```js +// Register a nested url under `sectionConfig.url` +const sectionConfig = ConfigHelpers.getSection('MyAdmin'); +reactRouteRegister.add({ + path: 'nested', + component: NestedComponent, +}, [ sectionConfig.url ]); ``` ## PJAX: Partial template replacement through Ajax @@ -375,57 +373,57 @@ in a single Ajax request. ```php - use SilverStripe\Admin\LeftAndMain; +use SilverStripe\Admin\LeftAndMain; - // mysite/code/MyAdmin.php - class MyAdmin extends LeftAndMain +// mysite/code/MyAdmin.php +class MyAdmin extends LeftAndMain +{ + private static $url_segment = 'myadmin'; + public function getResponseNegotiator() { - private static $url_segment = 'myadmin'; - public function getResponseNegotiator() - { - $negotiator = parent::getResponseNegotiator(); - $controller = $this; - // Register a new callback - $negotiator->setCallback('MyRecordInfo', function() use(&$controller) { - return $controller->MyRecordInfo(); - }); - return $negotiator; - } - public function MyRecordInfo() - { - return $this->renderWith('MyRecordInfo'); - } + $negotiator = parent::getResponseNegotiator(); + $controller = $this; + // Register a new callback + $negotiator->setCallback('MyRecordInfo', function() use(&$controller) { + return $controller->MyRecordInfo(); + }); + return $negotiator; } + public function MyRecordInfo() + { + return $this->renderWith('MyRecordInfo'); + } +} ``` ```js - // MyAdmin.ss - <% include SilverStripe\\Admin\\CMSBreadcrumbs %> -
      Static content (not affected by update)
      - <% include MyRecordInfo %> - - Update record info - +// MyAdmin.ss +<% include SilverStripe\\Admin\\CMSBreadcrumbs %> +
      Static content (not affected by update)
      +<% include MyRecordInfo %> + + Update record info + ``` ```ss - // MyRecordInfo.ss -
      - Current Record: $currentPage.Title -
      +// MyRecordInfo.ss +
      + Current Record: $currentPage.Title +
      ``` A click on the link will cause the following (abbreviated) ajax HTTP request: ``` - GET /admin/myadmin HTTP/1.1 - X-Pjax:MyRecordInfo,Breadcrumbs - X-Requested-With:XMLHttpRequest +GET /admin/myadmin HTTP/1.1 +X-Pjax:MyRecordInfo,Breadcrumbs +X-Requested-With:XMLHttpRequest ``` ... and result in the following response: ``` - {"MyRecordInfo": "getResponse()->addHeader('X-Controller', 'MyOtherController'); - return $html; - } + // ... + $this->getResponse()->addHeader('X-Controller', 'MyOtherController'); + return $html; } +} ``` Built-in headers are: - * `X-Title`: Set window title (requires URL encoding) - * `X-Controller`: PHP class name matching a menu entry, which is marked active - * `X-ControllerURL`: Alternative URL to record in the HTML5 browser history - * `X-Status`: Extended status information, used for an information popover. - * `X-Reload`: Force a full page reload based on `X-ControllerURL` + * `X-Title`: Set window title (requires URL encoding) + * `X-Controller`: PHP class name matching a menu entry, which is marked active + * `X-ControllerURL`: Alternative URL to record in the HTML5 browser history + * `X-Status`: Extended status information, used for an information popover. + * `X-Reload`: Force a full page reload based on `X-ControllerURL` ## Special Links @@ -572,12 +580,12 @@ which is picked up by the menu: ```php - public function mycontrollermethod() - { - // .. logic here - $this->getResponse()->addHeader('X-Controller', 'AssetAdmin'); - return 'my response'; - } +public function mycontrollermethod() +{ + // .. logic here + $this->getResponse()->addHeader('X-Controller', 'AssetAdmin'); + return 'my response'; +} ``` This is usually handled by the existing [LeftAndMain](api:SilverStripe\Admin\LeftAndMain) logic, @@ -626,29 +634,29 @@ Form template with custom tab navigation (trimmed down): ```ss -
      + -
      - <% if Fields.hasTabset %> - <% with Fields.fieldByName('Root') %> -
      -
        - <% loop Tabs %> -
      • $Title
      • - <% end_loop %> -
      -
      - <% end_with %> - <% end_if %> -
      +
      + <% if Fields.hasTabset %> + <% with Fields.fieldByName('Root') %> +
      +
        + <% loop Tabs %> +
      • $Title
      • + <% end_loop %> +
      +
      + <% end_with %> + <% end_if %> +
      -
      -
      - <% loop Fields %>$FieldHolder<% end_loop %> -
      -
      +
      +
      + <% loop Fields %>$FieldHolder<% end_loop %> +
      +
      -
      + ``` Tabset template without tab navigation (e.g. `CMSTabset.ss`) @@ -656,19 +664,19 @@ Tabset template without tab navigation (e.g. `CMSTabset.ss`) ```ss -
      - <% loop Tabs %> - <% if Tabs %> - $FieldHolder - <% else %> -
      - <% loop Fields %> - $FieldHolder - <% end_loop %> -
      - <% end_if %> - <% end_loop %> -
      +
      + <% loop Tabs %> + <% if Tabs %> + $FieldHolder + <% else %> +
      + <% loop Fields %> + $FieldHolder + <% end_loop %> +
      + <% end_if %> + <% end_loop %> +
      ``` Lazy loading works based on the `href` attribute of the tab navigation. @@ -682,20 +690,20 @@ and load the HTML content into the main view. Example: ```ss -
      - -
      +
      + +
      ``` The URL endpoints `{$AdminURL}mytabs/tab1` and `{$AdminURL}mytabs/tab2` diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/03_CMS_Layout.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/03_CMS_Layout.md index fff88e1bf..1d2d94c13 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/03_CMS_Layout.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/03_CMS_Layout.md @@ -23,8 +23,7 @@ The easiest way to update the layout of the CMS is to call `redraw` on the top-l ```js - - $('.cms-container').redraw(); +$('.cms-container').redraw(); ``` This causes the framework to: @@ -65,13 +64,12 @@ Layout manager will automatically apply algorithms to the children of `.cms-cont ```html - -
      - <%-- content utilising border's north, south, east, west and center classes --%> -
      +
      + <%-- content utilising border's north, south, east, west and center classes --%> +
      ``` For detailed discussion on available algorithms refer to @@ -112,8 +110,7 @@ Use provided factory method to generate algorithm instances. ```js - - jLayout.threeColumnCompressor(, ); +jLayout.threeColumnCompressor(, ); ``` The parameters are as follows: diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/04_Preview.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/04_Preview.md index 7c8532a5e..2e8c9b4f7 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/04_Preview.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/04_Preview.md @@ -52,28 +52,27 @@ Note how the configuration happens in different entwine namespaces ```js - - (function($) { - $.entwine('ss.preview', function($){ - $('.cms-preview').entwine({ - DefaultMode: 'content', - getSizes: function() { - var sizes = this._super(); - sizes.mobile.width = '400px'; - return sizes; - } - }); +(function($) { + $.entwine('ss.preview', function($){ + $('.cms-preview').entwine({ + DefaultMode: 'content', + getSizes: function() { + var sizes = this._super(); + sizes.mobile.width = '400px'; + return sizes; + } }); - $.entwine('ss', function($){ - $('.cms-container').entwine({ - getLayoutOptions: function() { - var opts = this._super(); - opts.minPreviewWidth = 600; - return opts; - } - }); + }); + $.entwine('ss', function($){ + $('.cms-container').entwine({ + getLayoutOptions: function() { + var opts = this._super(); + opts.minPreviewWidth = 600; + return opts; + } }); - }(jQuery)); + }); +}(jQuery)); ``` Load the file in the CMS via setting adding 'mysite/javascript/MyLeftAndMain.Preview.js' @@ -81,10 +80,9 @@ to the `LeftAndMain.extra_requirements_javascript` [configuration value](../conf ```yml - - SilverStripe\Admin\LeftAndMain: - extra_requirements_javascript: - - mysite/javascript/MyLeftAndMain.Preview.js +SilverStripe\Admin\LeftAndMain: + extra_requirements_javascript: + - mysite/javascript/MyLeftAndMain.Preview.js ``` In order to find out which configuration values are available, the source code @@ -115,9 +113,9 @@ property. States are the site stages: _live_, _stage_ etc. Preview states are picked up from the `SilverStripeNavigator`. You can invoke the state change by calling: - ```js - $('.cms-preview').entwine('.ss.preview').changeState('StageLink'); - ``` +```js +$('.cms-preview').entwine('.ss.preview').changeState('StageLink'); +``` Note the state names come from `SilverStripeNavigatorItems` class names - thus the _Link_ in their names. This call will also redraw the state selector to fit @@ -126,9 +124,9 @@ list of supported states. You can get the current state by calling: - ```js - $('.cms-preview').entwine('.ss.preview').getCurrentStateName(); - ``` +```js +$('.cms-preview').entwine('.ss.preview').getCurrentStateName(); +``` ## Preview sizes @@ -145,15 +143,15 @@ You can switch between different types of display sizes programmatically, which has the benefit of redrawing the related selector and maintaining a consistent internal state: - ```js - $('.cms-preview').entwine('.ss.preview').changeSize('auto'); - ``` +```js +$('.cms-preview').entwine('.ss.preview').changeSize('auto'); +``` You can find out current size by calling: - ```js - $('.cms-preview').entwine('.ss.preview').getCurrentSizeName(); - ``` +```js +$('.cms-preview').entwine('.ss.preview').getCurrentSizeName(); +``` ## Preview modes @@ -161,16 +159,16 @@ Preview modes map to the modes supported by the _threeColumnCompressor_ layout algorithm, see [layout reference](cms_layout) for more details. You can change modes by calling: - ```js - $('.cms-preview').entwine('.ss.preview').changeMode('preview'); - ``` +```js +$('.cms-preview').entwine('.ss.preview').changeMode('preview'); +``` Currently active mode is stored on the `.cms-container` along with related internal states of the layout. You can reach it by calling: - ```js - $('.cms-container').entwine('.ss').getLayoutOptions().mode; - ``` +```js +$('.cms-container').entwine('.ss').getLayoutOptions().mode; +```
      Caveat: the `.preview-mode-selector` appears twice, once in the preview and diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/05_Typography.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/05_Typography.md index 1497af63a..cc52dfebb 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/05_Typography.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/05_Typography.md @@ -8,9 +8,9 @@ SilverStripe lets you customise the style of content in the CMS. This is done by ```php - use SilverStripe\Forms\HTMLEditor\HtmlEditorConfig; - - HtmlEditorConfig::get('cms')->setOption('content_css', project() . '/css/editor.css'); +use SilverStripe\Forms\HTMLEditor\HtmlEditorConfig; + +HtmlEditorConfig::get('cms')->setOption('content_css', project() . '/css/editor.css'); ``` Will load the `mysite/css/editor.css` file. @@ -19,7 +19,7 @@ If using this config option in `mysite/_config.php`, you will have to instead ca ```php - HtmlEditorConfig::get('cms')->setOption('content_css', project() . '/css/editor.css'); +HtmlEditorConfig::get('cms')->setOption('content_css', project() . '/css/editor.css'); ``` Any CSS classes within this file will be automatically added to the `WYSIWYG` editors 'style' dropdown. For instance, to @@ -27,10 +27,9 @@ add the color 'red' as an option within the `WYSIWYG` add the following to the ` ```css - - .red { - color: red; - } +.red { + color: red; +} ```
      diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/06_Javascript_Development.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/06_Javascript_Development.md index dc2b1277f..aa50df875 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/06_Javascript_Development.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/06_Javascript_Development.md @@ -45,13 +45,12 @@ plugin. See "[How jQuery Works](http://docs.jquery.com/How_jQuery_Works)" for a You should write all your custom jQuery code in a closure. -```javascript - - (function($) { - $(document).ready(function(){ - // your code here. - }) - })(jQuery); +```js +(function($) { + $(document).ready(function(){ + // your code here. + }) +})(jQuery); ``` ## jQuery Plugins @@ -75,49 +74,47 @@ Example: A plugin to highlight a collection of elements with a configurable fore ```js - - // create closure - (function($) { - // plugin definition - $.fn.hilight = function(options) { - // build main options before element iteration - var opts = $.extend({}, $.fn.hilight.defaults, options); - // iterate and reformat each matched element - return this.each(function() { - $this = $(this); - // build element specific options - var o = $.meta ? $.extend({}, opts, $this.data()) : opts; - // update element styles - $this.css({ - backgroundColor: o.background, - color: o.foreground - }); - }); - }; - // plugin defaults - $.fn.hilight.defaults = { - foreground: "red", - background: "yellow" - }; - // end of closure - })(jQuery); +// create closure +(function($) { + // plugin definition + $.fn.hilight = function(options) { + // build main options before element iteration + var opts = $.extend({}, $.fn.hilight.defaults, options); + // iterate and reformat each matched element + return this.each(function() { + $this = $(this); + // build element specific options + var o = $.meta ? $.extend({}, opts, $this.data()) : opts; + // update element styles + $this.css({ + backgroundColor: o.background, + color: o.foreground + }); + }); + }; + // plugin defaults + $.fn.hilight.defaults = { + foreground: "red", + background: "yellow" + }; +// end of closure +})(jQuery); ``` Usage: ```js +(function($) { + // Highlight all buttons with default colours + jQuery(':button').highlight(); - (function($) { - // Highlight all buttons with default colours - jQuery(':button').highlight(); + // Highlight all buttons with green background + jQuery(':button').highlight({background: "green"}); - // Highlight all buttons with green background - jQuery(':button').highlight({background: "green"}); - - // Set all further highlight() calls to have a green background - $.fn.hilight.defaults.background = "green"; - })(jQuery); + // Set all further highlight() calls to have a green background + $.fn.hilight.defaults.background = "green"; +})(jQuery); ``` ## jQuery UI Widgets @@ -137,57 +134,54 @@ See the [official developer guide](http://jqueryui.com/docs/Developer_Guide) and Example: Highlighter - ```js - - (function($) { - $.widget("ui.myHighlight", { - getBlink: function () { - return this._getData('blink'); - }, - setBlink: function (blink) { - this._setData('blink', blink); - if(blink) this.element.wrapInner(''); - else this.element.html(this.element.children().html()); - }, - _init: function() { - // 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); +(function($) { + $.widget("ui.myHighlight", { + getBlink: function () { + return this._getData('blink'); + }, + setBlink: function (blink) { + this._setData('blink', blink); + if(blink) this.element.wrapInner(''); + else this.element.html(this.element.children().html()); + }, + _init: function() { + // 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); ``` Usage: ```js +(function($) { + // call with default options + $(':button').myHighlight(); - (function($) { - // call with default options - $(':button').myHighlight(); + // call with custom options + $(':button').myHighlight({background: "green"}); - // call with custom options - $(':button').myHighlight({background: "green"}); + // set defaults for all future instances + $.ui.myHighlight.defaults.background = "green"; - // set defaults for all future instances - $.ui.myHighlight.defaults.background = "green"; + // Adjust property after initialization + $(':button').myHighlight('setBlink', true); - // Adjust property after initialization - $(':button').myHighlight('setBlink', true); - - // Get property - $(':button').myHighlight('getBlink'); - })(jQuery); + // Get property + $(':button').myHighlight('getBlink'); +})(jQuery); ``` ### jQuery.Entwine @@ -205,34 +199,32 @@ Example: Highlighter ```js - - (function($) { - $(':button').entwine({ - Foreground: 'red', - Background: 'yellow', - highlight: function() { - this.css('background', this.getBackground()); - this.css('color', this.getForeground()); - } - }); - })(jQuery); +(function($) { + $(':button').entwine({ + Foreground: 'red', + Background: 'yellow', + highlight: function() { + this.css('background', this.getBackground()); + this.css('color', this.getForeground()); + } + }); +})(jQuery); ``` Usage: ```js +(function($) { + // call with default options + $(':button').entwine().highlight(); - (function($) { - // call with default options - $(':button').entwine().highlight(); + // set options for existing and new instances + $(':button').entwine().setBackground('green'); - // set options for existing and new instances - $(':button').entwine().setBackground('green'); - - // get property - $(':button').entwine().getBackground(); - })(jQuery); + // get property + $(':button').entwine().getBackground(); +})(jQuery); ``` This is a deliberately simple example, the strength of jQuery.entwine over simple jQuery plugins lies in its public @@ -255,12 +247,11 @@ Global properties are evil. They are accessible by other scripts, might be overw ```js - - // you can't rely on '$' being defined outside of the closure - (function($) { - var myPrivateVar; // only available inside the closure - // inside here you can use the 'jQuery' object as '$' - })(jQuery); +// you can't rely on '$' being defined outside of the closure +(function($) { + var myPrivateVar; // only available inside the closure + // inside here you can use the 'jQuery' object as '$' +})(jQuery); ``` You can run `[jQuery.noConflict()](http://docs.jquery.com/Core/jQuery.noConflict)` to avoid namespace clashes. @@ -273,11 +264,10 @@ the `window.onload` and `document.ready` events. ```js - - // DOM elements might not be available here - $(document).ready(function() { - // The DOM is fully loaded here - }); +// DOM elements might not be available here +$(document).ready(function() { + // The DOM is fully loaded here +}); ``` See [jQuery FAQ: Launching Code on Document @@ -292,18 +282,16 @@ Caution: Only applies to certain events, see the [jQuery.on() documentation](htt Example: Add a 'loading' classname to all pressed buttons - ```js +// manual binding, only applies to existing elements +$('input[[type=submit]]').on('click', function() { + $(this).addClass('loading'); +}); - // manual binding, only applies to existing elements - $('input[[type=submit]]').on('click', function() { - $(this).addClass('loading'); - }); - - // binding, applies to any inserted elements as well - $('.cms-container').on('click', 'input[[type=submit]]', function() { - $(this).addClass('loading'); - }); +// binding, applies to any inserted elements as well +$('.cms-container').on('click', 'input[[type=submit]]', function() { + $(this).addClass('loading'); +}); ``` ### Assume Element Collections @@ -313,13 +301,12 @@ makes sense). Encapsulate your code by nesting your jQuery commands inside a `jQ ```js - - $('div.MyGridField').each(function() { - // This is the over code for the tr elements inside a GridField. - $(this).find('tr').hover( - // ... - ); - }); +$('div.MyGridField').each(function() { + // This is the over code for the tr elements inside a GridField. + $(this).find('tr').hover( + // ... + ); +}); ``` ### Use plain HTML and jQuery.data() to store data @@ -333,27 +320,24 @@ Through CSS properties ```js - - $('form :input').bind('change', function(e) { - $(this.form).addClass('isChanged'); - }); - $('form').bind('submit', function(e) { - if($(this).hasClass('isChanged')) return false; - }); +$('form :input').bind('change', function(e) { + $(this.form).addClass('isChanged'); +}); +$('form').bind('submit', function(e) { + if($(this).hasClass('isChanged')) return false; +}); ``` Through jQuery.data() - ```js - - $('form :input').bind('change', function(e) { - $(this.form).data('isChanged', true); - }); - $('form').bind('submit', function(e) { - alert($(this).data('isChanged')); - if($(this).data('isChanged')) return false; - }); +$('form :input').bind('change', function(e) { + $(this.form).data('isChanged', true); +}); +$('form').bind('submit', function(e) { + alert($(this).data('isChanged')); + if($(this).data('isChanged')) return false; +}); ``` See [interactive example on jsbin.com](http://jsbin.com/opuva) @@ -364,25 +348,20 @@ rendering a form element through the SilverStripe templating engine. Example: Restricted numeric value field - ```ss - - + ``` - - ```js - - $('.restricted-text').bind('change', function(e) { - if( - e.target.value < $(this).metadata().min - || e.target.value > $(this).metadata().max - ) { - alert('Invalid value'); - return false; - } - }); +$('.restricted-text').bind('change', function(e) { + if( + e.target.value < $(this).metadata().min + || e.target.value > $(this).metadata().max + ) { + alert('Invalid value'); + return false; + } +}); ``` See [interactive example on jsbin.com](http://jsbin.com/axafa) @@ -407,77 +386,73 @@ Template: ```ss - -
        - <% loop $Results %> -
      • $Title
      • - <% end_loop %> -
      +
        +<% loop $Results %> +
      • $Title
      • +<% end_loop %> +
      ``` PHP: ```php - use SilverStripe\Control\HTTPResponse; - use SilverStripe\View\ViewableData; +use SilverStripe\Control\HTTPResponse; +use SilverStripe\View\ViewableData; - class MyController - { - public function autocomplete($request) - { - $results = Page::get()->filter("Title", $request->getVar('title')); - if(!$results) return new HTTPResponse("Not found", 404); +class MyController +{ + public function autocomplete($request) + { + $results = Page::get()->filter("Title", $request->getVar('title')); + if(!$results) return new HTTPResponse("Not found", 404); - // Use HTTPResponse to pass custom status messages - $this->getResponse()->setStatusCode(200, "Found " . $results->Count() . " elements"); - - // render all results with a custom template - $vd = new ViewableData(); - return $vd->customise([ - "Results" => $results - ])->renderWith('AutoComplete'); - } - } + // Use HTTPResponse to pass custom status messages + $this->getResponse()->setStatusCode(200, "Found " . $results->Count() . " elements"); + // render all results with a custom template + $vd = new ViewableData(); + return $vd->customise([ + "Results" => $results + ])->renderWith('AutoComplete'); + } +} ``` HTML ```ss - -
      -
      - - - - +
      +
      + + + + ``` JavaScript: ```js - - $('.autocomplete input').on('change', function() { - var resultsEl = $(this).siblings('.results'); - resultsEl.load( - // get form action, using the jQuery.metadata plugin - $(this).parent().metadata().url, - // submit all form values - $(this.form).serialize(), - // callback after data is loaded - function(data, status) { - resultsEl.show(); - // get all record IDs from the new HTML - var ids = jQuery('.results').find('li').map(function() { - return $(this).attr('id').replace(/Record\-/,''); - }); - } - ); - }); +$('.autocomplete input').on('change', function() { + var resultsEl = $(this).siblings('.results'); + resultsEl.load( + // get form action, using the jQuery.metadata plugin + $(this).parent().metadata().url, + // submit all form values + $(this.form).serialize(), + // callback after data is loaded + function(data, status) { + resultsEl.show(); + // get all record IDs from the new HTML + var ids = jQuery('.results').find('li').map(function() { + return $(this).attr('id').replace(/Record\-/,''); + }); + } + ); +}); ``` Although they are the minority of cases, there are times when a simple HTML fragment isn't enough. For example, if you @@ -501,21 +476,20 @@ Example: Trigger custom 'validationfailed' event on form submission for each emp ```js +$('form').bind('submit', function(e) { + // $(this) refers to form + $(this).find(':input').each(function() { + // $(this) in here refers to input field + if(!$(this).val()) $(this).trigger('validationfailed'); + }); + return false; +}); - $('form').bind('submit', function(e) { - // $(this) refers to form - $(this).find(':input').each(function() { - // $(this) in here refers to input field - if(!$(this).val()) $(this).trigger('validationfailed'); - }); - return false; - }); - - // listen to custom event on each field - $('form :input').bind('validationfailed',function(e) { - // $(this) refers to input field - alert($(this).attr('name')); - }); +// listen to custom event on each field +$('form :input').bind('validationfailed',function(e) { + // $(this) refers to input field + alert($(this).attr('name')); +}); ``` See [interactive example on jsbin.com](http://jsbin.com/ipeca). @@ -558,55 +532,53 @@ JSDoc-toolkit is a command line utility, see [usage](http://code.google.com/p/js Example: jQuery.entwine - ```js +/** + + * Available Custom Events: + *
        + *
      • ajaxsubmit
      • + *
      • validate
      • + *
      • reloadeditform
      • + *
      + * + * @class Main LeftAndMain interface with some control panel and an edit form. + * @name ss.LeftAndMain + */ +$('.LeftAndMain').entwine('ss', function($){ + return/** @lends ss.LeftAndMain */ { + /** + + * Reference to some property + * @type Number + */ + MyProperty: 123, /** - * Available Custom Events: - *
        - *
      • ajaxsubmit
      • - *
      • validate
      • - *
      • reloadeditform
      • - *
      + * Renders the provided data into an unordered list. * - * @class Main LeftAndMain interface with some control panel and an edit form. - * @name ss.LeftAndMain + * @param {Object} data + * @param {String} status + * @return {String} HTML unordered list */ - $('.LeftAndMain').entwine('ss', function($){ - return/** @lends ss.LeftAndMain */ { - /** + publicMethod: function(data, status) { + return '
        ' + + /... + + '
      '; + }, - * 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: function(data, status) { - return '
        ' - + /... - + '
      '; - }, - - /** - - * Won't show in documentation, but still worth documenting. - * - * @return {String} Something else. - */ - _privateMethod: function() { - // ... - } - }; - ]]); + * Won't show in documentation, but still worth documenting. + * + * @return {String} Something else. + */ + _privateMethod: function() { + // ... + } + }; +]]); ``` ### Unit Testing @@ -619,31 +591,31 @@ start with JSpec, as it provides a much more powerful testing framework. Example: QUnit test (from [jquery.com](http://docs.jquery.com/QUnit#Using_QUnit)): - ```js - - test("a basic test example", function() { - ok( true, "this test is fine" ); - var value = "hello"; - equals( "hello", value, "We expect value to be hello" ); - }); +test("a basic test example", function() { + ok( true, "this test is fine" ); + var value = "hello"; + equals( "hello", value, "We expect value to be hello" ); +}); ``` Example: JSpec Shopping cart test (from [visionmedia.github.com](http://visionmedia.github.com/jspec/)) + ``` - 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 +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 ``` + ## Related * [Unobtrusive Javascript](http://www.onlinetools.org/articles/unobtrusivejavascript/chapter1.html) diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/CMS_Alternating_Button.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/CMS_Alternating_Button.md index d11fbf67a..704ca1c22 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/CMS_Alternating_Button.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/CMS_Alternating_Button.md @@ -28,21 +28,21 @@ Here is the configuration code for the button: ```php - public function getCMSActions() - { - $fields = parent::getCMSActions(); +public function getCMSActions() +{ + $fields = parent::getCMSActions(); - $fields->fieldByName('MajorActions')->push( - $cleanupAction = FormAction::create('cleanup', 'Cleaned') - // Set up an icon for the neutral state that will use the default text. - ->setAttribute('data-icon', 'accept') - // Initialise the alternate constructive state. - ->setAttribute('data-icon-alternate', 'addpage') - ->setAttribute('data-text-alternate', 'Clean-up now') - ); + $fields->fieldByName('MajorActions')->push( + $cleanupAction = FormAction::create('cleanup', 'Cleaned') + // Set up an icon for the neutral state that will use the default text. + ->setAttribute('data-icon', 'accept') + // Initialise the alternate constructive state. + ->setAttribute('data-icon-alternate', 'addpage') + ->setAttribute('data-text-alternate', 'Clean-up now') + ); - return $fields; - } + return $fields; +} ``` You can control the state of the button from the backend by applying `ss-ui-alternate` class to the `FormAction`. To @@ -55,15 +55,15 @@ Here we initialise the button based on the backend check, and assume that the bu ```php - public function getCMSActions() - { - // ... - if ($this->needsCleaning()) { - // Will initialise the button into alternate state. - $cleanupAction->addExtraClass('ss-ui-alternate'); - } - // ... +public function getCMSActions() +{ + // ... + if ($this->needsCleaning()) { + // Will initialise the button into alternate state. + $cleanupAction->addExtraClass('ss-ui-alternate'); } + // ... +} ``` ## Frontend support @@ -80,24 +80,21 @@ First of all, you can toggle the state of the button - execute this code in the ```js - - jQuery('.cms-edit-form .btn-toolbar #Form_EditForm_action_cleanup').button('toggleAlternate'); +jQuery('.cms-edit-form .btn-toolbar #Form_EditForm_action_cleanup').button('toggleAlternate'); ``` Another, more useful, scenario is to check the current state. ```js - - jQuery('.cms-edit-form .btn-toolbar #Form_EditForm_action_cleanup').button('option', 'showingAlternate'); +jQuery('.cms-edit-form .btn-toolbar #Form_EditForm_action_cleanup').button('option', 'showingAlternate'); ``` You can also force the button into a specific state by using UI options. ```js - - jQuery('.cms-edit-form .btn-toolbar #Form_EditForm_action_cleanup').button({showingAlternate: true}); +jQuery('.cms-edit-form .btn-toolbar #Form_EditForm_action_cleanup').button({showingAlternate: true}); ``` This will allow you to react to user actions in the CMS and give immediate feedback. Here is an example taken from the @@ -106,24 +103,23 @@ CMS core that tracks the changes to the input fields and reacts by enabling the ```js - - /** - * Enable save buttons upon detecting changes to content. - * "changed" class is added by jQuery.changetracker. - */ - $('.cms-edit-form .changed').entwine({ - // This will execute when the class is added to the element. - onmatch: function(e) { - var form = this.closest('.cms-edit-form'); - form.find('#Form_EditForm_action_save').button({showingAlternate: true}); - form.find('#Form_EditForm_action_publish').button({showingAlternate: true}); - this._super(e); - }, - // Entwine requires us to define this, even if we don't use it. - onunmatch: function(e) { - this._super(e); - } - }); +/** + * Enable save buttons upon detecting changes to content. + * "changed" class is added by jQuery.changetracker. + */ +$('.cms-edit-form .changed').entwine({ + // This will execute when the class is added to the element. + onmatch: function(e) { + var form = this.closest('.cms-edit-form'); + form.find('#Form_EditForm_action_save').button({showingAlternate: true}); + form.find('#Form_EditForm_action_publish').button({showingAlternate: true}); + this._super(e); + }, + // Entwine requires us to define this, even if we don't use it. + onunmatch: function(e) { + this._super(e); + } +}); ``` ## Frontend hooks @@ -156,27 +152,26 @@ cases. ```js +(function($) { - (function($) { - - $.entwine('mysite', function($){ - $('.cms-edit-form .btn-toolbar #Form_EditForm_action_cleanup').entwine({ - /** - * onafterrefreshalternate is SS-specific jQuery UI hook that is executed - * every time the button is rendered (including on initialisation). - */ - onbuttonafterrefreshalternate: function() { - if (this.button('option', 'showingAlternate')) { - this.addClass('ss-ui-action-constructive'); - } - else { - this.removeClass('ss-ui-action-constructive'); - } + $.entwine('mysite', function($){ + $('.cms-edit-form .btn-toolbar #Form_EditForm_action_cleanup').entwine({ + /** + * onafterrefreshalternate is SS-specific jQuery UI hook that is executed + * every time the button is rendered (including on initialisation). + */ + onbuttonafterrefreshalternate: function() { + if (this.button('option', 'showingAlternate')) { + this.addClass('ss-ui-action-constructive'); } - }); + else { + this.removeClass('ss-ui-action-constructive'); + } + } }); + }); - }(jQuery)); +}(jQuery)); ``` ## Summary diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/CMS_Formfield_Help_Text.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/CMS_Formfield_Help_Text.md index 7582f184a..57fd0bd88 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/CMS_Formfield_Help_Text.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/CMS_Formfield_Help_Text.md @@ -11,10 +11,10 @@ at the last position within the field, and expects unescaped HTML content. ```php - use SilverStripe\Forms\TextField; - - TextField::create('MyText', 'My Text Label') - ->setDescription('More detailed help'); +use SilverStripe\Forms\TextField; + +TextField::create('MyText', 'My Text Label') + ->setDescription('More detailed help'); ``` To show the help text as a tooltip instead of inline, @@ -22,9 +22,9 @@ add a `.cms-description-tooltip` class. ```php - TextField::create('MyText', 'My Text Label') - ->setDescription('More detailed help') - ->addExtraClass('cms-description-tooltip'); +TextField::create('MyText', 'My Text Label') + ->setDescription('More detailed help') + ->addExtraClass('cms-description-tooltip'); ``` Tooltips are only supported @@ -42,9 +42,9 @@ by clicking the 'info' icon displayed alongside the field. ```php - TextField::create('MyText', 'My Text Label') - ->setDescription('More detailed help') - ->addExtraClass('cms-description-toggle'); +TextField::create('MyText', 'My Text Label') + ->setDescription('More detailed help') + ->addExtraClass('cms-description-toggle'); ``` If you want to provide a custom icon for toggling the description, you can do that @@ -52,10 +52,10 @@ by setting an additional `RightTitle`. ```php - TextField::create('MyText', 'My Text Label') - ->setDescription('More detailed help') - ->addExtraClass('cms-description-toggle') - ->setRightTitle('My custom icon'); +TextField::create('MyText', 'My Text Label') + ->setDescription('More detailed help') + ->addExtraClass('cms-description-toggle') + ->setRightTitle('My custom icon'); ``` Note: For more advanced help text we recommend using diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Menu.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Menu.md index 703e0fc28..343e0c9f0 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Menu.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Menu.md @@ -22,13 +22,13 @@ black-and-transparent PNG graphics. In this case we'll place the icon in ```php - use SilverStripe\Admin\ModelAdmin; +use SilverStripe\Admin\ModelAdmin; - class ProductAdmin extends ModelAdmin - { - // ... - private static $menu_icon = 'mysite/images/product-icon.png'; - } +class ProductAdmin extends ModelAdmin +{ + // ... + private static $menu_icon = 'mysite/images/product-icon.png'; +} ``` ### Defining a Custom Title @@ -39,13 +39,13 @@ controller, removing the "Admin" bit at the end. ```php - use SilverStripe\Admin\ModelAdmin; +use SilverStripe\Admin\ModelAdmin; - class ProductAdmin extends ModelAdmin - { - // ... - private static $menu_title = 'My Custom Admin'; - } +class ProductAdmin extends ModelAdmin +{ + // ... + private static $menu_title = 'My Custom Admin'; +} ``` In order to localize the menu title in different languages, use the @@ -66,37 +66,36 @@ button configuration. ```php - use SilverStripe\Admin\CMSMenu; - use SilverStripe\Admin\LeftAndMainExtension; +use SilverStripe\Admin\CMSMenu; +use SilverStripe\Admin\LeftAndMainExtension; - class CustomLeftAndMain extends LeftAndMainExtension +class CustomLeftAndMain extends LeftAndMainExtension +{ + + public function init() { + // unique identifier for this item. Will have an ID of Menu-$ID + $id = 'LinkToGoogle'; - public function init() - { - // unique identifier for this item. Will have an ID of Menu-$ID - $id = 'LinkToGoogle'; + // your 'nice' title + $title = 'Google'; - // your 'nice' title - $title = 'Google'; + // the link you want to item to go to + $link = 'http://google.com'; - // the link you want to item to go to - $link = 'http://google.com'; + // priority controls the ordering of the link in the stack. The + // lower the number, the lower in the list + $priority = -2; - // priority controls the ordering of the link in the stack. The - // lower the number, the lower in the list - $priority = -2; + // Add your own attributes onto the link. In our case, we want to + // open the link in a new window (not the original) + $attributes = [ + 'target' => '_blank' + ]; - // Add your own attributes onto the link. In our case, we want to - // open the link in a new window (not the original) - $attributes = [ - 'target' => '_blank' - ]; - - CMSMenu::add_link($id, $title, $link, $priority, $attributes); - } + CMSMenu::add_link($id, $title, $link, $priority, $attributes); } - +} ``` To have the link appear, make sure you add the extension to the `LeftAndMain` @@ -105,7 +104,7 @@ class. For more information about configuring extensions see the ```php - LeftAndMain::add_extension('CustomLeftAndMain') +LeftAndMain::add_extension('CustomLeftAndMain') ``` ## Related diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Pages_List.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Pages_List.md index 458d1271f..92f022bcf 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Pages_List.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Pages_List.md @@ -18,23 +18,24 @@ Here's a brief example on how to add sorting and a new column for a hypothetical `NewsPageHolder` type, which contains `NewsPage` children. +**mysite/code/NewsPageHolder.php** + ```php - use Page; +class NewsPageHolder extends Page +{ + private static $allowed_children = ['NewsPage']; +} +``` - // mysite/code/NewsPageHolder.php - class NewsPageHolder extends Page - { - private static $allowed_children = ['NewsPage']; - } - - // mysite/code/NewsPage.php - class NewsPage extends Page - { - private static $has_one = [ - 'Author' => 'Member', - ]; - } +**mysite/code/NewsPage.php** +```php +class NewsPage extends Page +{ + private static $has_one = [ + 'Author' => 'Member', + ]; +} ``` We'll now add an `Extension` subclass to `LeftAndMain`, which is the main CMS controller. @@ -43,43 +44,44 @@ before its rendered. In this case, we limit our logic to the desired page type, although it's just as easy to implement changes which apply to all page types, or across page types with common characteristics. +**mysite/code/NewsPageHolderCMSMainExtension.php** ```php - use Page; - use SilverStripe\Core\Extension; +use SilverStripe\Core\Extension; - // mysite/code/NewsPageHolderCMSMainExtension.php - class NewsPageHolderCMSMainExtension extends Extension - { - function updateListView($listView) { - $parentId = $listView->getController()->getRequest()->requestVar('ParentID'); - $parent = ($parentId) ? Page::get()->byId($parentId) : new Page(); +class NewsPageHolderCMSMainExtension extends Extension +{ + public function updateListView($listView) { + $parentId = $listView->getController()->getRequest()->requestVar('ParentID'); + $parent = ($parentId) ? Page::get()->byId($parentId) : new Page(); - // Only apply logic for this page type - if($parent && $parent instanceof NewsPageHolder) { - $gridField = $listView->Fields()->dataFieldByName('Page'); - if($gridField) { - // Sort by created - $list = $gridField->getList(); - $gridField->setList($list->sort('Created', 'DESC')); - // Add author to columns - $cols = $gridField->getConfig()->getComponentByType('GridFieldDataColumns'); - if($cols) { - $fields = $cols->getDisplayFields($gridField); - $fields['Author.Title'] = 'Author'; - $cols->setDisplayFields($fields); - } + // Only apply logic for this page type + if($parent && $parent instanceof NewsPageHolder) { + $gridField = $listView->Fields()->dataFieldByName('Page'); + if($gridField) { + // Sort by created + $list = $gridField->getList(); + $gridField->setList($list->sort('Created', 'DESC')); + // Add author to columns + $cols = $gridField->getConfig()->getComponentByType('GridFieldDataColumns'); + if($cols) { + $fields = $cols->getDisplayFields($gridField); + $fields['Author.Title'] = 'Author'; + $cols->setDisplayFields($fields); } } } } +} ``` Now you just need to enable the extension in your [configuration file](../../configuration). + ```yml - // mysite/_config/config.yml - SilverStripe\Admin\LeftAndMain: - extensions: - - NewsPageHolderCMSMainExtension +// mysite/_config/config.yml +SilverStripe\Admin\LeftAndMain: + extensions: + - NewsPageHolderCMSMainExtension ``` + You're all set! Don't forget to flush the caches by appending `?flush=all` to the URL. diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Tree.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Tree.md index 132628a43..534f900b5 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Tree.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_CMS_Tree.md @@ -23,24 +23,24 @@ code like this: ```ss +... + +... ``` By applying the proper style sheet, the snippet html above could produce the look of: @@ -66,22 +66,22 @@ __Example: using a subclass__ ```php - use SilverStripe\CMS\Model\SiteTree; +use SilverStripe\CMS\Model\SiteTree; - class Page extends SiteTree +class Page extends SiteTree +{ + public function getScheduledToPublish() { - public function getScheduledToPublish() - { - // return either true or false - } - - public function getStatusFlags($cached = true) - { - $flags = parent::getStatusFlags($cached); - $flags['scheduledtopublish'] = "Scheduled To Publish"; - return $flags; - } + // return either true or false } + + public function getStatusFlags($cached = true) + { + $flags = parent::getStatusFlags($cached); + $flags['scheduledtopublish'] = "Scheduled To Publish"; + return $flags; + } +} ``` The above subclass of [SiteTree](api:SilverStripe\CMS\Model\SiteTree) will add a new flag for indicating its diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_React_Components.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_React_Components.md index fed07b012..a3e977ac6 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_React_Components.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_React_Components.md @@ -43,13 +43,13 @@ into the admin page. __my-module/\_config/config.yml__ ```yaml - --- - Name: my-module - --- - SilverStripe\Admin\LeftAndMain: - extra_requirements_javascript: - # The name of this file will depend on how you've configured your build process - - 'my-module/js/dist/main.bundle.js' +--- +Name: my-module +--- +SilverStripe\Admin\LeftAndMain: + extra_requirements_javascript: + # The name of this file will depend on how you've configured your build process + - 'my-module/js/dist/main.bundle.js' ``` Now that the customisation is applied, our text fields look like this: @@ -61,6 +61,7 @@ Let's add another customisation to TextField. If the text goes beyond a specifie length, let's throw a warning in the UI. __my-module/js/components/TextLengthChecker.js__ + ```js const TextLengthCheker = (TextField) => (props) => { const {limit, value } = props; @@ -86,6 +87,7 @@ For the purposes of demonstration, let's imagine this customisation comes from a module. __my-module/js/main.js__ + ```js import Injector from 'lib/Injector'; import TextLengthChecker from './components/TextLengthChecker'; diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_Site_Reports.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_Site_Reports.md index 22edf2642..b55207419 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_Site_Reports.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Customise_Site_Reports.md @@ -33,36 +33,35 @@ Inside the *mysite/code* folder create a file called *CustomSideReport.php*. Ins The following example will create a report to list every page on the current site. ###CustomSideReport.php + ```php - use Page; - use SilverStripe\Reports\Report; +use SilverStripe\Reports\Report; - class CustomSideReport_NameOfReport extends Report +class CustomSideReport_NameOfReport extends Report +{ + + // the name of the report + public function title() { - - // the name of the report - public function title() - { - return 'All Pages'; - } - - // what we want the report to return - public function sourceRecords($params = null) - { - return Page::get()->sort('Title'); - } - - // which fields on that object we want to show - public function columns() - { - $fields = [ - 'Title' => 'Title' - ]; - - return $fields; - } + return 'All Pages'; } - + + // what we want the report to return + public function sourceRecords($params = null) + { + return Page::get()->sort('Title'); + } + + // which fields on that object we want to show + public function columns() + { + $fields = [ + 'Title' => 'Title' + ]; + + return $fields; + } +} ``` More useful reports can be created by changing the `DataList` returned in the `sourceRecords` function. diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Extend_CMS_Interface.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Extend_CMS_Interface.md index 5389815cd..89ff78df7 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Extend_CMS_Interface.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Extend_CMS_Interface.md @@ -31,18 +31,17 @@ the CMS logic. Add a new section into the `
        ` ```ss - - ... - - ... +... + +... ``` Refresh the CMS interface with `admin/?flush=all`, and you should see those @@ -57,8 +56,7 @@ with the CMS interface. Paste the following content into a new file called ```css - - .bookmarked-link.first {margin-top: 1em;} +.bookmarked-link.first {margin-top: 1em;} ``` Load the new CSS file into the CMS, by setting the `LeftAndMain.extra_requirements_css` @@ -66,10 +64,9 @@ Load the new CSS file into the CMS, by setting the `LeftAndMain.extra_requiremen ```yml - - SilverStripe\Admin\LeftAndMain: - extra_requirements_css: - - mysite/css/BookmarkedPages.css +SilverStripe\Admin\LeftAndMain: + extra_requirements_css: + - mysite/css/BookmarkedPages.css ``` ## Create a "bookmark" flag on pages @@ -81,23 +78,23 @@ and insert the following code. ```php - use SilverStripe\Forms\CheckboxField; - use SilverStripe\ORM\DataExtension; +use SilverStripe\Forms\CheckboxField; +use SilverStripe\ORM\DataExtension; - class BookmarkedPageExtension extends DataExtension +class BookmarkedPageExtension extends DataExtension +{ + + private static $db = [ + 'IsBookmarked' => 'Boolean' + ]; + + public function updateCMSFields(FieldList $fields) { - - private static $db = [ - 'IsBookmarked' => 'Boolean' - ]; - - public function updateCMSFields(FieldList $fields) - { - $fields->addFieldToTab('Root.Main', - new CheckboxField('IsBookmarked', "Show in CMS bookmarks?") - ); - } + $fields->addFieldToTab('Root.Main', + new CheckboxField('IsBookmarked', "Show in CMS bookmarks?") + ); } +} ``` @@ -105,10 +102,9 @@ Enable the extension in your [configuration file](../../configuration) ```yml - - SilverStripe\CMS\Model\SiteTree: - extensions: - - BookmarkedPageExtension +SilverStripe\CMS\Model\SiteTree: + extensions: + - BookmarkedPageExtension ``` In order to add the field to the database, run a `dev/build/?flush=all`. @@ -125,27 +121,25 @@ Add the following code to a new file `mysite/code/BookmarkedLeftAndMainExtension ```php - use Page; - use SilverStripe\Admin\LeftAndMainExtension; +use SilverStripe\Admin\LeftAndMainExtension; - class BookmarkedPagesLeftAndMainExtension extends LeftAndMainExtension +class BookmarkedPagesLeftAndMainExtension extends LeftAndMainExtension +{ + + public function BookmarkedPages() { - - public function BookmarkedPages() - { - return Page::get()->filter("IsBookmarked", 1); - } + return Page::get()->filter("IsBookmarked", 1); } +} ``` Enable the extension in your [configuration file](../../configuration) ```yml - - SilverStripe\Admin\LeftAndMain: - extensions: - - BookmarkedPagesLeftAndMainExtension +SilverStripe\Admin\LeftAndMain: + extensions: + - BookmarkedPagesLeftAndMainExtension ``` As the last step, replace the hardcoded links with our list from the database. @@ -154,15 +148,14 @@ and replace it with the following: ```ss - -
          - - <% loop $BookmarkedPages %> -
        • Edit "$Title"
        • - - <% end_loop %> -
        +
          + + <% loop $BookmarkedPages %> +
        • Edit "$Title"
        • + + <% end_loop %> +
        ``` ## Extending the CMS actions @@ -197,7 +190,7 @@ button group (`CompositeField`) in a similar fashion. ```php - $fields->unshift(FormAction::create('normal', 'Normal button')); +$fields->unshift(FormAction::create('normal', 'Normal button')); ``` We can affect the existing button group by manipulating the `CompositeField` @@ -205,7 +198,7 @@ already present in the `FieldList`. ```php - $fields->fieldByName('MajorActions')->push(FormAction::create('grouped', 'New group button')); +$fields->fieldByName('MajorActions')->push(FormAction::create('grouped', 'New group button')); ``` Another option is adding actions into the drop-up - best place for placing @@ -213,7 +206,7 @@ infrequently used minor actions. ```php - $fields->addFieldToTab('ActionMenus.MoreOptions', FormAction::create('minor', 'Minor action')); +$fields->addFieldToTab('ActionMenus.MoreOptions', FormAction::create('minor', 'Minor action')); ``` We can also easily create new drop-up menus by defining new tabs within the @@ -221,7 +214,7 @@ We can also easily create new drop-up menus by defining new tabs within the ```php - $fields->addFieldToTab('ActionMenus.MyDropUp', FormAction::create('minor', 'Minor action in a new drop-up')); +$fields->addFieldToTab('ActionMenus.MyDropUp', FormAction::create('minor', 'Minor action in a new drop-up')); ```
        @@ -245,21 +238,21 @@ applicable controller actions to it: ```php - use SilverStripe\Admin\LeftAndMainExtension; +use SilverStripe\Admin\LeftAndMainExtension; - class CustomActionsExtension extends LeftAndMainExtension +class CustomActionsExtension extends LeftAndMainExtension +{ + + private static $allowed_actions = [ + 'sampleAction' + ]; + + public function sampleAction() { - - private static $allowed_actions = [ - 'sampleAction' - ]; - - public function sampleAction() - { - // Create the web - } - + // Create the web } + +} ``` @@ -267,17 +260,16 @@ The extension then needs to be registered: ```yaml - - SilverStripe\Admin\LeftAndMain: - extensions: - - CustomActionsExtension +SilverStripe\Admin\LeftAndMain: + extensions: + - CustomActionsExtension ``` You can now use these handlers with your buttons: ```php - $fields->push(FormAction::create('sampleAction', 'Perform Sample Action')); +$fields->push(FormAction::create('sampleAction', 'Perform Sample Action')); ``` ## Summary diff --git a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Extending_An_Existing_ModelAdmin.md b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Extending_An_Existing_ModelAdmin.md index 6c7c4d30c..fd8645d35 100644 --- a/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Extending_An_Existing_ModelAdmin.md +++ b/docs/en/02_Developer_Guides/15_Customising_the_Admin_Interface/How_Tos/Extending_An_Existing_ModelAdmin.md @@ -5,26 +5,25 @@ also another tool at your disposal: The [Extension](api:SilverStripe\Core\Extens ```php - use SilverStripe\Core\Extension; +use SilverStripe\Core\Extension; - class MyAdminExtension extends Extension +class MyAdminExtension extends Extension +{ + // ... + public function updateEditForm(&$form) { - // ... - public function updateEditForm(&$form) - { - $form->Fields()->push(/* ... */) - } + $form->Fields()->push(/* ... */) } +} ``` Now enable this extension through your `[config.yml](/topics/configuration)` file. ```yml - - MyAdmin: - extensions: - - MyAdminExtension +MyAdmin: + extensions: + - MyAdminExtension ``` The following extension points are available: `updateEditForm()`, `updateSearchContext()`, diff --git a/docs/en/02_Developer_Guides/16_Execution_Pipeline/01_Flushable.md b/docs/en/02_Developer_Guides/16_Execution_Pipeline/01_Flushable.md index 2abd1ac0e..5e1a18d39 100644 --- a/docs/en/02_Developer_Guides/16_Execution_Pipeline/01_Flushable.md +++ b/docs/en/02_Developer_Guides/16_Execution_Pipeline/01_Flushable.md @@ -20,31 +20,31 @@ This example uses [Cache](api:Cache) in some custom code, and the same cache is ```php - use SilverStripe\ORM\DataObject; - use SilverStripe\Core\Injector\Injector; - use SilverStripe\Core\Flushable; - use Psr\SimpleCache\CacheInterface; +use SilverStripe\ORM\DataObject; +use SilverStripe\Core\Injector\Injector; +use SilverStripe\Core\Flushable; +use Psr\SimpleCache\CacheInterface; - class MyClass extends DataObject implements Flushable +class MyClass extends DataObject implements Flushable +{ + + public static function flush() { - - public static function flush() - { - Injector::inst()->get(CacheInterface::class . '.mycache')->clear(); - } - - public function MyCachedContent() - { - $cache = Injector::inst()->get(CacheInterface::class . '.mycache') - $something = $cache->get('mykey'); - if(!$something) { - $something = 'value to be cached'; - $cache->set('mykey', $something); - } - return $something; - } - + Injector::inst()->get(CacheInterface::class . '.mycache')->clear(); } + + public function MyCachedContent() + { + $cache = Injector::inst()->get(CacheInterface::class . '.mycache') + $something = $cache->get('mykey'); + if(!$something) { + $something = 'value to be cached'; + $cache->set('mykey', $something); + } + return $something; + } + +} ``` ### Using with filesystem @@ -54,18 +54,18 @@ useful in an example like `GD` or `Imagick` generating resampled images, but we flush so they are re-created on demand. ```php - use SilverStripe\ORM\DataObject; - use SilverStripe\Core\Flushable; +use SilverStripe\ORM\DataObject; +use SilverStripe\Core\Flushable; - class MyClass extends DataObject implements Flushable +class MyClass extends DataObject implements Flushable +{ + + public static function flush() { - - public static function flush() - { - foreach(glob(ASSETS_PATH . '/_tempfiles/*.jpg') as $file) { - unlink($file); - } + foreach(glob(ASSETS_PATH . '/_tempfiles/*.jpg') as $file) { + unlink($file); } - } -``` \ No newline at end of file + +} +``` diff --git a/docs/en/02_Developer_Guides/16_Execution_Pipeline/03_App_Object_and_Kernel.md b/docs/en/02_Developer_Guides/16_Execution_Pipeline/03_App_Object_and_Kernel.md index 8f5acafd2..6f7282fc0 100644 --- a/docs/en/02_Developer_Guides/16_Execution_Pipeline/03_App_Object_and_Kernel.md +++ b/docs/en/02_Developer_Guides/16_Execution_Pipeline/03_App_Object_and_Kernel.md @@ -10,11 +10,11 @@ This can be accessed in user code via Injector ```php - use SilverStripe\Core\Kernel; - use SilverStripe\Core\Injector\Injector; - - $kernel = Injector::inst()->get(Kernel::class); - echo "Current environment: " . $kernel->getEnvironment(); +use SilverStripe\Core\Kernel; +use SilverStripe\Core\Injector\Injector; + +$kernel = Injector::inst()->get(Kernel::class); +echo "Current environment: " . $kernel->getEnvironment(); ``` ## Kernel services @@ -42,16 +42,16 @@ you should call `->activate()` on the kernel instance you would like to unnest t ```php - $oldKernel = Injector::inst()->get(Kernel::class); - try { - // Injector::inst() / Config::inst() are automatically updated to the new kernel - $newKernel = $oldKernel->nest(); - Config::modify()->set(Director::class, 'alternate_base_url', '/myurl'); - } - finally { - // Any changes to config (or other application state) have now been reverted - $oldKernel->activate(); - } +$oldKernel = Injector::inst()->get(Kernel::class); +try { + // Injector::inst() / Config::inst() are automatically updated to the new kernel + $newKernel = $oldKernel->nest(); + Config::modify()->set(Director::class, 'alternate_base_url', '/myurl'); +} +finally { + // Any changes to config (or other application state) have now been reverted + $oldKernel->activate(); +} ``` # Application @@ -73,7 +73,6 @@ You can customise it as required. ```php -execute($request, function (HTTPRequest $request) { - // Start session and execute - $request->getSession()->init(); - - // Set dummy controller - $controller = Controller::create(); - $controller->setRequest($request); - $controller->pushCurrent(); - $controller->doInit(); - }, true); +$request = CLIRequestBuilder::createFromEnvironment(); +$kernel = new TestKernel(BASE_PATH); +$app = new HTTPApplication($kernel); +$app->execute($request, function (HTTPRequest $request) { + // Start session and execute + $request->getSession()->init(); + + // Set dummy controller + $controller = Controller::create(); + $controller->setRequest($request); + $controller->pushCurrent(); + $controller->doInit(); +}, true); ``` diff --git a/docs/en/02_Developer_Guides/17_CLI/index.md b/docs/en/02_Developer_Guides/17_CLI/index.md index 2ac89cfec..0673b9ef2 100644 --- a/docs/en/02_Developer_Guides/17_CLI/index.md +++ b/docs/en/02_Developer_Guides/17_CLI/index.md @@ -8,10 +8,10 @@ needs to interface over the command line. The main entry point for any command line execution is `cli-script.php` in the framework module. For example, to run a database rebuild from the command line, use this command: -```bash - cd your-webroot/ - php vendor/silverstripe/framework/cli-script.php dev/build +```bash +cd your-webroot/ +php vendor/silverstripe/framework/cli-script.php dev/build ```
        @@ -33,10 +33,12 @@ when running the command php -v, then you may not have php-cli installed so sake ### Installation `sake` can be invoked using `./vendor/bin/sake`. For easier access, copy the `sake` file into `/usr/bin/sake`. + ``` - cd your-webroot/ - sudo ./vendor/bin/sake installsake +cd your-webroot/ +sudo ./vendor/bin/sake installsake ``` +
        This currently only works on UNIX like systems, not on Windows.
        @@ -59,24 +61,23 @@ SS_BASE_URL="http://localhost/base-url" ```bash +sake / +# returns the homepage - sake / - # returns the homepage - - sake dev/ - # shows a list of development operations +sake dev/ +# shows a list of development operations ``` `sake` is particularly useful for running build tasks. -```bash - sake dev/build "flush=1" +```bash +sake dev/build "flush=1" ``` It can also be handy if you have a long running script.. -```bash - sake dev/tasks/MyReallyLongTask +```bash +sake dev/tasks/MyReallyLongTask ``` ### Running processes @@ -93,38 +94,35 @@ This code provides a good template: ```php - use SilverStripe\Control\Controller; +use SilverStripe\Control\Controller; - class MyProcess extends Controller - { +class MyProcess extends Controller +{ - private static $allowed_actions = [ - 'index' - ]; + private static $allowed_actions = [ + 'index' + ]; - function index() { - set_time_limit(0); + function index() { + set_time_limit(0); - while(memory_get_usage() < 32*1024*1024) { - if($this->somethingToDo()) { - $this->doSomething(); - sleep(1) - } else { - sleep(300); - } + while(memory_get_usage() < 32*1024*1024) { + if($this->somethingToDo()) { + $this->doSomething(); + sleep(1) + } else { + sleep(300); } } } - +} ``` Then the process can be managed through `sake` - ```bash - - sake -start MyProcess - sake -stop MyProcess +sake -start MyProcess +sake -stop MyProcess ```
        @@ -135,19 +133,15 @@ Then the process can be managed through `sake` Parameters can be added to the command. All parameters will be available in `$_GET` array on the server. - ```bash - - cd your-webroot/ - php vendor/silverstripe/framework/cli-script.php myurl myparam=1 myotherparam=2 +cd your-webroot/ +php vendor/silverstripe/framework/cli-script.php myurl myparam=1 myotherparam=2 ``` Or if you're using `sake` - ```bash - - sake myurl "myparam=1&myotherparam=2" +vendor/bin/sake myurl "myparam=1&myotherparam=2" ``` ## Running Regular Tasks With Cron @@ -158,5 +152,5 @@ On a UNIX machine, you can typically run a scheduled task with a [cron job](http The following will run `MyTask` every minute. ```bash - * * * * * /your/site/folder/vendor/bin/sake dev/tasks/MyTask +* * * * * /your/site/folder/vendor/bin/sake dev/tasks/MyTask ``` diff --git a/docs/en/02_Developer_Guides/18_Cookies_And_Sessions/01_Cookies.md b/docs/en/02_Developer_Guides/18_Cookies_And_Sessions/01_Cookies.md index 2fc2b9107..16b1a1bd8 100644 --- a/docs/en/02_Developer_Guides/18_Cookies_And_Sessions/01_Cookies.md +++ b/docs/en/02_Developer_Guides/18_Cookies_And_Sessions/01_Cookies.md @@ -15,11 +15,11 @@ Sets the value of cookie with configuration. ```php - use SilverStripe\Control\Cookie; +use SilverStripe\Control\Cookie; - Cookie::set($name, $value, $expiry = 90, $path = null, $domain = null, $secure = false, $httpOnly = false); +Cookie::set($name, $value, $expiry = 90, $path = null, $domain = null, $secure = false, $httpOnly = false); - // Cookie::set('MyApplicationPreference', 'Yes'); +// Cookie::set('MyApplicationPreference', 'Yes'); ``` ### get @@ -28,10 +28,10 @@ Returns the value of cookie. ```php - Cookie::get($name); +Cookie::get($name); - // Cookie::get('MyApplicationPreference'); - // returns 'Yes' +// Cookie::get('MyApplicationPreference'); +// returns 'Yes' ``` ### force_expiry @@ -40,9 +40,9 @@ Clears a given cookie. ```php - Cookie::force_expiry($name, $path = null, $domain = null); +Cookie::force_expiry($name, $path = null, $domain = null); - // Cookie::force_expiry('MyApplicationPreference') +// Cookie::force_expiry('MyApplicationPreference') ``` ## Cookie_Backend @@ -56,19 +56,19 @@ from the browser. ```php - use SilverStripe\Core\Injector\Injector; - use SilverStripe\Control\Cookie; - use SilverStripe\Control\CookieJar; +use SilverStripe\Core\Injector\Injector; +use SilverStripe\Control\Cookie; +use SilverStripe\Control\CookieJar; - $myCookies = [ - 'cookie1' => 'value1', - ]; +$myCookies = [ + 'cookie1' => 'value1', +]; - $newBackend = new CookieJar($myCookies); +$newBackend = new CookieJar($myCookies); - Injector::inst()->registerService($newBackend, 'Cookie_Backend'); +Injector::inst()->registerService($newBackend, 'Cookie_Backend'); - Cookie::get('cookie1'); +Cookie::get('cookie1'); ``` @@ -80,9 +80,9 @@ create a new service for you using the `$_COOKIE` superglobal. ```php - Injector::inst()->unregisterNamedObject('Cookie_Backend'); +Injector::inst()->unregisterNamedObject('Cookie_Backend'); - Cookie::get('cookiename'); // will return $_COOKIE['cookiename'] if set +Cookie::get('cookiename'); // will return $_COOKIE['cookiename'] if set ``` Alternatively, if you know that the superglobal has been changed (or you aren't sure it hasn't) you can attempt to use @@ -90,11 +90,11 @@ the current `CookieJar` service to tell you what it was like when it was registe ```php - //store the cookies that were loaded into the `CookieJar` - $recievedCookie = Cookie::get_inst()->getAll(false); +//store the cookies that were loaded into the `CookieJar` +$recievedCookie = Cookie::get_inst()->getAll(false); - //set a new `CookieJar` - Injector::inst()->registerService(new CookieJar($recievedCookie), 'CookieJar'); +//set a new `CookieJar` +Injector::inst()->registerService(new CookieJar($recievedCookie), 'CookieJar'); ``` ### Using your own Cookie_Backend @@ -103,14 +103,13 @@ If you need to implement your own Cookie_Backend you can use the injector system ```yml - - --- - Name: mycookie - After: '#cookie' - --- - SilverStripe\Core\Injector\Injector: - Cookie_Backend: - class: MyCookieJar +--- +Name: mycookie +After: '#cookie' +--- +SilverStripe\Core\Injector\Injector: + Cookie_Backend: + class: MyCookieJar ``` To be a valid backend your class must implement the [Cookie_Backend](api:SilverStripe\Control\Cookie_Backend) interface. @@ -126,12 +125,12 @@ Using the `Cookie_Backend` we can do this like such: ```php - Cookie::set('CookieName', 'CookieVal'); +Cookie::set('CookieName', 'CookieVal'); - Cookie::get('CookieName'); //gets the cookie as we set it +Cookie::get('CookieName'); //gets the cookie as we set it - //will return the cookie as it was when it was sent in the request - Cookie::get('CookieName', false); +//will return the cookie as it was when it was sent in the request +Cookie::get('CookieName', false); ``` ### Accessing all the cookies at once @@ -140,9 +139,9 @@ One can also access all of the cookies in one go using the `Cookie_Backend` ```php - Cookie::get_inst()->getAll(); //returns all the cookies including ones set during the current process +Cookie::get_inst()->getAll(); //returns all the cookies including ones set during the current process - Cookie::get_inst()->getAll(false); //returns all the cookies in the request +Cookie::get_inst()->getAll(false); //returns all the cookies in the request ``` ## API Documentation diff --git a/docs/en/02_Developer_Guides/18_Cookies_And_Sessions/02_Sessions.md b/docs/en/02_Developer_Guides/18_Cookies_And_Sessions/02_Sessions.md index 4aa094771..347d87825 100644 --- a/docs/en/02_Developer_Guides/18_Cookies_And_Sessions/02_Sessions.md +++ b/docs/en/02_Developer_Guides/18_Cookies_And_Sessions/02_Sessions.md @@ -39,7 +39,7 @@ $session = $request->getSession(); ```php - $session->set('MyValue', 6); +$session->set('MyValue', 6); ``` Saves the value of to session data. You can also save arrays or serialized objects in session (but note there may be @@ -47,12 +47,12 @@ size restrictions as to how much you can save). ```php - // saves an array - $session->set('MyArrayOfValues', ['1','2','3']); +// saves an array +$session->set('MyArrayOfValues', ['1','2','3']); - // saves an object (you'll have to unserialize it back) - $object = new Object(); - $session->set('MyObject', serialize($object)); +// saves an object (you'll have to unserialize it back) +$object = new Object(); +$session->set('MyObject', serialize($object)); ``` @@ -64,14 +64,14 @@ can use this anywhere in your PHP files. ```php - echo $session->get('MyValue'); - // returns 6 +echo $session->get('MyValue'); +// returns 6 - $data = $session->get('MyArrayOfValues'); - // $data = array(1,2,3) +$data = $session->get('MyArrayOfValues'); +// $data = array(1,2,3) - $object = unserialize($session->get('MyObject', $object)); - // $object = Object() +$object = unserialize($session->get('MyObject', $object)); +// $object = Object() ``` @@ -79,9 +79,8 @@ can use this anywhere in your PHP files. You can also get all the values in the session at once. This is useful for debugging. ```php - $session->getAll(); - // returns an array of all the session values. - +$session->getAll(); +// returns an array of all the session values. ``` ## clear @@ -89,13 +88,13 @@ You can also get all the values in the session at once. This is useful for debug Once you have accessed a value from the Session it doesn't automatically wipe the value from the Session, you have to specifically remove it. ```php - $session->clear('MyValue'); +$session->clear('MyValue'); ``` Or you can clear every single value in the session at once. Note SilverStripe stores some of its own session data including form and page comment information. None of this is vital but `clear_all` will clear everything. ```php - $session->clearAll(); +$session->clearAll(); ``` ## Secure Session Cookie @@ -104,7 +103,6 @@ In certain circumstances, you may want to use a different `session_name` cookie ```yml - SilverStripe\Control\Session: cookie_secure: true ``` diff --git a/docs/en/04_Changelogs/2.3.0.md b/docs/en/04_Changelogs/2.3.0.md index 4214dd165..44cf0f021 100644 --- a/docs/en/04_Changelogs/2.3.0.md +++ b/docs/en/04_Changelogs/2.3.0.md @@ -115,17 +115,17 @@ specifies "these are arguments to the controller". In other words, change this: ```php - Director::addRules(50, array( - 'admin/ImageEditor/$Action' => 'ImageEditor', - )); +Director::addRules(50, array( + 'admin/ImageEditor/$Action' => 'ImageEditor', +)); ``` To this: ```php - Director::addRules(50, array( - 'admin/ImageEditor//$Action' => 'ImageEditor', - )); +Director::addRules(50, array( + 'admin/ImageEditor//$Action' => 'ImageEditor', +)); ``` @@ -214,7 +214,7 @@ like Validator.js and behaviour.js. If you want to disable JavaScript validation _config.php: ```php - Validator::set_javascript_validation_handler('none'); +Validator::set_javascript_validation_handler('none'); ``` See http://open.silverstripe.com/changeset/69688 diff --git a/docs/en/04_Changelogs/2.3.2.md b/docs/en/04_Changelogs/2.3.2.md index fa4536834..c410ad4d3 100644 --- a/docs/en/04_Changelogs/2.3.2.md +++ b/docs/en/04_Changelogs/2.3.2.md @@ -74,31 +74,31 @@ Because of this, you will need to change the static definitions in your ModelAdm change this: ```php - class MyCatalogAdmin extends ModelAdmin - { - - protected static $managed_models = array( - 'Product', - 'Category' - ); - - ... - } +class MyCatalogAdmin extends ModelAdmin +{ + + protected static $managed_models = array( + 'Product', + 'Category' + ); + + ... +} ``` To this: ```php - class MyCatalogAdmin extends ModelAdmin - { - - public static $managed_models = array( - 'Product', - 'Category' - ); - - ... - } +class MyCatalogAdmin extends ModelAdmin +{ + + public static $managed_models = array( + 'Product', + 'Category' + ); + + ... +} ``` diff --git a/docs/en/04_Changelogs/2.4.0.md b/docs/en/04_Changelogs/2.4.0.md index 413fbc81c..bc24c84d1 100644 --- a/docs/en/04_Changelogs/2.4.0.md +++ b/docs/en/04_Changelogs/2.4.0.md @@ -130,7 +130,7 @@ You can enable it manually for existing websites. Existing URLs will automatical republication (your old URLs should redirect automatically). ```php - SiteTree::enable_nested_urls(); +SiteTree::enable_nested_urls(); ``` ### SiteTree->Link() instead of SiteTree->URLSegment diff --git a/docs/en/04_Changelogs/2.4.1.md b/docs/en/04_Changelogs/2.4.1.md index f7d8e4bc7..29a689e57 100644 --- a/docs/en/04_Changelogs/2.4.1.md +++ b/docs/en/04_Changelogs/2.4.1.md @@ -124,7 +124,7 @@ To clarify: Leaving existing decorators unchanged might mean that you allow acti // In mysite/_config.php :::php Object::add_extension('SiteTree', 'MyDecorator'); - + // 2.4.0 :::php class MyDecorator extends DataObjectDecorator @@ -137,7 +137,7 @@ To clarify: Leaving existing decorators unchanged might mean that you allow acti } } } - + // 2.4.1 :::php class MyDecorator extends DataObjectDecorator diff --git a/docs/en/04_Changelogs/2.4.3.md b/docs/en/04_Changelogs/2.4.3.md index 2db4ec214..4cd2ac3fc 100644 --- a/docs/en/04_Changelogs/2.4.3.md +++ b/docs/en/04_Changelogs/2.4.3.md @@ -50,7 +50,7 @@ parameters (//$data, $form// instead of *$request*). // Form field actions class MyFormField extends FormField { - + // Form fields always have a reference to their form. // Use the form-specific token instance. function delete($request) { @@ -64,7 +64,7 @@ parameters (//$data, $form// instead of *$request*). // Controller actions (GET and POST) without form class MyController extends Controller { - + // Manually adds token to link function DeleteLink() { $token = SecurityToken::inst(); @@ -73,7 +73,7 @@ parameters (//$data, $form// instead of *$request*). $link = $token->addToUrl($link); return $link; } - + // Controller actions pass through the request object, // not called through a form. // Use a global token instance. @@ -84,7 +84,7 @@ parameters (//$data, $form// instead of *$request*). // valid controller delete action } } - + // Controller actions (GET and POST) with form class MyController extends Controller { @@ -155,7 +155,7 @@ parameters don't break through string concatenation. :::php // bad $link = $this->Link() . 'export?csv=1'; - + // good $link = Controller::join_links($this->Link(), 'export', '?csv=1'); @@ -165,15 +165,15 @@ Full controller example: :::php class MyController extends Controller { - + function export($request) { // ... } - + function Link($action = null) { return Controller::join_links('MyController', $action); } - + function ExportLink() { return Controller::join_links($this->Link('export'), '?csv=1'); } @@ -195,13 +195,13 @@ You can manually enable security tokens, either globally or for a specific form. :::php class MyTest extends SapphireTest { - + // option 1: enable for all forms created through this test function setUp() { parent::setUp(); SecurityToken::enable(); } - + // option 2: enable for one specific form function testMyForm() { $form = new MyForm(); @@ -352,4 +352,4 @@ You can manually enable security tokens, either globally or for a specific form. * [rev:111040] API-CHANGE: remove include which is not required. * [rev:111038] ENHACENEMENT: Change behaviour of the !MenufestBuilder to use spl_autoload_register instead of traditional __autoload. -sscreatechangelog --version 2.4.3 --branch branches/2.4 --stopbranch tags/2.4.2 \ No newline at end of file +sscreatechangelog --version 2.4.3 --branch branches/2.4 --stopbranch tags/2.4.2 diff --git a/docs/en/04_Changelogs/3.0.0.md b/docs/en/04_Changelogs/3.0.0.md index 60e87dc71..3bc5364d9 100644 --- a/docs/en/04_Changelogs/3.0.0.md +++ b/docs/en/04_Changelogs/3.0.0.md @@ -145,7 +145,7 @@ you can use `add_to_class()` as a replacement to `extraStatics()`. :::php class MyExtension extends Extension { - + // before function extraStatics($class, $extensionClass) { if($class == 'MyClass') { @@ -171,7 +171,7 @@ you can use `add_to_class()` as a replacement to `extraStatics()`. )); } parent::add_to_class($class, $extensionClass, $args); - } + } } @@ -185,7 +185,7 @@ expressive notation (instead of unnamed arguments). DataObject::get('Member', '"FirstName" = \'Sam'\', '"Surname" ASC"); // after Member::get()->filter(array('FirstName' => 'Sam'))->sort('Surname'); - + The underlying record retrieval and management is rewritten from scratch, and features lazy loading which fetches only the records it needs, as late as possible. In order to retrieve all ORM records manually (as the previous ORM would've done), @@ -226,7 +226,7 @@ this command would have been intolerably slow: :::php SiteTree::get()->count(); - + The 3.0 ORM is more intelligent gives you tools you need to create high-performance code without bypassing the ORM: @@ -478,7 +478,7 @@ as well as the HTML form element itself.
        - + After (abbreviated):
        @@ -670,7 +670,7 @@ will only produce errors if the API was deprecated in the release equal to or ea in 3.0. Deprecation::notification_version('3.0.0'); - + If you change the notification version to 3.0.0-dev, then only methods deprecated in older versions (e.g. 2.4) will trigger notices, and the other methods will silently pass. This can be useful if you don't yet have time to remove all calls to deprecated methods. diff --git a/docs/en/04_Changelogs/3.1.0.md b/docs/en/04_Changelogs/3.1.0.md index 66fedaae5..b33a2a875 100644 --- a/docs/en/04_Changelogs/3.1.0.md +++ b/docs/en/04_Changelogs/3.1.0.md @@ -161,21 +161,21 @@ Here's an example on how to rewrite a common `_config.php` configuration: count()) return false; - + $context = func_num_args() > 1 ? func_get_arg(1) : array(); return parent::canCreate($member, $context); } diff --git a/docs/en/04_Changelogs/4.0.0.md b/docs/en/04_Changelogs/4.0.0.md index 29d8503ad..8c300a6c3 100644 --- a/docs/en/04_Changelogs/4.0.0.md +++ b/docs/en/04_Changelogs/4.0.0.md @@ -215,10 +215,8 @@ define('SS_DATABASE_PASSWORD', ''); define('SS_DATABASE_SERVER', '127.0.0.1'); ``` - `.env`: - ``` ## Environment SS_ENVIRONMENT_TYPE="dev" @@ -234,7 +232,6 @@ SS_DATABASE_PASSWORD="" SS_DATABASE_SERVER="127.0.0.1" ``` - The removal of the `_ss_environment.php` file means that conditional logic is no longer available in the environment variable set-up process. This generally encouraged bad practice and should be avoided. If you still require conditional logic early in the bootstrap, this is best placed in the `_config.php` files. diff --git a/docs/en/04_Changelogs/alpha/4.0.0-alpha1.md b/docs/en/04_Changelogs/alpha/4.0.0-alpha1.md index 2356f9df3..46bf47721 100644 --- a/docs/en/04_Changelogs/alpha/4.0.0-alpha1.md +++ b/docs/en/04_Changelogs/alpha/4.0.0-alpha1.md @@ -737,7 +737,7 @@ For instance: "Versioned('StagedVersioned')" ); } - + /** * This model has versioning only, and will not has a draft or live stage, nor be affected by the current stage. */ @@ -814,7 +814,7 @@ For example: Will become: - use SilverStripe\Model\FieldType\DBVarchar; + use SilverStripe\Model\FieldType\DBVarchar; class MyObject extends DataObject { private static $db = array( diff --git a/docs/en/05_Contributing/01_Code.md b/docs/en/05_Contributing/01_Code.md index 31db7224a..8d88eceba 100644 --- a/docs/en/05_Contributing/01_Code.md +++ b/docs/en/05_Contributing/01_Code.md @@ -212,15 +212,18 @@ Further guidelines: * Mention important changed classes and methods in the commit summary. Example: Bad commit message -``` - finally fixed this dumb rendering bug that Joe talked about ... LOL - also added another form field for password validation -``` -Example: Good commit message -``` - BUG Formatting through prepValueForDB() - Added prepValueForDB() which is called on DBField->writeToManipulation() - to ensure formatting of value before insertion to DB on a per-DBField type basis (fixes #1234). - Added documentation for DBField->writeToManipulation() (related to a4bd42fd). -``` +``` +finally fixed this dumb rendering bug that Joe talked about ... LOL +also added another form field for password validation +``` + +Example: Good commit message + +``` +BUG Formatting through prepValueForDB() + +Added prepValueForDB() which is called on DBField->writeToManipulation() +to ensure formatting of value before insertion to DB on a per-DBField type basis (fixes #1234). +Added documentation for DBField->writeToManipulation() (related to a4bd42fd). +``` diff --git a/docs/en/05_Contributing/03_Request_for_comment.md b/docs/en/05_Contributing/03_Request_for_comment.md index a2d716635..2d4822ebd 100644 --- a/docs/en/05_Contributing/03_Request_for_comment.md +++ b/docs/en/05_Contributing/03_Request_for_comment.md @@ -21,7 +21,7 @@ The benefits of writing an RFC for non-trivial feature proposals are: * Obtaining a preliminary approval from core-committers on an architecture before code is completed, to mitigate the risk of a non-merge after a PR is submitted * Community becomes aware of incoming changes prior to the implementation * RFC can be used as a basis for documentation of the feature - + ## How to write an RFC? ### Template The following heading can act as a template to starting your RFC. diff --git a/docs/en/05_Contributing/04_Release_Process.md b/docs/en/05_Contributing/04_Release_Process.md index c8acc6d6f..e9664c3a2 100644 --- a/docs/en/05_Contributing/04_Release_Process.md +++ b/docs/en/05_Contributing/04_Release_Process.md @@ -63,15 +63,15 @@ Here's an example for replacing `Director::isDev()` with a (theoretical) `Env::i ```php - /** - * Returns true if your are in development mode - * @deprecated 4.0 Use {@link Env::is_dev()} instead. - */ - public function isDev() - { - Deprecation::notice('4.0', 'Use Env::is_dev() instead'); - return Env::is_dev(); - } +/** + * Returns true if your are in development mode + * @deprecated 4.0 Use {@link Env::is_dev()} instead. + */ +public function isDev() +{ + Deprecation::notice('4.0', 'Use Env::is_dev() instead'); + return Env::is_dev(); +} ``` This change could be committed to a minor release like *3.2.0*, and remains deprecated in all subsequent minor releases @@ -87,13 +87,14 @@ notices are always disabled on both live and test. ```php - Deprecation::set_enabled(false); +Deprecation::set_enabled(false); ``` `.env` - - SS_DEPRECATION_ENABLED="0" +``` +SS_DEPRECATION_ENABLED="0" +``` ## Security Releases diff --git a/docs/en/05_Contributing/05_Making_A_SilverStripe_Core_Release.md b/docs/en/05_Contributing/05_Making_A_SilverStripe_Core_Release.md index 9872d1147..9dd42c2c1 100644 --- a/docs/en/05_Contributing/05_Making_A_SilverStripe_Core_Release.md +++ b/docs/en/05_Contributing/05_Making_A_SilverStripe_Core_Release.md @@ -39,26 +39,27 @@ As a core contributor it is necessary to have installed the following set of too * A good `.env` setup in your localhost webroot. Example `.env`: + ``` - # Environent - SS_TRUSTED_PROXY_IPS="*" - SS_ENVIRONMENT_TYPE="dev" - - # DB Credentials - SS_DATABASE_CLASS="MySQLDatabase" - SS_DATABASE_SERVER="127.0.0.1" - SS_DATABASE_USERNAME="root" - SS_DATABASE_PASSWORD="" - - # Each release will have its own DB - SS_DATABASE_CHOOSE_NAME=1 - - # So you can test releases - SS_DEFAULT_ADMIN_USERNAME="admin" - SS_DEFAULT_ADMIN_PASSWORD="password" - - # Basic CLI request url default - SS_BASE_URL="http://localhost/" +# Environent +SS_TRUSTED_PROXY_IPS="*" +SS_ENVIRONMENT_TYPE="dev" + +# DB Credentials +SS_DATABASE_CLASS="MySQLDatabase" +SS_DATABASE_SERVER="127.0.0.1" +SS_DATABASE_USERNAME="root" +SS_DATABASE_PASSWORD="" + +# Each release will have its own DB +SS_DATABASE_CHOOSE_NAME=1 + +# So you can test releases +SS_DEFAULT_ADMIN_USERNAME="admin" +SS_DEFAULT_ADMIN_PASSWORD="password" + +# Basic CLI request url default +SS_BASE_URL="http://localhost/" ``` You will also need to be assigned the following permissions. Contact one of the SS staff from @@ -168,9 +169,11 @@ doe not make any upstream changes (so it's safe to run without worrying about any mistakes migrating their way into the public sphere). Invoked by running `cow release` in the format as below: + ``` - cow release -vvv +cow release -vvv ``` + This command has the following parameters: * `` The version that is to be released. E.g. 3.2.4 or 4.0.0-alpha4 @@ -238,8 +241,9 @@ building an archive, and uploading to [www.silverstripe.org](http://www.silverstripe.org/software/download/) download page. Invoked by running `cow release:publish` in the format as below: + ``` - cow release:publish -vvv +cow release:publish -vvv ``` As with the `cow release` command, this step is broken down into the following subtasks which are invoked in sequence: diff --git a/docs/en/05_Contributing/06_Documentation.md b/docs/en/05_Contributing/06_Documentation.md index 01ce1b3c0..9982d91e0 100644 --- a/docs/en/05_Contributing/06_Documentation.md +++ b/docs/en/05_Contributing/06_Documentation.md @@ -90,31 +90,37 @@ sparingly.
        Code for a Tip box: + ``` -
        - ... -
        +
        +... +
        ``` +
        "Notification box": A notification box is good for technical notifications relating to the main text. For example, notifying users about a deprecated feature.
        Code for a Notification box: + ``` -
        - ... -
        +
        +... +
        ``` +
        "Warning box": A warning box is useful for highlighting a severe bug or a technical issue requiring a user's attention. For example, suppose a rare edge case sometimes leads to a variable being overwritten incorrectly. A warning box can be used to alert the user to this case so they can write their own code to handle it.
        Code for a Warning box: + ``` -
        - ... -
        +
        +... +
        ``` + See [markdown extra documentation](http://michelf.com/projects/php-markdown/extra/#html) for more restrictions on placing HTML blocks inside Markdown. diff --git a/docs/en/05_Contributing/08_Translation_Process.md b/docs/en/05_Contributing/08_Translation_Process.md index 0488d6376..f93b1ba6e 100644 --- a/docs/en/05_Contributing/08_Translation_Process.md +++ b/docs/en/05_Contributing/08_Translation_Process.md @@ -20,7 +20,7 @@ creating a new project, you have to upload the `en.yml` master file as a new "Re the web interface, there's a convenient [commandline client](http://support.transifex.com/customer/portal/topics/440187-transifex-client/articles) for this purpose. In order to use it, set up a new `.tx/config` file in your module folder: - + ```yaml [main] host = https://www.transifex.com @@ -71,13 +71,13 @@ under the "silverstripe" user, see Translations need to be reviewed before being committed, which is a process that happens roughly once per month. We're merging back translations into all supported release branches as well as the `master` branch. The following script should be applied to the oldest release branch, and then merged forward into newer branches: -```bash - - tx pull - # Manually review changes through git diff, then commit - git add lang/* - git commit -m "Updated translations" +```bash +tx pull + +# Manually review changes through git diff, then commit +git add lang/* +git commit -m "Updated translations" ```
        @@ -89,9 +89,9 @@ You can download your work right from Transifex in order to speed up the process SilverStripe also supports translating strings in JavaScript (see [i18n](/developer_guides/i18n)), but there's a conversion step involved in order to get those translations syncing with Transifex. Our translation files stored in `mymodule/javascript/lang/*.js` call `ss.i18n.addDictionary()` to add files. -```js - ss.i18n.addDictionary('de', {'MyNamespace.MyKey': 'My Translation'}); +```js +ss.i18n.addDictionary('de', {'MyNamespace.MyKey': 'My Translation'}); ``` But Transifex only accepts structured formats like JSON. @@ -101,33 +101,35 @@ But Transifex only accepts structured formats like JSON. ``` First of all, you need to create those source files in JSON, and store them in `mymodule/javascript/lang/src/*.js`. In your `.tx/config` you can configure this path as a separate master location. + ```ruby +[main] +host = https://www.transifex.com - [main] - host = https://www.transifex.com +[silverstripe-mymodule.master] +file_filter = lang/.yml +source_file = lang/en.yml +source_lang = en +type = YML - [silverstripe-mymodule.master] - file_filter = lang/.yml - source_file = lang/en.yml - source_lang = en - type = YML - - [silverstripe-mymodule.master-js] - file_filter = javascript/lang/src/.js - source_file = javascript/lang/src/en.js - source_lang = en - type = KEYVALUEJSON +[silverstripe-mymodule.master-js] +file_filter = javascript/lang/src/.js +source_file = javascript/lang/src/en.js +source_lang = en +type = KEYVALUEJSON ``` Then you can upload the source files via a normal `tx push`. Once translations come in, you need to convert the source files back into the JS files SilverStripe can actually read. This requires an installation of our [buildtools](https://github.com/silverstripe/silverstripe-buildtools). + ``` - tx pull - (cd .. && phing -Dmodule=mymodule translation-generate-javascript-for-module) - git add javascript/lang/* - git commit -m "Updated javascript translations" +tx pull +(cd .. && phing -Dmodule=mymodule translation-generate-javascript-for-module) +git add javascript/lang/* +git commit -m "Updated javascript translations" ``` + # Related * [i18n](/developer_guides/i18n/): Developer-level documentation of Silverstripe's i18n capabilities diff --git a/docs/en/05_Contributing/14_PHP_Coding_Conventions.md b/docs/en/05_Contributing/14_PHP_Coding_Conventions.md index 600cf1f87..6133fc223 100644 --- a/docs/en/05_Contributing/14_PHP_Coding_Conventions.md +++ b/docs/en/05_Contributing/14_PHP_Coding_Conventions.md @@ -27,10 +27,10 @@ As opposed to other variables, these should be declared as lower case with under ```php - class MyClass - { - private static $my_config_variable = 'foo'; - } +class MyClass +{ + private static $my_config_variable = 'foo'; +} ``` ## Prefer identical (===) comparisons over equality (==) @@ -40,15 +40,15 @@ Read more in the PHP documentation for [comparison operators](http://php.net/man ```php - // good - only need to cast to (int) if $a might not already be an int - if ((int)$a === 100) { - doThis(); - } - - // bad - if ($a == 100) { - doThis(); - } +// good - only need to cast to (int) if $a might not already be an int +if ((int)$a === 100) { + doThis(); +} + +// bad +if ($a == 100) { + doThis(); +} ``` ## Separation of Logic and Presentation @@ -57,28 +57,32 @@ Try to avoid using PHP's ability to mix HTML into the code. ```php - // PHP code - public function getTitle() - { - return "

        Bad Example

        "; - } +// PHP code +public function getTitle() +{ + return "

        Bad Example

        "; +} +``` - // Template code - $Title +```ss +// Template code +$Title ``` Better: Keep HTML in template files: ```php - // PHP code - public function getTitle() - { - return "Better Example"; - } +// PHP code +public function getTitle() +{ + return "Better Example"; +} +``` - // Template code -

        $Title

        +```ss +// Template code +

        $Title

        ``` ## Comments @@ -97,34 +101,34 @@ Example: ```php +/** + * My short description for this class. + * My longer description with + * multiple lines and richer formatting. + * + * Usage: + * + * $c = new MyClass(); + * $c->myMethod(); + * + * + * @package custom + */ +class MyClass extends Class +{ /** - * My short description for this class. - * My longer description with - * multiple lines and richer formatting. + * My Method. + * This method returns something cool. {@link MyParentMethod} has other cool stuff in it. * - * Usage: - * - * $c = new MyClass(); - * $c->myMethod(); - * - * - * @package custom + * @param string $colour The colour of cool things that you want + * @return DataList A list of everything cool */ - class MyClass extends Class + public function myMethod($colour) { - /** - * My Method. - * This method returns something cool. {@link MyParentMethod} has other cool stuff in it. - * - * @param string $colour The colour of cool things that you want - * @return DataList A list of everything cool - */ - public function myMethod($foo) - { - // ... - } - + // ... } + +} ``` ## Class Member Ordering @@ -148,7 +152,7 @@ with the column or table name escaped with double quotes as below. ```php - MyClass::get()->where(["\"Score\" > ?" => 50]); +MyClass::get()->where(['"Score" > ?' => 50]); ``` @@ -159,7 +163,7 @@ are single quoted. ```php - MyClass::get()->where("\"Title\" = 'my title'"); +MyClass::get()->where("\"Title\" = 'my title'"); ``` Use [ANSI SQL](http://en.wikipedia.org/wiki/SQL#Standardization) format where possible.