>/Deadly Technology_ Deadly Technology RSS Feed
  • SilverStripe
  • CakePHP
  • Javascript
  • Linux
  • PHP
  • Git
  • Web

SilverStripe

  • Snippets
  • Articles

SilverStripe is now my CMS of choice, I have a few SilverStripe projects under my belt I'm enjoying developing CMS driven websites and unlocking some of the power of Sapphire, the framework underpinning the SilverStripe CMS. There is a learning curve attached however, which led me to start documenting little snippets that make life a little easier.

Templates

Resize an image and get URL on the fly in template file:

<% control Image %>
<% control SetSize(blah, blah) %>
$FileName
<% end_control %>
<% end_control %>

Using GroupedBy to organise a listing of Pages or DataObjects:

<% control AllChildren.GroupedBy(Province) %>
        <p>$Province</p>
        <% control Children %>
	$Title
        $Content
	<% end_control %>

<% end_control %>

Check page class in the template:

If on the home page do not show the SilverStripe navigator.
<% if ClassName != HomePage %>
$SilverStripeNavigator
<% end_if %>

Using renderWith() from a DataObject to give the view access to the data and methods of that object:

//Fields and methods in the someObject class will be accessible to the view
$content = $someObject->renderWith("SomePage");

You can also pass data to the template by using customise():

$someViewableDataObject->customise(array(
	"Data" => $someData
))->renderWith('SomeTemplate');

Return an array of data in a DataObjectSet for access in the template:

  public function getAllProvinces() {
        //Get all the children for this page then pull out the provinces
        
        $currentPage = $this->data();
        $pages = $currentPage->AllChildren();
        
        $allProvinces = array();
        
        $i = 0;
        foreach ($pages as $page) {
            $allProvinces[$i]['provinceID'] = $page->Province;
            $allProvinces[$i++]['provinceName'] = $page->strProvince;
        }

        return new DataObjectSet($allProvinces);
   }

Adding comments to template files that will not be rendered:

<%-- Comments marked like this will be excluded from the HTML output --%>

If you ever have the problem of sitetree_link ids appearing in your anchor tags like:it is likely because the content containing the link is passed as plain text rather than as an instance of HTMLText.

$content = new HTMLText(); 
$content->setValue('html with the anchor tag in it here'); 

DataObjects

Setting default values for database fields, the $defaults array in SilverStripe DataObjects makes all new objects created have the default, it does not alter already saved objects (rows in the database).

static $db = array(
        'Mailto' => 'Varchar(100)'
);
static $defaults = array(
        'Mailto' => 'info@example.com'
);

Accessing the model (Page) from the controller, in Page_Controller this will return the Page object.

$this->data();

Accessing a field in a DataObject

$this->getField("Field");
//or
$this->Field;
//or
$this->dataRecord->MyField;

Sometimes its useful to access a field from a DataObject and return the object that represents this field

public static $db = array(
  'Amount' => 'Money'
);

//Elsewhere in DataObject:
$this->dbObject("Amount");

Accessing a component in a DataObject such as a $has_one or $has_many

$this->Field(); //has_one relationship
$this->Fields(); //has_many relationship

Require a field in the CMS area

getCMSValidator() {
    return new RequiredFields('FieldName');
}

Accessing getFunctionName() as $FunctionName in the view, you can drop the 'get' prefix of a function name to call the function in views. So if you have a scenario like:

class Page extends SiteTree {
    public static $db = array(
        "Foo" => "Text",
    );
}
class Page_Controller extends ContentController {
    public function getFoo() {
        return 'Some value';
    }
}

Calling $Foo in your view will result in 'Some value'. If you want to access $Foo of the Page class rename the function getFoo(). You don't need to write getters for the db fields in the model (Page in this case) because $db fields become variables in the view and $has_x relationships become methods. Creating a multiple or 2 column key index:

static $indexes = array( 
  'KeyName' => array( 
    'type' => 'unique', 
    'value' => 'ColumnOne,ColumnTwo' 
  ) 
);

