horst

Pagetree Add New Child Reverse (on Top)

Recommended Posts

Pagetree Add New Child Reverse

New Pages in Descending Sortorder (newest first) while sortmode can be "Manual Drag-n-Drop"
 
When a site display an overview of the latest posts, news, image-albums, etc. the newest entries should be on top of the list. We can achieve that by using an automated setting for the sortfield e.g. when the page was created = "-created".
 
But this way we are not able to manually move a single page in the tree.
 
This module enables us to do exactly that. It works with manually created pages, with pages created via the API, also when bootstrapped by importer scripts.
 
 
 
Pagetree "Newsitems" with 3 newsitems sorted in descending order.

PageTreeAddNewChildsReverse_1.jpg

 
New created item 4 is added to the top.
 
PageTreeAddNewChildsReverse_2.jpg

 
To change the order click item 3 and drag it to the top and drop it.
 
PageTreeAddNewChildsReverse_3.jpg
 
PageTreeAddNewChildsReverse_4.jpg

PageTreeAddNewChildsReverse_5.jpg
 

How to use it

Download the module into your site/modules/ directory and install it.
 
In the config page you find a single textarea field. Here you can enter the templatename or page-ID of the page which children should get reverse added, - optionally followed by a comma and the child-templatename if you need a more precise selector.
 
You can add as many parents as you like, but only one on each line and in this format:
TEMPLATE-NAME or PAGE-ID[,CHILDTEMPLATE-NAME].
 
A few examples:

newsitems
posts,post
1042
1033,album

 
You want set your template(s) sortfield(s) to 'Manual drag-n-drop' if not have done already.

 
ATTENTION
 
You need to setup the TreeParent and the module config when there are no children in it! Otherwise it will not work!
 
Also disabling the module once you have added children and then add one new page to it will mess up all!
(You may think about to install the module as permanent in critical situations.?! see below ->)

If you need to install it in a site for an already existing branch, you can do it this way:

  1. move / rename your existing branch
  2. create a new (empty) branch with the original name
  3. move your childpages into the new branch
  4. remove the renamed (and now empty) old branch

 
 
DOWNLOAD   -  Version 1.0.2

 
 
Want to make it bulletproof?
 
If you are concerned that the module settings could be dropped by other users or that the module itself could be uninstalled by accident, you may edit the module file directly:

This way the permanent settings couldn't be dropped by accident. To change it you first need to edit the modules file again.

Example:

You have two settings in the inputfield of the modules config, without permanent setting:

parenttemplate1,childtemplate1
parenttemplate2,childtemplate2

Now you want to have the the first setting become bulletproof permanent:

a) you enable the setting in the getModuleInfo, (uncomment setting for permanent)

b) you write your permanent settings under the constant permanentValue

const permanentValue = "parenttemplate1,childtemplate1";

After both steps, the module cannot get uninstalled anymore (Step a), and the first setting cannot get deleted anymore (Step b), as it is recreated with every call of the configscreen. (See first code line of method getModuleConfigInputfields)

If you want to keep both definitions permanent, write them separated with a newline character "\n" :

const permanentValue = "parenttemplate1,childtemplate1\nparenttemplate2,childtemplate2";




History of origins

Edited by horst
added example how to make it permanent
  • Like 12

Share this post


Link to post
Share on other sites

Wow, I can't wrap my mind around this. How is this possible without heavy overhead. Great work Horst, thank You !

Sneakpeeked at the code... clever :-)

Edited by Martijn Geerts
  • Like 1

Share this post


Link to post
Share on other sites

This does look great horst.

I think it is something I am going to have to be aware of though as my page tree migrator module gets closer to release. I can see it being an issue if migrating pages from a site that has this installed, or to one that has it installed if the other doesn't. Not sure how to handle that, but we'll see :)

Just curious - did you test the idea of negative number indexing? Might be opening another can of worms though!

  • Like 1

