Add db field to "blogcategory" table

Silverstripe Version: 4.*

How can I add a field to “blogcategory” table?

Blogcategory table includes URLSegment field which changes according to Title. The problem is that the Title contains non url friendly characters like (šđč ćžäü). I need another field that keeps the correct characters like the Title does - once that is set. This field would than be used for a custom filter on frontend. For now I tried like this but it doesn’t do the trick. Should I rename the class? How can I tell Silverstripe which table to use?

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


class BlogCategoryExtension extends DataExtension {
    private static $db = [
        'SafeUrlSegment' => 'String'
    ];

    public function updateCMSFields(FieldList $fields)
    {
        $fields->push(new TextField('SafeUrlSegment', 'Safe URL Segment'));
    }
}

You don’t necessary need a whole separate field - you could just add a getURLSegment() method which takes the value from $this->owner->getField('URLSegment') and transforms it to a ‘safe’ value.

Also there’s no standard that I’m aware of that disallows šđč ćžäü characters from URLs - I think those are valid.

That said, if you really do want to handle this with an entirely separate field, the code you’ve got there should do that just fine. You should probably namespace it according to PSR4, and I’d probably recommend $fields->addFieldToTab() instead of $fields->push() so you only have the field on the tab you want it on (normally 'Root.Main')… and you will want some validation for that field if you’re saying it can only have certain characters. But yes your code should work just fine.

You just need to make sure to apply the extension using yml configuration:

SilverStripe\Blog\Model\BlogCategory:
  extensions:
    - BlogCategoryExtension
1 Like

Hi
I forgot about to apply it of course… :roll_eyes: Thanks for the reminder. :slight_smile:
There are addtional reasons for this field. The Title is prone to changes (ISCSD => IS CSD => …) and I have an unfortunate “RŠS” Title that would be /r%C5%A1s or even worse /rss. And it would interfere with rss feed. With this field I can control it.

1 Like