Checking if writing a DataObject for the first time in the onAfterWrite() method:

class Something extends Page {
  private $firstWrite = false;
  
  function onBeforeWrite() {
    parent::onBeforeWrite();
    if (!$this->ID) $this->firstWrite = true;
  }
  
  function onAfterWrite() {
    parent::onAfterWrite();
    if ($this->firstWrite) echo 'New object';
  }
}

Controllers

Because I am always forgetting the syntax, how to include jQuery from Sapphire on SilverStripe 2.4

Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery/jquery.js');

If you want to overload the index() method of a controller its often useful to return the Content and Form:

function index() {
  
  //Do something here
  
  return array( 
     'Content' => $this->Content, 
     'Form' => $this->Form 
  );
}

CMS

Adding nested tabs to 3 or more levels deep can be achieved by adding a TabSet and then adding new Tabs to that tab set:

$fields->addFieldToTab("Root", new TabSet('Advertisements', 
  new TabSet('LargeAds', new Tab('One'), new Tab('Two')),
  new Tab('SmallAds')
)); 

$fields->addFieldToTab("Root.Advertisements.LargeAds.One", new TextField('LargeAdOneLink', 'URL address for advertisement')); 

//Or something like
$fields->addFieldToTab("Root", new TabSet('Advertisements')); 
$fields->addFieldToTab("Root.Advertisements", new Tab('LargeAds')); 

Debugging

Javascript files are concatenated and saved in the Assets folder. If you are having problems accessing the CMS due to Javascript errors check the permissions of the assets/ and perhaps also assets/_combinedfiles/ folders. When SilverStripe is in production mode javascript files will be concatenated and saved. In order to disable this add the following line to mysite/_config.php:

Requirements::set_combined_files_enabled(false);

Debugging SilverStripe issues, the most annoying problem is the blank white page. The blank white page can often be attributed to some syntax error in the template file. If no errors are being shown try adding: ?isDev=1 to the URL. Or looking in apache error logs for any related errors:

tail -f /var/logs/apache2/error.log

Setting a log for the application is also useful, in the mysite/_config.php file:

SS_Log::add_writer(new SS_LogFileWriter('/var/www/silverstripe/mysite/errors.log')); 

Then can log errors specifically using something like:

SS_Log::log(new Exception('Some log message here'), SS_Log::NOTICE); 

//Or for objects/arrays
SS_Log::log(new Exception(print_r($this, true)), SS_Log::NOTICE);

Admin splash / loading screen stuck? If you have a look in the firebug console and see a bunch of javascript errors its likely due to problems creating combinedfiles for the javascript that needs to be loaded for the CMS. This might be due to a permissions problem of your /assets/_combinedfiles/ folder, if changing permissions of this folder doesn't work and neither does changing the owner or turning off php_safe_mode then you can stop SilverStripe from combining files in your _config.php file:

Requirements::set_combined_files_enabled(false);

