Jump to content
EyeDentify

Adding image to Page via API $page->images->add() (SOLVED)

Recommended Posts

Hello Gentlemen and Ladies.

I have not posted for a while but now i need your help figuring out some things.

The Documentation has come a long way and i love it.
Though on the page:
https://processwire.com/api/ref/pageimages/

I am trying to figure out if when i want to add an image to an existing image field with multiple images alldready in it and using the method $page->images->add()

<?PHP
/* get the images object array for the Page */
$myPageImg = $page->images;

/* define the image to add */
$newImg = 'http://www.somesite.com/image.jpg';

/* Thanks Autofahrn, forgot about the output formating */
$page->of(false);

/* create a new Pageimage object with the given URL and add to the Pageimages array */
$myPageImg->add($newImg);

/* save the page */
$page->save();

?>

I am pretty sure i missed a few steps in the code above?

Is that string suppose to be an URL like "http://www.somesite.com/image.jpg" and the method will automaticly download the image and create an Pageimage Object and add it to Pageimages array or does it have to exist on the host first and i supply a file path to that image?

I guess im confused about that, hope you guys could clarify that for me.

And if it needs to be allready downloaded to my host before adding the image, what would be the best API methods for that task?
Just point me in the right direction and i will figure it out.

Sorry for the bad explaination but i could not figure out a better way of asking.

Thanks in advance.

/EyeDentify

Edited by EyeDentify
Marked as Solved with help of Autofahrn and bernhard

Share this post


Link to post
Share on other sites

According to this old post it basically seems ok:

If the page already exists, you want to turn off output formatting first. Something like:

$page->of(false);
$page->images->add($imageUrl);
$page->save();

 

  • Like 1
  • Thanks 1

Share this post


Link to post
Share on other sites
3 minutes ago, Autofahrn said:

According to this old post it basically seems ok:

If the page already exists, you want to turn off output formatting first. Something like:


$page->of(false);
$page->images->add($imageUrl);
$page->save();

 

 

Yes ofcourse Sir 🙂 Forgot about the output formating 🙂

But otherwise it seems allright?

Could i expect to access the newly created Pageimage object as a return value from:

 

<?PHP
$urlToImage = 'http://www.somesite.com/image.jpg';

$pageImageObj = $page->images->add($urlToImage);
?>

And do some changes to it before saving or should one save in between?

Share this post


Link to post
Share on other sites

Why don't you just install TracyDebugger and try it out? It makes so many things so easy:

3NgmSb9.png

  • Like 1
  • Thanks 1

Share this post


Link to post
Share on other sites

I do have TracyDebugger installed, but i did not know i could do that in the TracyDebugger 🙂

You learn something new everyday.

Thank you all for helping me understand this. 🙂

Share this post


Link to post
Share on other sites

As @bernhard said, the add returns the whole PageImages array including the new, unaltered image file.

You may create variations afterwards but if you need to do some "editing" before, you'll probably have to go through PHP, download the file into a temporary folder, perform any kind of manipulation and then add the local file to the PageImages array.

  • Like 1
  • Thanks 1

Share this post


Link to post
Share on other sites
1 minute ago, Autofahrn said:

As @bernhard said, the add returns the whole PageImages array including the new, unaltered image file.

You may create variations afterwards but if you need to do some "editing" before, you'll probably have to go through PHP, download the file into a temporary folder, perform any kind of manipulation and then add the local file to the PageImages array.

Ok i got it.

But i was refering to changing the Pageimage obj properties that was newly created:
https://processwire.com/api/ref/pageimage/#api-construct

And then save it.

But maybe i should save it, find it, change it and then save it again?

Share this post


Link to post
Share on other sites

Thanks to Everyone involved with helping me on this subject. Sometimes you can get confused and then need another set of eyes on the problem to figure it out.

  • Like 1

Share this post


Link to post
Share on other sites
24 minutes ago, EyeDentify said:

But i was refering to changing the Pageimage obj properties that was newly created

If you create variations from an existing PageImage, they exist as files only, there is no need to save the page afterwards. For that reason you may create variations on the fly during output (i.e. thumbnail with reduced size).

  • Thanks 1

Share this post


Link to post
Share on other sites
6 minutes ago, Autofahrn said:

If you create variations from an existing PageImage, they exist as files only, there is no need to save the page afterwards. For that reason you may create variations on the fly during output (i.e. thumbnail with reduced size).

Oki. I have to do some testing but i think i got the gist of it.

  • Like 1

Share this post


Link to post
Share on other sites

Thanks to bernhard and Autofahrn i have come up with this example code and run it in TracyDebugger on a test page with a image field and it works beautifully.

 

<?PHP
/* get and save a new image to image field Pageimages array */
$page->of(false);
$pageImages = $page->images->add('https://www.somesite.com/image_of_tree.jpg');

/* save the page (perhaps not needed but there for comfort.) */
$page->save();

/* get the last added image */
$lastImage = $page->images->last();

