Search code examples
phpconfigsilverstripesilverstripe-4

How to set a property in SiteConfig in silverstripe?


I have a created a CustomSiteConfig in silverstripe using this guide -> https://docs.silverstripe.org/en/4/developer_guides/configuration/siteconfig/#siteconfig

This is how it looks like:

<?php
namespace Poptin\Silverstripe;

use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\DataExtension;

class PoptinSiteConfig extends DataExtension 
{
    private static $db = [
        'PoptinConfig' => 'Text'
    ];

    public function updateCMSFields(FieldList $fields) 
    {
        $fields->addFieldToTab("Root.Main", 
            new TextField("PoptinConfig", "Poptin Config")
        );
    }
}

And I can retrieve the information by doing

$config = SiteConfig::current_site_config();
var_dump($config->PoptinConfig);

And it works, but how to set it back? I have tried $config->__set('PoptinConfig', 'foo'), $config->setField('PoptinConfig', 'foo'); but none of them work. No errors, but the field doesn't change.


Solution

  • $cfg = SiteConfig::current_site_config();
    $cfg->PoptinConfig = "Something";
    $cfg->write();
    

    Should do the trick, just like on any class that extends DataObject. Only difference being

    $cfg = SiteConfig::current_site_config();
    

    as it's a SiteConfig method.