PHP: Warning: Unexpected character in input: ''' (ASCII=39) - this warning was related to a PHP parse error in one of my class files, (http://www.php.net/manual/en/function.token-get-all.php#79502). In my case it related to a poorly formed Enum string. If you get the warning: "File is not a valid upload" when trying to upload files to SilverStripe then you might want to view this ticket and apply one of the patches, you can also try turning off open_basedir.

Useful Documentation

I find myself hitting most of these pages often for reference:

  • Page controls - what you can and can't do in the SilverStripe templates.
  • SilverStripe templates - including template syntax, if and control blocks and Modulus/MultipleOf.
  • Debugging - a must have for any CMS.
  • Environment management - a cool technique to manage development and live environments for a SilverStripe project.
  • Execution pipeline - the process of a page request from SilverStripe.
  • Image controls - all those functions you can use on Images in SilverStripe templates.
  • Text methods - all the functions you can use to manipulate text in templates.
  • URL variable tools - very useful for development and testing a SilverStripe site

SilverStripe text books for reference:

  • SilverStripe 2.4 reference book - this is the most recent SilverStripe book which I am currently reading and is very good.
  • Original SilverStripe book - a good reference that helped me when I was getting started

GridField edit record set relation ID

14 Sep 12

SilverStripe 3 Gridfield is very flexible and easy to work with compared to the old ComplexTableField and popups of SilverStripe 2.4 (so far). One pitfall however is that when adding a record to a  has_many the parent ID / relation ID is not prepopulated - related ticket here.

Read the rest of the post…

#SilverStripe  

Display latest tweets in SilverStripe

19 Jul 12

Displaying your latest tweet using Javascript is fairly straight forward and this method can be used to display a tweet in a SilverStripe template. The Javascript might look a bit like this:

Read the rest of the post…

#SilverStripe  

How To: Nginx, PHP-FPM, MySQL, phpMyAdmin, Postfix on Ubuntu

26 Apr 12

I recently moved to a new VPS because my last one was at something like 92% uptime. I wanted to try Nginx because Apache was constantly crashing, possibly something to do with Plesk being installed.

Read the rest of the post…

#SilverStripe  

Scheduled Tasks in SilverStripe

19 Dec 11

Creating a scheduled task in SilverStripe, one that is called by cron, can be a bit fiddly and the documentation seems to have disappeared. Here's the process I followed to create a SilverStripe scheduled task that is run by cron.  

Read the rest of the post…

#SilverStripe  

Bare bones SilverStripe image gallery module

17 Nov 11

This is an example image gallery that has no dependencies on other SilverStripe modules - not counting the SilverStripe framework and cms haha. Just an example of a bare bones image gallery, using ComplexTableField instead of the DataObjectManager. If you are looking for a more complete Image Gallery Tutorial please follow that link to a walkthrough, much of the process is the same.

Read the rest of the post…

#SilverStripe  

Easy 'Under Construction' pages for SilverStripe sites

11 Nov 11

For if you've ever been in the situation where you've developed a SilverStripe site for a client and now they want to review it before making it live - but you don't have a staging server set up. What you usually want to do is give the client full access to their website, but prevent the public from viewing the unfinished product. [ad#Half Banner] This simple technique is perfect for those situations. It lets you deliver a static HTML 'Under Construction' page to the general public, but if an admin user is logged in, the 'Under Construction' page disappears and the admin user can browse the site as normal. Additionally the 'Under Construction' page is served up with a 503 - Service Unavailable HTTP response status code.

Read the rest of the post…

#SilverStripe  

Posting invalid form data in SilverStripe unit tests

8 Nov 11

By default posting form data from a SilverStripe unit test seems to restrict your POST data to only valid values. Meaning, if you want to post a value for a select field on the form, the value must be in the options for that select field in order for it to be POST'd. [ad#Half Banner] Usually when submitting form data from a unit test its easiest to use the FunctionalTest->submitForm() function with something like:

Read the rest of the post…

#SilverStripe  

Speed up SilverStripe Unit Testing with SQLite

6 Nov 11

Unit testing can be a useful process to kill those pesky bugs, luckily with SilverStripe its relatively easy to get started unit testing. Running a test can take some time though, a great way of speeding up unit testing (as pointed out to me by Will Rossiter on the IRC channel) is to use the SQLite3 module by Andreas Piening. [ad#Half Banner] Installation is pretty straight forward, so that only your unit tests use the SQLite database you can hack up the config file a bit:

Read the rest of the post…

#SilverStripe  

Date range picker for SilverStripe model admin search

28 Jun 11

After reading this awesome post by Aaron Carlino I decided a date range filter was just what I needed to filter search results in my ModelAdmin class. Then I read the comment by Ingo Schommer and that date range widget looked pretty badass so I incorporated that instead of having two fields like Aaron's solution.

Read the rest of the post…

#SilverStripe   #Javascript  

SilverStripe 2.4 Module Extension, Themes, and Widgets: Beginner's Guide by Philipp Krenn

3 Jun 11

The latest book offering in a short line of SilverStripe books is an enjoyable read and full of useful and practical content. As I read through I kept a file noting little tips that were either completely new to me or were techniques that I should be making more use of, by the end of the book there were 49 of them.

Read the rest of the post…

#SilverStripe  

HTML Emails with inline CSS on SilverStripe

8 May 11

This is a really neat method to include CSS styles into an HTML email inline, which is apparently the best practice for HTML emails.

Read the rest of the post…

#SilverStripe  

How to setup PayPal Express Checkout with SilverStripe

3 May 11

The SilverStripe Payment module is really handy, its useful to have a payment module completely separate from ecommerce because it gives you so much freedom. The Payment-Test module is an ideal example of this. I used Payment-Test to create a basic booking system for instance, its a really good example of how to hook up a payment gateway to your site.

Read the rest of the post…

#SilverStripe  

Pear, PHPUnit, MAMP and SilverStripe Unit Testing

20 Apr 11

Installing PHPUnit using Pear on Mac OSX was such a process I have to write it down. If you want to get started with unit testing in SilverStripe you need PHPUnit installed.

Read the rest of the post…

#SilverStripe  

Submit SilverStripe User Forms via AJAX

6 Mar 11

The User Forms SilverStripe module is super useful for creating forms. I often use it for contact page forms, recently I wanted to submit a contact form via AJAX which is pretty straight forward using SilverStripe's extension class.

Read the rest of the post…

#SilverStripe  

Pear, PHPUnit, MAMP and SilverStripe Unit Testing

20 Apr 11

Installing PHPUnit using Pear on Mac OSX was such a process I have to write it down. If you want to get started with unit testing in SilverStripe you need PHPUnit installed.

Read the rest of the post…

#SilverStripe  

Add google maps to pages in SilverStripe

27 Oct 10

UPDATE: A better method of adding a google map to a page in SilverStripe can be found here.

Read the rest of the post…

#SilverStripe  

SilverStripe Membership Module Tutorial

12 Oct 10

This SilverStripe Membership Module by ajshort is one of the most useful and solid modules I've used on a SilverStripe install.

Read the rest of the post…

#SilverStripe  

How to access array data from SilverStripe sessions easily

14 Sep 10

Its not evident from the SilverStripe documentation on sessions, but you can access nested array data from SilverStripe sessions using dot notation.

Read the rest of the post…

#SilverStripe  

How to change the breadcrumb separator on SilverStripe

13 Sep 10

Quick tip to change the separator used by SilverStripe to separate the links of the breadcrumb.

Read the rest of the post…

#SilverStripe  

Silverstripe Image Gallery Tutorial

10 Jun 10

I have had a few issues installing image gallery modules on Silverstripe 2.4. I'm new to using silverstripe so this is a beginners tutorial, the aim is to install a basic image gallery which fits the following criteria:

Read the rest of the post…

#SilverStripe  

Rolling out an API for your cakePHP app Part 1: The Problems

29 Apr 10

Recently I've put a lot of work into an API solution for a cakePHP app which addresses some of the architectural issues of creating an API in a cakePHP project. To start with I threw together a nice simple API as a proof of concept and to showcase the ease at which an API can be created quickly using the RequestHandler component. While that solution was fine and incredibly quick to whip up, there are some issues when it comes time to extend the API, the biggest of which is versioning.

Read the rest of the post…

#PHP   #CakePHP  

read more
SilverStripe Ecommerce Module

Ecommerce Module
Works with SilverStripe 3

Popular Posts

Deploy websites using Git - the easy way

GridField edit record set relation ID

Silverstripe Image Gallery Tutorial

Regenerating Temporary Terminal Server CALS.

How to setup PayPal Express Checkout with SilverStripe

Transfer photos from Nikon DSLR on Ubuntu

Nested Ternary Statement PHP

HTTP Cache Poisoning

How To: Nginx, PHP-FPM, MySQL, phpMyAdmin, Postfix on Ubuntu

Rolling out an API for your cakePHP app Part 3: Handling Errors

© 2006 - 2023 Frank Mullenger

site map