Jump to content
kixe

Page sorting and moving via API

Recommended Posts

This morning I pushed a module to github which extends the page api with moving and sorting capability.

https://github.com/kixe/PageMove

 * CALLABLE (static & instance)
 * PageMove::execute($page, $parent = null, $newIndex = 0, $selector = 'all');
 * $modules->get('PageMove')->execute($page, $parent = null, $newIndex = 0, $selector = 'all');
 *
 * EXTENDED PAGE API
 * @method $page->move($parent, $newIndex = null, $selector = 'all')
 * @method $page->setIndex($newIndex, $selector = 'all') // set absolute index include=all
 * @method $page->getIndex($selector = '') // same as $page->index without argument @see getSelector()
 *
 * @method $page->moveFirst($parent = null)
 * @method $page->moveLast($parent = null)
 * @method $page->moveForward($steps = 1, $selector = 'all')
 * @method $page->moveBackwards($steps = 1, $selector = 'all')
 *
 * @property $page->moveFirst // same parent
 * @property $page->moveLast
 * @property $page->moveForward
 * @property $page->moveBackwards
 *
 * EXTENDED PAGES API
 * @method $pages->move($page, $parent = null, $newIndex = 0, $selector = 'all')
 * @method $pages->resortChildren($page, $selectorValue)
 * // same like core function $pages->sort($page, true); with capibility to change the sort condition

Have a nice weekend.

  • Like 8

Share this post


Link to post
Share on other sites

Is $page->first means move page to first position? If so, wouldn't be a more descriptive name better, eg moveFirst or similar?

  • Like 1

Share this post


Link to post
Share on other sites

Thanks for input. I have been searching for something really short. I am also not sure about the modules name. Any recommendation welcome. :rolleyes:

I changed the method/ property names to moveFirst and moveLast.

  • Like 1

Share this post


Link to post
Share on other sites
53 minutes ago, LostKobrakai said:

Just so you don't miss them; there are sorting functions in the dev version of 3.0:

Of course I missed them. Thanks for the hint.

  • Like 1

Share this post


Link to post
Share on other sites

@LostKobrakai

I took a look in the core sorting functions. Unfortunately it doesn't work as expected and the $pages API reference is faulty and should be updated:

// set $page to have sort=5, moving any 5+ sort pages ahead
$pages->sort($page, 5); // works as expected

// same as above using alternate syntax
$page->sort = 5; // WILL NOT moving any 5+ sort pages ahead it just changes the sort value. Duplicates possible
$pages->sort($page); // WILL NOT set anything. This is a getter not a setter. Similar to $page->sort

In the $page API reference, $page->sort is described as follow which is faulty too.

Quote

Sort order of this page relative to siblings (applicable when manual sorting is used).

Use $page->index instead to get expected/ described result. But you cannot use $page->index as a setter!


Currently the only (nearly)  working solution needs the following 2 steps

$pages->sort($page->parent, true); // re-build sort values for children of $page, removing duplicates and gaps
$pages->sort($page, 5); // sort +=1 for all pages above

In this example you will get an unexpected result If the sort position related to the siblings was 4 before. There will be no change, because there is a gap at sort position 4 now.


What I would expect using this function

If I set sort I would expect a zero based position related to the page siblings.


Example

$pages->sort($page, 2);

3 page siblings having the sort values 4, 7, and 11. If I assign a sort value 2 to the page with the former sort value 7 I would expect the page moves to the end (last index number under 3 siblings), but currently it moves in the opposit direction and will be the first one related to its 2 siblings.

Nice to have in the future
(already available via PageMove module)

// move page to the first or last position related to its siblings
$page->moveFirst;
$page->moveLast;
$page->moveFirst($newParent = null);
$page->moveLast($newParent = null);

// move the page to an index position relative to its siblings, optionally change the parent too in one step
$page->move($parent, $newIndex = null, $selector = 'all')

// or simply
$page->setIndex($newIndex, $selector = 'all');


Expecting a core update related to this I will not push the module to the modules directory. Feel free to pull it from github directly until this is available from core.

 

 



 

Edited by kixe
module update 1.0.2
  • Like 2

Share this post


Link to post
Share on other sites

$page->sort always worked this way, which is why most people simply avoided changing it most of the time. It might need some clarification now that there is a function which does prevent duplicate sort values.

13 minutes ago, kixe said:

What I would expect using this function

If I set sort I would expect a zero based position related to the page siblings.

Rebuilding all sort values is a waist of db computation. Imagine you've 10000 siblings and you reorder just the 9999 to be the last one. If there are gaps in the first siblings sort values it'll rebuild all 10000 instead of just a few pages.

16 minutes ago, kixe said:

Example


$pages->sort($page, 2);

3 page siblings having the sort values 4, 7, and 11. If I assign a sort value 2 to the page with the former sort value 7 I would expect the page moves to the end (last index number under 3 siblings), but currently it moves in the opposit direction and will be the first one related to its 2 siblings.

