4

this is my page

page.htm (Markup) - I manage to get the image name but I can't get the image source

<img id="avatar-image" alt="Jason's Image" src="{{ avatar_id }}"/>

{{ file_name }} // working       
{{ avatar_id }} // not working

page.htm(Code)

function onStart()
{
    $var = \System\Models\File::where("field", "=", "avatar")->first();
    $this["file_name"] = $var->file_name;
    $this["avatar_id"] = $var->path;
}

my model

model.php

class Settings extends Model
{
    public $implement = ['System.Behaviors.SettingsModel'];

    public $settingsCode = 'dca_plugins_settings';

    public $settingsFields = 'fields.yaml';

    public $attachOne = [ 'avatar' => ['System\Models\File'] ];
}

field.yaml

fields:
  id:
    label: ID
    disabled: true

  name:
    label: Image

  avatar:
    label: Avatar
    type: fileupload
    mode: image
    imageHeight: 150
    imageWidth: 250

can someone tell me how to get the path(image source)?

BEX
  • 187
  • 4
  • 21

1 Answers1

3

Following the docs:

The getPath() method returns the full URL of an uploaded public file. The following code would print something like ...mysite.com/uploads/public/path/to/avatar.jpg

In your case, would be something like:

$setting = Settings::first(); // Gets some settings model.
$avatar = $setting->avatar;
$avatarPath = null;

// Check if setting has an attached avatar.
if ($avatar) {
  $avatarPath = $avatar->getPath(); // Uploaded public file.
}

And inject into Twig environment via PHP Section, for example.

$this['avatar_path'] = $avatarPath;
Alexandre Thebaldi
  • 4,546
  • 6
  • 41
  • 55
  • This works perfectly when the image is defined as type `fileupload` and is stored by means of the integrated relation `System\Models\File`. What if the image is defined as type `mediafinder` and the value is stored as a string in the database? How would one find the path of it? I always get the error message `call to a member function getPath() on string`. Could you please advise? – chocolata Jan 23 '18 at 21:14