/* debug before changes */
d($lastImage, '$lastImage before changes');

/* add tags to the image and description */
$lastImage->addTag('test');
$lastImage->addTag('Tree');
$lastImage->addTag('Syren');
$lastImage->addTag('Sun');
$lastImage->addTag('Sunny');
$lastImage->description = 'This is a beautiful tree.';

/* debug info */
d($page->images, '$page->images');
d($lastImage, '$lastImage');

/* save the page */
$page->save();
?>

I used the following API docs and mentioned forums users help to accomplish this:
https://processwire.com/api/ref/pageimage/

https://processwire.com/api/ref/pageimages/

https://processwire.com/api/ref/pagefile/

https://processwire.com/api/ref/pagefiles/

 

Just wanted to post this at the end so others who wonder about this could get a starting point.

 

  • Like 4

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Chris Bennett
      Hi all, I am going round and round in circles and would greatly appreciate if anyone can point me in the right direction.
      I am sure I am doing something dumb, or missing something I should know, but don't. Story of my life 😉

      Playing round with a module and my basic problem is I want to upload an image and also use InputfieldMarkup and other Inputfields.
      Going back and forth between trying an api generated page defining Fieldgroup, Template, Fields, Page and the InputfieldWrapper method.

      InputfieldWrapper method works great for all the markup stuff, but I just can't wrap my head around what I need to do to save the image to the database.
      Can generate a Field for it (thanks to the api investigations) but not sure what I need to do to link the Inputfield to that. Tried a lot of stuff from various threads, of varying dates without luck.
      Undoubtedly not helped by me not knowing enough.

      Defining Fieldgroup etc through the api seems nice and clean and works great for the images but I can't wrap my head around how/if I can add/append/hook the InputfieldWrapper/InputfieldMarkup stuff I'd like to include on that template as well. Not even sure if it should be where it is on ___install with the Fieldtype stuff or later on . Not getting Tracy errors, just nothing seems to happen.
      If anyone has any ideas or can point me in the right direction, that would be great because at the moment I am stumbling round in the dark.
       
      public function ___install() { parent::___install(); $page = $this->pages->get('name='.self::PAGE_NAME); if (!$page->id) { // Create fieldgroup, template, fields and page // Create new fieldgroup $fmFieldgroup = new Fieldgroup(); $fmFieldgroup->name = MODULE_NAME.'-fieldgroup'; $fmFieldgroup->add($this->fields->get('title')); // needed title field $fmFieldgroup->save(); // Create new template using the fieldgroup $fmTemplate = new Template(); $fmTemplate->name = MODULE_NAME; $fmTemplate->fieldgroup = $fmFieldgroup; $fmTemplate->noSettings = 1; $fmTemplate->noChildren = 1; $fmTemplate->allowNewPages = 0; $fmTemplate->tabContent = MODULE_NAME; $fmTemplate->noChangeTemplate = 1; $fmTemplate->setIcon(ICON); $fmTemplate->save(); // Favicon source $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeImage"); $fmField->name = 'fmFavicon'; $fmField->label = 'Favicon'; $fmField->focusMode = 'off'; $fmField->gridMode = 'grid'; $fmField->extensions = 'svg png'; $fmField->columnWidth = 50; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon(ICON); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($fmField); // Favicon Silhouette source $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeImage"); $fmField->name = 'fmFaviconSilhouette'; $fmField->label = 'SVG Silhouette'; $fmField->notes = 'When creating a silhouette/mask svg version for Safari Pinned Tabs and Windows Tiles, we recommend setting your viewbox for 0 0 16 16, as this is what Apple requires. In many cases, the easiest way to do this in something like illustrator is a sacrificial rectangle with no fill, and no stroke at 16 x 16. This forces the desired viewbox and can then be discarded easily using something as simple as notepad. Easy is good, especially when you get the result you want without a lot of hassle.'; $fmField->focusMode = 'off'; $fmField->extensions = 'svg'; $fmField->columnWidth = 50; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon(ICON); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($fmField); // Create: Open Settings Tab $tabOpener = new Field(); $tabOpener->type = new FieldtypeFieldsetTabOpen(); $tabOpener->name = 'fmTab1'; $tabOpener->label = "Favicon Settings"; $tabOpener->collapsed = Inputfield::collapsedNever; $tabOpener->addTag(MODULE_NAME); $tabOpener->save(); // Create: Close Settings Tab $tabCloser = new Field(); $tabCloser->type = new FieldtypeFieldsetClose; $tabCloser->name = 'fmTab1' . FieldtypeFieldsetTabOpen::fieldsetCloseIdentifier; $tabCloser->label = "Close open tab"; $tabCloser->addTag(MODULE_NAME); $tabCloser->save(); // Create: Opens wrapper for Favicon Folder Name $filesOpener = new Field(); $filesOpener->type = new FieldtypeFieldsetOpen(); $filesOpener->name = 'fmOpenFolderName'; $filesOpener->label = 'Wrap Folder Name'; $filesOpener->class = 'inline'; $filesOpener->collapsed = Inputfield::collapsedNever; $filesOpener->addTag(MODULE_NAME); $filesOpener->save(); // Create: Close wrapper for Favicon Folder Name $filesCloser = new Field(); $filesCloser->type = new FieldtypeFieldsetClose(); $filesCloser->name = 'fmOpenFolderName' . FieldtypeFieldsetOpen::fieldsetCloseIdentifier; $filesCloser->label = "Close open fieldset"; $filesCloser->addTag(MODULE_NAME); $filesCloser->save(); // Create Favicon Folder Name $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeText"); $fmField->name = 'folderName'; $fmField->label = 'Favicon Folder:'; $fmField->description = $this->config->urls->files; $fmField->placeholder = 'Destination Folder for your generated favicons, webmanifest and browserconfig'; $fmField->columnWidth = 100; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon('folder'); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($tabOpener); $fmFieldgroup->add($filesOpener); $fmFieldgroup->add($fmField); $fmFieldgroup->add($filesCloser); $fmFieldgroup->add($tabCloser); $fmFieldgroup->save(); /////////////////////////////////////////////////////////////// // Experimental Markup Tests $wrapperFaviconMagic = new InputfieldWrapper(); $wrapperFaviconMagic->attr('id','faviconMagicWrapper'); $wrapperFaviconMagic->attr('title',$this->_('Favicon Magic')); // field show info what $field = $this->modules->get('InputfieldMarkup'); $field->name = 'use'; $field->label = __('How do I use it?'); $field->collapsed = Inputfield::collapsedNever; $field->icon('info'); $field->attr('value', 'Does this even begin to vaguely work?'); $field->columnWidth = 50; $wrapperFaviconMagic->add($field); $fmTemplate->fields->add($wrapperFaviconMagic); $fmTemplate->fields->save(); ///////////////////////////////////////////////////////////// // Create page $page = $this->wire( new Page() ); $page->template = MODULE_NAME; $page->parent = $this->wire('pages')->get('/'); $page->addStatus(Page::statusHidden); $page->title = 'Favicons'; $page->name = self::PAGE_NAME; $page->process = $this; $page->save(); } }  
    • By Pip
      Hi everyone, 
      Is there a way for us to replicate the "http://mydomain.com/processwire/page/edit/?id=xxx" and change the template to match my site template? 
      I'm terribly happy with the admin / backend page edit. It covers literaly everything I want to empower my non super admin user in updating pages such as validation, repeater management, file upload. 
      I wish not to allow the users to see the backend for both security and aesthetic reasons. 
      Thanks and hope to hear from you soon. 
       
    • By marcus
      wireshell 1.0.0 is out    
      See Bea's post
       


      -------- Original post -----------
        Now this one could be a rather long post about only an experimental niche tool, but maybe a helpful one for some, so stay with me   Intention Do you guys know "Artisan" (Laravel) or "Drush" (Drupal)? If not: These are command line companions for said systems, and very useful for running certain (e.g. maintenance, installation) task quickly - without having to use the Admin Interface, first and foremost when dealing with local ProcessWire installations. And since it has a powerful API and an easy way of being bootstrapped into CLIs like this, I think such a tool has a certain potential in the PW universe.    It's totally not the first approach of this kind. But: this one should be easily extendable - and is based on PHP (specifically: the Console component of the Symfony Framework). Every command is tidily wrapped in its own class, dependencies are clearly visible, and so on.   ( Here was the outdated documentation. Please visit wireshell.pw for the current one )
    • By Mats
      BETA: SplashAndGrab
      https://github.com/madebymats/InputfieldSplashAndGrab
      This module attaches a search input to selected image fields that lets you search and download images from Unsplash.
      (Unsplash is a stock photo service where you can download images for free and use as you wish. No strings attached.)   
      You can search by string, colors, orientation/crop and order by relevance or time published
      I find Unsplash useful both for placeholder images when building sites but also as a time saver for editors if they don’t have any images at hand, just search, download and publish.

      Thanks to @apeisa for building the  FlickrInputField Module and @Robin S for AddImageUrls,  took a lot ideas and code from those modules.
    • By Markus (Blue Tomato)
      We have created a module to create BlurHash strings for images while uploading in ProcessWire. This blurry images will be saved in the database because they are very small (20-30 characters) and can be used for Data-URL's  as placeholders for image-lazy loading.
      https://github.com/blue-tomato/ImageBlurhash
      E.g. where we use this in production:
      https://www.blue-tomato.com/en-INT/blue-world/ https://www.blue-tomato.com/en-INT/blue-world/products/girls-are-awesome/ https://www.blue-tomato.com/en-INT/buyers-guides/skateboard/skateboard-decks/ https://www.blue-tomato.com/en-INT/team/anna-gasser/
×
×
  • Create New...