Search code examples
silverstripedata-objects

How do I sanitize form input in Silverstripe CMS


Can someone please direct me to an example of how to sanitise a field from a dataObject BEFORE it gets dumped in the DB?

I don't know where to look.

I want to clean some user input before it is saved to the SiteConfig.


Solution

  • You can customize saving-behaviour of a Page, DataObject or SiteConfig using the onBeforeWrite function.

    The function is triggered when calling write() to save the object to the database. This includes saving a page in the CMS or altering a ModelAdmin record.

    Here is an example for Silverstripe 3.1 of using onBeforeWrite on a SiteConfig Extension to strip characters and convert characters to lowercase on a text field:

    SiteConfig onBeforeWrite example

    class CustomSiteConfig extends DataExtension {
    
        private static $db = array(
            'TwitterUsername' => 'Text'
        );
    
        public function updateCMSFields(FieldList $fields) {
            $fields->addFieldToTab('Root.Main', new TextField('TwitterUsername', 'Twitter Username'));
        }
    
        public function onBeforeWrite() {
            $this->owner->TwitterUsername = strtolower($this->owner->TwitterUsername);
            $this->owner->TwitterUsername = preg_replace("/[^a-z0-9]/", '', $this->owner->TwitterUsername);
    
            parent::onBeforeWrite();
        }
    }
    

    Note: For the above example to work the CustomSiteConfig extensions needs to be applied to the SiteConfig. This can either be done through a yml config file or through a _config.php file.

    mysite/_config/config.yml

    ---
    Name: site
    After: 'framework/*','cms/*'
    ---
    
    # ...
    
    # SiteConfig Extension
    
    SiteConfig:
      extensions:
        - CustomSiteConfig
    
    # ...
    

    Or

    mysite/_config.php

    global $project;
    $project = 'mysite';
    
    // ...
    
    SiteConfig::add_extension('CustomSiteConfig');
    
    // ...