Share this post


Link to post
Share on other sites

 ... Just curious - did you test the idea of negative number indexing? Might be opening another can of worms though!

It doesn't work with negative numbers. They get corrected to 0 (zero) at some other points in PW, not only at Pages::setupNew() :(

  • Like 1

Share this post


Link to post
Share on other sites

I have template pr-index, children (template pr-item) are reverse sorted by pubdate (Datetime field in pr-item), not reverse sorted by created date. Is it possible to have manual drag-n-drop in this situation? 

Share this post


Link to post
Share on other sites

No sorry, this isn't possible. :(

Share this post


Link to post
Share on other sites

Successfully tested with PW 3.0 today :)

  • Like 3

Share this post


Link to post
Share on other sites
On 10/18/2013 at 4:34 PM, horst said:

ATTENTION
 
You need to setup the TreeParent and the module config when there are no children in it! Otherwise it will not work!

So I can't use this module on a production site? What if I unpublish the children?

Share this post


Link to post
Share on other sites

Based on the suggestion by @abdus, put this in your ready.php file:

$this->addHookAfter("Pages::saved", function($event) {
    $this->pages->sort($event->arguments[0], 0);
});

Note that $event->arguments[0] returns the page that was just saved.

Perhaps it would be a good idea to resort all other children too - have a read more about this here:
https://processwire.com/api/ref/pages/sort/

I think in this use case you'd actually want to use the parent of the saved page so that all child pages are sorted. I honestly have played around with this, so not sure if it matters or not.

  • Like 2

Share this post


Link to post
Share on other sites
Quote
5 minutes ago, adrian said:

Perhaps it would be a good idea to resort all other children too

Thanks for the quick solution, @adrian

I'm not sure if we're talking about the same thing, but docs mention that these methods modify other siblings to accept new order.

Quote

$pages->sort($page, $n)
This method sets and saves the sort value of $page to integer $n (0 based), and then also adjusts the sort values of all sibling pages as needed to ensure consistent order.

  • Like 1

Share this post


Link to post
Share on other sites
25 minutes ago, abdus said:

I'm not sure if we're talking about the same thing, but docs mention that these methods modify other siblings to accept new order.

Yeah, I agree that it sounds like it should take care of it (and it appears to work just fine), but I guess I am wondering what the point of this is:

// re-build sort values for children of $page, removing duplicates and gaps
$pages->sort($page, true);

Why would there be duplicates/gaps in the first place if the main sort() method works as expected? Maybe it's to clean things up if you did some manual changes? I am really not sure, but it seems like it shouldn't be necessary.

Share this post


Link to post
Share on other sites
1 hour ago, PWaddict said:

So I can't use this module on a production site? What if I unpublish the children?

unpublishing doesn't help. You need to start with an empty parent!

  • once I moved all children to a temporary parent,
  • installed and configured the module,
  • and then moved the children back.

But please, do a BACKUP of your DB before!

Share this post


Link to post
Share on other sites

@horst - what do you think - does the use of the new sort() method in a Pages::saved hook (like my example above) make this module obsolete or is there another scenario I am not thinking of?

Share this post


Link to post
Share on other sites

I don't know. What comes to my mind, and thats why I posted this to @PWaddict, is, that with my module simply the next free number (counted down!) is put onto the new page. No need to resort all other siblings!

With a huge amount of sibling pages, the new sort function may slow down the process. But I haven't tested it.

Share this post


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

the new sort function may slow down the process

I haven't tested at scale, but Ryan notes:

Quote

One nice thing about the sort() method is that it doesn't actually load any pages to do its job. It handles it all at the database level, so it can do it's job quickly regardless of scale.

https://processwire.com/blog/posts/pw-3.0.46-stocking-stuffers/#new-pages-api-manipulation-methods

  • Like 1

Share this post


Link to post
Share on other sites
14 minutes ago, adrian said:

