Question: There is any way to set default value for UploadField?
I have a question about setting default image for my DataObject. I have in database photo that i want to add as default for my input(UploadField) i want to load the Image to UploadField and if user save form simply save this image but if someone want to change img a want to save this image saved by user. Below is my code.
private static $has_one = array(
'Image' => Image::class,
);
public function getCMSFields()
{
$fields = new FieldList();
$img = new UploadField('Image');
$img->setFolderName('path/to/my/folder');
$img->getValidator()->setAllowedExtensions(array('jpg', 'gif', 'png'));
$fields->push($img);
(Here i have logic for download the image object that i want to use as default image $Image is my object)
$fields->dataFieldByName('Image')->setValue($Image->ID);
}
Im trying too the other option as documentation say:
In there I think you ought to be able to get the Image object and set it using $this->Image() = $MyDefaultImage; or possibly just using the ID: $this->ImageID = $MyDefaultImage->ID;
I just checked something like this according to this docs
public function populateDefaults()
{
[logic for dowload default image object from db as $defaultImage]
$this->Image = $defaultImage->ID;
parent::populateDefaults();
}
but this unfortunately doesn’t load the photo properly either. im checking my method on TextField and its working so the problem is only with UploadField and i dont know how to resolve this ;/
but there is one thing i noticed that if i dont have
$img = new UploadField('Image');
$img->setFolderName('path/to/my/folder');
$img->getValidator()->setAllowedExtensions(array('jpg', 'gif', 'png'));
$fields->push($img);
the method setValue loading the image to UploadField but i can select multiple images in this field maybe if i have relations loading value must be done differently. im not an expert in SS so I combine as much as I can :)))
Ok im finally did it, everything was fine but i didint notice that i didint call this function anywhere so…
public function getCMSFields()
{
... code ...
$this->populateDefaults();
}
public function populateDefaults()
{
[logic for dowload default image object from db as $defaultImage]
$this->Image = $defaultImage->ID;
parent::populateDefaults();
}
}
So… TIM your answer was perfect for me Thank you very much!