1
votes

I'm working on a site built with SilverStripe 4 where the user is going to be able to upload an image.

Is there a way to set a default image in the database until the user has uploaded one?

I know that I can check for existence in the layout. But I would prefer to avoid doing this since I'm going to use the image on several places.

I know that I can override populageDefaults() to set default values on dates and other types of fields. But what about images?

This is the php code for the class handling the image:

<?php

use SilverStripe\Forms\DateField;
use SilverStripe\Assets\Image;
use SilverStripe\Forms\TextareaField;
use SilverStripe\AssetAdmin\Forms\UploadField;

use Page;

class ArticlePage extends Page {

   private static $can_be_root = false;
   private static $db = [
      'DateEnd' => 'Date',
      'DateStart' => 'Date',
      'Teaser' => 'Text',
   ];

   private static $has_one = [
      'Photo' => Image::class,
   ];

   private static $owns = [
      'Photo',
   ];

   public function getCMSFields() {
      $fields = parent::getCMSFields();
      $fields->addFieldToTab('Root.Main', DateField::create('DateStart', 'Start Date'), 'Content');
      $fields->addFieldToTab('Root.Main', DateField::create('DateEnd', 'End Date'), 'Content');
      $fields->addFieldToTab('Root.Main', TextareaField::create('Teaser'), 'Content');
      $fields->addFieldToTab('Root.Main', $photo = UploadField::create('Photo', 'Article Image'), 'Content');
      $photo->getValidator()->setAllowedExtensions(['jpg']);
      return $fields;
   }

   public function populateDefaults() {
      $this->DateEnd = date('Y-m-d');
      $this->DateStart = date('Y-m-d');
      $this->Teaser = 'A short teaser.';
      parent::populateDefaults();
   }
}
1

1 Answers

2
votes

Yes you can, the image can be set with the the ID as follows...

public function populateDefaults()
{
   $this->PhotoID = 1;//Assuming you know the ID of the Image
   parent::populateDefaults();
}