does the use of the new sort() method in a Pages::saved hook (like my example above) make this module obsolete or is there another scenario I am not thinking of?

What about sites that still use PW 2.7? :):'(

  • Like 1

Share this post


Link to post
Share on other sites
Just now, kongondo said:

What about sites that still use PW 2.7? :):'(

Sure, but why not update the site to 3.x or at least 2.8 :) I have updated all my old sites and most involved no code changes. Only a couple of sites needed some work with bootstrapped ajax calls etc, but that was it.

Just so you know, I am not trying to say that this module should be removed, but perhaps it might be possible to say it is no longer required with PW 3. Obviously a little more testing would be beneficial - just wanting to start the dialog. 

 

Share this post


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

Sure, but why not update the site to 3.x or at least 2.8 :) I have updated all my old sites and most involved no code changes. Only a couple of sites needed some work with bootstrapped ajax calls etc, but that was it.

Just so you know, I am not trying to say that this module should be removed, but perhaps it might be possible to say it is no longer required with PW 3. Obviously a little more testing would be beneficial - just wanting to start the dialog. 

^-^:)

Share this post


Link to post
Share on other sites
5 minutes ago, adrian said:

Sure, but why not update the site to 3.x or at least 2.8 :) I have updated all my old sites and most involved no code changes. Only a couple of sites needed some work with bootstrapped ajax calls etc, but that was it.

I do not update all sites to 3.x or 2.8.x. I have sites from 2.4, 2.5, 2.6, 2.7, and some different 3.0.x. Only one of version 2.8!
(never touch a running system) :)

  • Like 1

Share this post


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

never touch a running system

Hope you're still enjoying Windows 3.1 then :) Sorry I couldn't resist ... ha ha ha - not really very funny I know :)

We are obviously getting way OT, but I guess the key thing for me is that there is now an option with $pages->sort() to easily add reverse order functionality after a site is already set up if we decide it would be a better UX.

I like having options!

  • Like 1
  • Haha 1

Share this post


Link to post
Share on other sites
14 hours ago, adrian said:

 


$this->addHookAfter("Pages::saved", function($event) {
    $this->pages->sort($event->arguments[0], 0);
});

 

I'm gonna test this soon. How can I apply it only to 1 or 2 specific templates?

Share this post


Link to post
Share on other sites

@PWaddict change $templates as necessary

$this->addHookAfter("Pages::saved", function($event) {
    $templates = ['product', 'post' ];
    $page = $event->arguments[0];

    if (! in_array($page->template->name, $templates)) return;

    $this->pages->sort($page, 0);
});
  • Like 2

Share this post


Link to post
Share on other sites

