silverstripesilvershop

How to modify Product in Silvershop (adding custom fields to $db)


I'm currently developing a shop using SilverShop. I want to add some specific fields to my products, such as what fabric my clothes are made of and an image. I know that we should not make these changes in the core SilverShop source code.

Should I extend the Product class in a new file such as app/src/ProductPage.php?

class Product extends Page implements Buyable
{
    private static $db = [
        'InternalItemID' => 'Varchar(30)', //ie SKU, ProductID etc (internal / existing recognition of product)
        'Model' => 'Varchar(30)',

        'BasePrice' => 'Currency(19,4)', // Base retail price the item is marked at.

        //physical properties
        // TODO: Move these to an extension (used in Variations as well)
        'Weight' => 'Decimal(12,5)',
        'Height' => 'Decimal(12,5)',
        'Width' => 'Decimal(12,5)',
        'Depth' => 'Decimal(12,5)',

        'Featured' => 'Boolean',
        'AllowPurchase' => 'Boolean',

        'Popularity' => 'Float' //storage for CalculateProductPopularity task
    ];
...

Solution

  • Use DataExtension

    For SilverStripe 4, it will be something like:

    ProductExtension.php :

    use SilverStripe\ORM\DataExtension;
    use SilverStripe\Forms\FieldList;
    use SilverStripe\Forms\TextField;
    
    class ProductExtension extends DataExtension 
    {
    
        private static $db = [
            'NewField' => 'Varchar(255)'
        ];
    
        public function updateCMSFields(FieldList $fields)
        {
            $fields->addFieldsToTab('Root.Main', TextField::create('NewField', 'This is new field'));
        }
    
    }
    

    And, add the next lines to mysite.yml

    SilverShop\Page\Product:
      extensions:
        - ProductExtension
    

    dev/build and it's done