How do you implement custom validation rules for a DataObject in SilverStripe?

How do you implement custom validation rules for a DataObject in SilverStripe?

To implement custom validation rules for a DataObject in SilverStripe, follow these steps:

Step 1: Extend DataObject and Add Fields

  • Define your custom DataObject with the fields that need validation.

Example

<?php
namespace App\Models;

use SilverStripe\ORM\DataObject;

class MyCustomObject extends DataObject
{
    private static $db = [
        'Title' => 'Varchar',
        'Age' => 'Int'
    ];
}
?>

Step 2: Create a Custom Validator

  • Implement custom validation rules by overriding the validate() method.

Example

<?php
use SilverStripe\ORM\ValidationResult;

class MyCustomObject extends DataObject
{
    private static $db = [
        'Title' => 'Varchar',
        'Age' => 'Int'
    ];

    public function validate()
    {
        $result = parent::validate();

        // Add custom rule for Title
        if (empty($this->Title)) {
            $result->addError('Title cannot be empty');
        }

        // Add custom rule for Age
        if ($this->Age < 18) {
            $result->addError('Age must be 18 or older');
        }

        return $result;
    }
}
?>

Step 3: Save the Object and Check Validation

  • When saving the object, SilverStripe will automatically run the validation rules. If validation fails, it will prevent saving.

Example

<?php
$myObject = MyCustomObject::create();
$myObject->Title = ''; // Invalid
$myObject->Age = 16;   // Invalid

if ($myObject->write()) {
    echo 'Saved successfully!';
} else {
    echo 'Failed to save due to validation errors.';
}
?>

Related Questions & Topics