I just test it and it works great. I replaced "saved" with "published" otherwise everytime my client will edit the pages sorting will applied. So for PW 3.0.46+ no need this module.

  • Like 3

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 BitPoet
      As threatened in the Pub sub forum in the "What are you currently building?" thread, I've toyed around with Collabora CODE and built file editing capabilities for office documents (Libre-/OpenOffice formats and MS Office as well as a few really old file types) into a PW module.
      If you are running OwnCloud or NextCloud, you'll perhaps be familiar with the Collabora app for this purpose.
      LoolEditor
      Edit office files directly in ProcessWire
      Edit your docx, odt, pptx, xlsx or whatever office files you have stored in your file fields directly from ProcessWire's page editor. Upload, click the edit icon, make your changes and save. Can be enabled per field, even in template context.
      Currently supports opening and saving of office documents. Locking functionality is in development.
      See the README on GitHub for installation instructions. You should be reasonably experienced with configuring HTTPS and running docker images to get things set up quickly.
      Pull requests are welcome!
      Here is a short demonstration:

    • By Robin S
      An Images field allows you to:
      Rename images by clicking the filename in the edit panel or in list view. Replace images, keeping metadata and filename (when possible) by dropping a new image on the thumbnail in the edit panel. Introduced here. But neither of these things is possible in File fields, which prompted this module. The way that files are renamed or replaced in this module is not as slick as in the Images field but it gets the job done. The most time-consuming part was dealing with the UI differences of the core admin themes. @tpr, gives me even more respect for the work that must go into AdminOnSteroids.
      Most of the code to support the rename/replace features is already present in InputfieldFile - there is just no UI for it currently. So hopefully that means these features will be offered in the core soon and this module can become obsolete.
       
      Files Rename Replace
      Allows files to be renamed or replaced in Page Edit.

      Usage
      Install the Files Rename Replace module.
      If you want to limit the module to certain roles only, select the roles in the module config. If no roles are selected then any role may rename/replace files.
      In Page Edit, click "Rename/Replace" for a file...
      Rename
      Use the text input to edit the existing name (excluding file extension).
      Replace
      Use the "Replace with" select to choose a replacement file from the same field. On page save the file will be replaced with the file you selected. Metadata (description, tags) will be retained, and the filename also if the file extensions are the same.
      Tip: newly uploaded files will appear in the "Replace with" select after the page has been saved.
       
      https://github.com/Toutouwai/FilesRenameReplace
      http://modules.processwire.com/modules/files-rename-replace/
    • By d'Hinnisdaël
      So I decided to wade into module development and created a wrapper module around ImageOptim, a service that compresses and optimizes images in the cloud. ImageOptim currently handles JPG, PNG and GIF files and, depending on the settings you use, shaves off between 15% and 60% in filesize. Great for bandwidth and great for users, especially on mobile.
      This module handles the part of uploading images to ImageOptim via their official API, downloading the optimized version and storing it alongside the original image.
       

       
      Download & Info
      GitHub / Module directory / Readme / Usage
       
      Why ImageOptim?
      There are other image optimization services out there, some of them free, that have outstanding ProcessWire modules. A few things make ImageOptim the best tool for most of my customers: It's not free, i.e. it will probably be around for a while and offers support. However, it's cheaper than some of the bigger competitors like Cloudinary. And it does PNG compression better than any of the free services out there, especially those with alpha channels.
       
      Installation
      Install the module like any other ProcessWire module, by either copying the folder into your modules folder or installing it via the admin. See above for downloads links on GitHub and in the module directory.
       
      Requirements
      To be able to upload images to the service, allow_url_fopen must be set on the server. The module will abort installation if that's not the case.
      I have only tested the module on ProcessWire 3.x installations. I don't see why it shouldn't work in 2.x, if anyone wants to try it out and report back.
       
      ImageOptim account
      To compress images, you first need to sign up for an ImageOptim account. They offer free trials to try the service.
       
      Usage (manual optimization)
      Images can be optimized by calling the optimize() method on any image. You can pass an options array to set ImageOptim API parameters.
      $image->size(800,600)->optimize()->url $image->optimize(['quality' => 'low', 'dpr' => 2]) // Set quality to low and enable hi-dpi mode
      Automatic optimization
      The module also has an automatic mode that optimizes all image variations after resizing. This is the recommended way to use this module since it leaves the original image uncompressed, but optimizes all derivative images.
      $image->size(800,600)->url // nothing to do here; image is optimized automatically
      To change compression setting for single images, you can pass an options array along with the standard ImageResizer options. Passing false disables optimization.
      $image->size(800, 600, ['optimize' => 'medium']) $image->size(800, 600, ['optimize' => ['quality' => 'low', 'dpr' => 2]]) $image->size(800, 600, ['optimize' => false])
      For detailed usage instructions and all API parameters, see the usage instructions on GitHub.
       
      Filenames
      Optimized images will be suffixed, e.g. image.jpg becomes image.optim.jpg. You can configure the suffix in the module settings.
       
      Roadmap
      Asynchronous processing. Not really high on the list. Image variations need to be created anyway, so waiting a few seconds longer on first load is preferable to adding complexity to achieve async optimization. Optimize image variations created by other modules. CroppableImage comes to mind. I don't use any of these, so if somebody wants to help out and submit a pull request — all for it! Add a dedicated page in the setup menu with a dashboard and detailed statistics. ImageOptim's API is very barebones for now, so not sure if that's feasible or even necessary.
      Stability
      I've been using this module on production sites for some time now, without hiccups. If you do notice oddities, feel free to comment here or investigate and submit PRs.
    • By daniels
      General
      This is a lightweight alternative to other newsletter & newsletter-subscription modules.
      It can update / create a subscriber in a list in Mailchimp with MailChimp API 3.0. It does not provide any forms or validation, so you can feel free to use your own. To protect your users, it does not save any user data in logs or sends them to an admin.
      This module fits your needs if you...
      ...use Mailchimp as your newsletter / email-automation tool ...want to let users subscribe to your newsletter on your website ...want to use your own form, validation and messages (with or without the wire forms) ...don't want any personal user data saved in any way in your ProcessWire environment (cf. EU data regulation terms) ...like to subscribe users to different lists ...like the Mailchimp UI for creating / sending / reviewing email campaigns You can find it here: https://github.com/danielstieber/SubscribeToMailchimp
      Let me know what you think and if I should add it to the Modules Directory.
      Setup
      Log into your Mailchimp account and go to  Profile > Extras > API Keys. If you don't have an API Key, create a new one. Copy your API Key and paste it in the module settings (Processwire > Modules > Site > SubscribeToMailchimp). Back in Mailchimp, go to the list, where you want your new subscribers. Go to Settings > List name and defaults. Copy the List ID an paste it in to the module settings.
      Usage
      To use the module, you need to load it into your template:
      $mc = $modules->get("SubscribeToMailchimp"); Now you can pass an email address to the module and it will try to edit (if the user exists) or create a new subscriber in your list.
      $mc->subscribe('john.doe@example.com'); You can also pass a data array, to add additional info.
      $mc->subscribe('john.doe@example.com', ['FNAME' => 'John', 'LNAME' => 'Doe']); You can even choose an alternative list, if you don't want this subscriber in your default list.
      $mc->subscribe('john.doe@example.com', ['FNAME' => 'John', 'LNAME' => 'Doe'], 'abcdef1356'); // Subscribe to List ID abcdef1356  
      Important Notes
      This module does not do any data validation. Use a sever-sided validation like Valitron Make sure that you have set up your fields in your Mailchimp list. You can do it at Settings > List fields and *|MERGE|* tags Example
      Example usage after a form is submitted on your page:
      // ... validation of form data $mc = $modules->get("SubscribeToMailchimp"); $email = $input->post->email; $subscriber = [ 'FNAME' => $input->post->firstname, 'LNAME' => $input->post->lastname, ]; $mc->subscribe($email, $subscriber);  
      Troubleshooting
      In case of trouble check your ProcessWire warning logs.
      I can't see the subscriber in the list
      If you have enabled double opt-in (it is enabled by default) you will not see the subscriber, until he confirmed the subscription in the email sent by Mailchimp
      I get an error in my ProccessWire warning logs
      Check if you have the right List ID and API Key. Check if you pass fields, that exist in your list. Check if you pass a valid email address. Go to Mailchimps Error Glossary for more Information
      How To Install
      Download the zip file at Github or clone directly the repo into your site/modules If you downloaded the zip file, extract it in your sites/modules directory. You might have to change the folders name to 'SubscribeToMailchimp'. Goto the modules admin page, click on refresh and install it  
    • By PWaddict
      Module for hiding pages for non-superusers.
      Download
      HidePages
      Requirements
      ProcessWire 3.x Changelog
      1.0.1 (31 March 2018)
      Module renamed to prevent confusion 1.0.0 (30 March 2018)
      Initial release