1

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.

Niels
  • 353
  • 1
  • 6
  • 15
  • Generally you don't want to escape data before you write it - instead you should escape before outputting. Do you have more information on your use case? – ajshort Jun 13 '14 at 09:07
  • @ajshort I want to convert to lowercase and trim non alpha characters before going into db. – Niels Jun 14 '14 at 23:49
  • @ajshort for the purpose of saving twitter hashtags to check against when parsing api return – Niels Jun 14 '14 at 23:58
  • Is this referring to the CMS or a fronted form? – Cam Jun 16 '14 at 03:27

2 Answers2

2

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');

// ...
3dgoo
  • 15,716
  • 6
  • 46
  • 58
  • 1
    Dont forget, this won't run automatically. You need to load it from _config.php in my site or one of your module, ie: SiteConfig::add_extension('CustomSiteConfig'); You can also load it via a yml file inside a _config folder. – cryptopay Jun 29 '14 at 06:22
  • Thanks @elliot_at_silverstripe. I've added that note into my answer. – 3dgoo Jun 29 '14 at 23:27
0

This is taken care of automatically.

$dataObject->Title = 'te"st'; // This will become "te\"st" $dataObject->write();

More information about this can be found in the docs: http://doc.silverstripe.com/framework/en/topics/security

micmania1
  • 623
  • 3
  • 10