I think you expect to set the new index of the page not the sort value, which in ProcessWire are currently different things. I see that it might be confusing, but mostly because people rarely dealt with that issue by now as sorting was mostly done via the GUI / modules.

It would be great if you could formulate those issue you had in a github issue, so that ryan can improve on them. 

  • Like 2

Share this post


Link to post
Share on other sites
19 hours ago, LostKobrakai said:

Rebuilding all sort values is a waist of db computation. Imagine you've 10000 siblings and you reorder just the 9999 to be the last one. If there are gaps in the first siblings sort values it'll rebuild all 10000 instead of just a few pages.

I completely agree. I don't mind about the absolute sort value, but the page index should be in the right place. In my example it is enough if the page with previous sort value 7 get the index 2, which is the fact if a sort value of 12 is assigned (one more than 11)


For handling pages the absolute sort value is not of interest it does say nothing, the index position is the important value.
So it would be nice in addition to get the index via $page->index  having a setting method.

19 hours ago, LostKobrakai said:

It would be great if you could formulate those issue you had in a github issue, so that ryan can improve on them. 

Of course I will do that.
https://github.com/processwire/processwire-issues/issues/225

  • Like 1

Share this post


Link to post
Share on other sites

I pushed a revision 1.0.2 of the module with extended capability and more delimited from core functions (still using them if possible).

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By louisstephens
      Going through my long quest to get better with ajax and utilizing the api, I have hit yet another roadblock. I currently have a form with an image field (thanks to flydev for getting that sorted), "title" text input, and a select field set to multiple. In my ajax call, I added in:
      tags = $("#select-tags").val(); form_data.append('tags', tags); $.ajax({ type: 'POST', data: form_data, contentType: false, processData: false, url: '/ajax/upload-preview/', success: function(data) { console.log("Woo"); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); } }); And in the ajax template: 
      $tags = $sanitizer->text($_POST['tags']); $image = $sanitizer->text($_POST['image']); $p = new Page(); $p->template = "preview"; $p->parent = $pages->get("/previews/"); $p->name = $title; $p->title = $title; $p->tags = $tags; $p->save(); If I select a "tag" from the select input and submit, it does indeed add it to the Page Reference field in the backend. However, this does not work with an array being passed to it of multiple options.

      So it does appear that my ajax call is trying to submit multiple options, but I am really just unsure how to get these two added in. I saw in other forums posts of add($page) and even add(array()). Do I need to handle this js array differently or do  I need to foreach through the $tags to add it like:
      foreach($tags as $tag) { $p->tags->add($tag); $p->save(); } I tried this approach, but apparently I am still missing something.
       
      Edit:
      I was doing some tweaking, and I know I can split the js array out like:
      for (i = 0, len = tags.length; i < len; i++) { console.log(tags[i]); } However, I am not sure then how to handle the POST in php if I were to split it out.
    • By Robin S
      Repeater Images
      Adds options to modify Repeater fields to make them convenient for "page-per-image" usage. Using a page-per-image approach allows for additional fields to be associated with each image, to record things such as photographer, date, license, links, etc.
      When Repeater Images is enabled for a Repeater field the module changes the appearance of the Repeater inputfield to be similar (but not identical) to an Images field. The collapsed view shows a thumbnail for each Repeater item, and items can be expanded for field editing.
      Screencast

      Installation
      Install the Repeater Images module.
      Setup
      Create an image field to use in the Repeater field. Recommended settings for the image field are "Maximum files allowed" set to 1 and "Formatted value" set to "Single item (null if empty)". Create a Repeater field. Add the image field to the Repeater. If you want additional fields in the Repeater create and add these also. Repeater Images configuration
      Tick the "Activate Repeater Images for this Repeater field" checkbox. In the "Image field within Repeater" dropdown select the single image field. You must save the Repeater field settings to see any newly added Image fields in the dropdown. Adjust the image thumbnail height if you want (unlike the core Images field there is no slider to change thumbnail height within Page Edit). Note: the depth option for Repeater fields is not compatible with the Repeater Images module.
      Image uploads feature
      There is a checkbox to activate image uploads. This feature allows users to quickly and easily add images to the Repeater Images field by uploading them to an adjacent "upload" field.
      To use this feature you must add the image field selected in the Repeater Images config to the template of the page containing the Repeater Images field - immediately above or below the Repeater Images field would be a good position.
      It's recommended to set the label for this field in template context to "Upload images" or similar, and set the visibility of the field to "Closed" so that it takes up less room when it's not being used. Note that when you drag images to a closed Images field it will automatically open. You don't need to worry about the "Maximum files allowed" setting because the Repeater Images module overrides this for the upload field.
      New Repeater items will be created from the images uploaded to the upload field when the page is saved. The user can add descriptions and tags to the images while they are still in the upload field and these will be retained in the Repeater items. Images are automatically deleted from the upload field when the page is saved.
      Tips
      The "Use accordion mode?" option in the Repeater field settings is useful for keeping the inputfield compact, with only one image item open for editing at a time. The "Repeater item labels" setting determines what is shown in the thumbnail overlay on hover. Example for an image field named "image": {image.basename} ({image.width}x{image.height})  
      https://github.com/Toutouwai/RepeaterImages
      https://modules.processwire.com/modules/repeater-images/
    • By louisstephens
      I have been messing around with creating pages from ajax requests, and it has gone swimmingly thus far. However, I am really struggling with creating a page and saving an image via ajax. 
      The form:
      <form action="./" role="form" method="post" enctype="multipart/form-data"> <div> <input type="text" id="preview" name="preview" placeholder="Image Title"> </div> <div> <input type="file" id="preview-name" name="preview-name"> </div> <div> <select id="select-tags" name="select-tags"> <?php $tags = $pages->find("template=tag"); ?> <option value="">Select Your Tags</option> <?php foreach ($tags as $tag) : ?> <option value="<?= $tag->name; ?>"><?= $tag->name; ?></option> <?php endforeach; ?> </select> </div> <div> <button type="button" id="submit-preview" name="submit" class="">Upload Images</button> </div> </form>  
      The ajax in my home template:
      $('#submit-preview').click(function(e) { e.preventDefault(); title = $("#preview").val(); image = $("input[name=preview-name]"); console.log(title); console.log(image); data = { title: title, image: image //not sure if this is actually needed }; $.ajax({ type: 'POST', data: data, url: '/development/upload-preview/', success: function(data) { console.log("Woo"); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); } }); }); And finally in my ajax template:
      $imagePath = $config->paths->assets . "files/pdfs/"; //was from an older iteration $title = $sanitizer->text($_POST['title']); $image = $sanitizer->text($_POST['image']); $p = new Page(); $p->template = "preview"; $p->parent = $pages->get("/previews/"); $p->name = $title; $p->title = $title; $p->save(); $p->setOutputFormatting(false); $u = new WireUpload('preview_image'); $u->setMaxFiles(1); $u->setOverwrite(false); $u->setDestinationPath($p->preview_image->path()); $u->setValidExtensions(array('jpg', 'jpeg', 'gif', 'png', 'pdf')); foreach($u->execute() as $filename) { $p->preview_image->add($filename); } $p->save(); I can complete the file upload but just using a simple post to the same page and it it works well, but I was really trying to work out the ajax on this so I could utilize some modals for success on creation (and to keep my templates a little cleaner). When I do run the code I have, a new/blank folder is created under assets, and a new page is created with the correct title entered. However, no image is being processed. I do get a 200 status in my console. I have searched google for help, but everything seems to be slightly off from my needs. If anyone could help point me in the right direction I would greatly appreciate it. 
    • By louisstephens
      This might be a completely dumb question, but I cant seem to wrap my head around it. I have a page reference field that allows users to select "Tags". In the front end I would like to use the titles as class names for a single item. ie:
      <?php $previews = $pages->find("template=preview"); ?> <?php foreach($previews as $preview): ?> <div class="tagOne TagTwo tagThree"> <!-- use another foreach to output--> <img src="<?=$preview->preview_image->url; ?>" /> </div> <?php endforeach; ?> I am little stumped as I know I need a foreach loop to produce each tag title, but how do I insert them all into one corresponding div class with spaces?
      Whelp, that was the easiest thing, but my brain just didnt "get it". Just put the foreach in the "class" inside of the overall foreach. Ugh 😓
    • By EyeDentify
      Hello There Guys.

      I am in the process of getting into making my first modules for PW and i had a question for you PHP and PW gurus in here.

      I was wondering how i could use an external library, lets say TwitterOAuth in my PW module.
      Link to library
      https://twitteroauth.com/

      Would the code below be correct or how would i go about this:
      <?PHP namespace ProcessWire; /* load the TwitterOAuth library from my Module folder */ require "twitteroauth/autoload.php"; use Abraham\TwitterOAuth\TwitterOAuth; class EyeTwitter extends WireData,TwitterOAuth implements Module { /* vars */ protected $twConnection; /* extend parent TwitterOAuth contructor $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret); */ public function myTwitterConnection ($consumer_key, $consumer_secret, $access_token, $access_token_secret) { /* save the connection for use later */ $this->twConnection = TwitterOAuth::__construct($consumer_key, $consumer_secret, $access_token, $access_token_secret); } } ?> Am i on the right trail here or i am barking up the wrong tree?
      I don´t need a complete solution, i just wonder if i am including the external library the right way.
      If not, then give me a few hint´s and i will figure it out.

      Thanks a bunch.

      /EyeDentify
×
×
  • Create New...