Jump to content

Recommended Posts

Posted

Hi, I'm having some troubles sorting pages by a number.

I have a field that counts views, but I created using text instead of integer. When I search all items and then do a filter like:

$pages->filter("sort=-views_count");

It sorts correctly, but if I do: 

$pages->find("sort=-views_count");

it doesn't sort correctly.

I tested it on the backend and the error exists, if the fieldtype is text the sort is something like: 

1411
14690
1478
14890
1502

if it's an integer the sort is correct.

Is possible to convert a text to an integer? from the backend the option doesn't exists.

Thanks

Posted (edited)

You would have to do it either manually or using the API. If it's only a few pages to deal with you could do it manually. Otherwise, use the API. Something like this.

  1. First, rename your current text field 'views_count' to something like 'views_count_old'
  2. Create an integer field called 'views_count'. Add it to your template (the one with pages requiring view counts)
  3. Backup your db
  4. Run the code below in a template file (doesn't matter which one) on a test install first if you can. If all goes well, run on your 'real' install
  5. If all went well, remove 'views_count_old' from the above template

@note: Written in browser and haven't tested but it should work. If you have thousands of pages you will want to do it in batches

foreach ($pages->find('template=template-with-views-count-field') as $p) {
        $p->of(false);
	$p->views_count = (int) $p->views_count_old;
	$p->save('views_count');
}
Edited by kongondo
added of(false) as per suggestion in post below
  • Like 5
  • 2 weeks later...
Posted

Thanks for that code snippet Kongondo.

It was throwing a fatal error for me, but I added $p->setOutputFormatting(false); and it worked a dream.

Here's my (fractionally) modified code:

foreach ($pages->find('template=template-with-views-count-field') as $p) {
	$p->setOutputFormatting(false);
        $p->views_count = (int) $p->views_count_old;
	$p->save('views_count');
}

Just thought I'd post feedback in case anyone else wants to use it and encounters the same fatal error :)

  • Like 2

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.
×
×
  • Create New...