Images doesnt show when published

Sorry for another newbie question again. I’m just trying to publish a page that has lots of images as a background for each section. However, after saving and publishing in CMS admin, the images i uploaded via UploadField doesn’t show. The images only shows when it’s in draft in the Admin page. I also dont have the images uploaded when going into localhost/mysampleproject.

image

image

Another SS4 quirk.
Every time you upload an image or file, it doesn’t publish by default, you need to write some code to make that happen.
Try the following in your Page model:

    private static $owns = [
        'HomepageLogo'
    ];

    public function onAfterWrite()
    {
        parent::onAfterWrite();
        if ($this->HomepageLogo()->exists() && !$this->HomepageLogo()->isPublished()) { 
            $this->HomepageLogo()->doPublish(); 
        } 
    }

Repeat the if block and the $owns array item for each image in your model.

Once you publish the page, the image will also publish, and you’ll be able to see it.

2 Likes

Thank you @Peter Will try do this. :+1::+1::+1: you are awesome!

It works! Where can you find to study these codes like isPublished, doPublish and these Data Extensions like onAfterWrite and onBeforeWrite? I have visited silverstripe website and i didn’t find any definition or example. I know they are being called/written because they have a purpose while functions from other languages just get declared by the developer itself.

Thanks a lot! @JonoM. Those will be very helpful with my study about silverstripe. I appreciate it.

I will usually search the Developer Docs and if that doesn’t turn up anything I’ll try the API Docs. As a last resort (but I do it very often) I’ll read the code :slight_smile:

I always use Google instead of the built in search on docs:

BTW I use Alfred and have a shortcut set up so I can type ssd <search-term> to search the docs and ssa <search-term> to search the API docs as I do it many times a day.

1 Like

In the latest version of SS4, there should be no need for the onAfterWrite() method. Adding the $owns array should be sufficient to handle the publish action on the image automatically.

2 Likes

This is good news Tim. Which version does that apply from?

1 Like

I believe it was released in 4.2.0

1 Like