Getting a URL from new image field

When I try to get the URL from the new image field in 2.3 it doesn’t work

<?= $page->picturefield()->url() ?>
returns http://root.dev/filename.jpg

But I’m expecting it to return http://root.dev/01-parent/02-child/filename.jpg
The toFile() function doesn’t seem to work on the new field. Works fine with a select field or the selector plugin.

1 Like

This should work:

$page->image($page->picturefield())->url();

or if not, then:

$page->image($page->picturefield()->value())->url();
2 Likes

Yes, they both work. I guess I’m just used to the toFile()->url() method, but this will do the trick :slight_smile:

Either way, is this expected behavior for the image field’s url() and toFile() functions?

1 Like

toFile() should actually also work:

$page->picturefield()->toFile()->url();
3 Likes

It appears to only work for me when the template corresponds to the same level…
The image is /01-parent/02-child/filename.jpg and I can use any of the above methods just fine in child.php template

But if I want to display it for in a list/grid in parent.php template it throws an error
Fatal error: Call to a member function url() on null in /Applications/MAMP/h...

Exact code:

<?php foreach($page->children()->visible() as $p): ?>
	<strong><?= $p->picturefield()->toFile()->url() ?></strong>
<?php endforeach; ?>

I tested this in a starterkit and it works on all levels. Have you made sure that the field contains an image filename in every page? Or better still, use an if statement to check that the field is not empty and the image exists.

Okay that seems to have been the problem :sweat_smile:
Thank you!

Really weird way of doing things, but it works, i guess.

Any plugins that can be made so you can simply do:
$page->$img(imageField);
where that would output the url?

@AdamRasheed Check out the docs on custom page methods.

1 Like

4 posts were merged into an existing topic: $img = $page->$slide()->toFile(); I need to append a value to the end of slide. See code. Thanks